ngx-extended-pdf-viewer
Version:
Embedding PDF files in your Angular application. Highly configurable viewer including the toolbar, sidebar, and all the features you're used to.
21 lines • 704 kB
JavaScript
/**
* @licstart The following is the entire license notice for the
* JavaScript code in this page
*
* Copyright 2024 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @licend The above is the entire license notice for the
* JavaScript code in this page
*/var t={641:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{NgxConsole:()=>NgxConsole});class NgxConsole{static ngxConsoleFilter=(t,e)=>!0;static log(t,e){NgxConsole.ngxConsoleFilter("log",t)&&(void 0!==e?console.log("%s",t,e):console.log(t))}static error(t,e){NgxConsole.ngxConsoleFilter("error",t)&&(void 0!==e?console.error("%s",t,e):console.error(t))}static warn(t,e){NgxConsole.ngxConsoleFilter("warn",t)&&(void 0!==e?console.warn("%s",t,e):console.warn(t))}static debug(t,e){NgxConsole.ngxConsoleFilter("debug",t)&&(void 0!==e?console.warn("%s",t,e):console.warn(t))}get ngxConsoleFilter(){return NgxConsole.ngxConsoleFilter}set ngxConsoleFilter(t){NgxConsole.ngxConsoleFilter=t}reset(){NgxConsole.ngxConsoleFilter=(t,e)=>!0}}},792:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{AnnotationStorage:()=>AnnotationStorage,PrintAnnotationStorage:()=>PrintAnnotationStorage,SerializableEmpty:()=>a});var i=e(292),n=e(310),s=e(651);const a=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#t=!1;#e=null;#i=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#i.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#i.get(t)}remove(t){this.#i.delete(t);0===this.#i.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#i.values())if(t instanceof n.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#i.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#i.set(t,e)}s&&this.#n();e instanceof n.AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#i.has(t)}getAll(){return this.#i.size>0?(0,i.objectFromMap)(this.#i):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#i.size}#n(){if(!this.#t){this.#t=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#t){this.#t=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#i.size)return a;const t=new Map,e=new s.MurmurHash3_64,i=[],r=Object.create(null);let o=!1;for(const[i,s]of this.#i){const a=s instanceof n.AnnotationEditor?s.serialize(!1,r):s;if(a){t.set(i,a);e.update(`${i}:${JSON.stringify(a)}`);o||=!!a.bitmap}}if(o)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:a}get editorStats(){let t=null;const e=new Map;for(const i of this.#i.values()){if(!(i instanceof n.AnnotationEditor))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:a}=s;e.has(a)||e.set(a,Object.getPrototypeOf(i).constructor);t||=Object.create(null);const r=t[a]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=r.get(t);if(!i){i=new Map;r.set(t,i)}const n=i.get(e)??0;i.set(e,n+1)}}for(const[i,n]of e)t[i]=n.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#e=null}get modifiedIds(){if(this.#e)return this.#e;const t=[];for(const e of this.#i.values())e instanceof n.AnnotationEditor&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}}class PrintAnnotationStorage extends AnnotationStorage{#s;constructor(t){super();const{map:e,hash:i,transfer:n}=t.serializable,s=structuredClone(e,n?{transfer:n}:null);this.#s={map:s,hash:i,transfer:n}}get print(){(0,i.unreachable)("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#s}get modifiedIds(){return(0,i.shadow)(this,"modifiedIds",{ids:new Set,hash:""})}}},925:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFWorker:()=>PDFWorker,build:()=>O,getDocument:()=>getDocument,version:()=>B});var i=e(292),n=e(792);class FontLoader{#a=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){if(!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.#a.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#a.has(t.loadedName)){(0,i.assert)(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:n,src:s,style:a}=t,r=new FontFace(n,s,a);this.addNativeFontFace(r);try{await r.load();this.#a.add(n);e?.(t)}catch{(0,i.warn)(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(r)}}else(0,i.unreachable)("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(n){(0,i.warn)(`Failed to load font '${e.family}': '${n}'.`);t.disableFontFace=!0;throw n}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return(0,i.shadow)(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;(i.isNodeJS||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0);return(0,i.shadow)(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,n={done:!1,complete:function completeRequest(){(0,i.assert)(!n.done,"completeRequest() cannot be called twice.");n.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(n);return n}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return(0,i.shadow)(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,n){return t.substring(0,e)+n+t.substring(e+i)}let n,s;const a=this._document.createElement("canvas");a.width=1;a.height=1;const r=a.getContext("2d");let o=0;const l=`lt${Date.now()}${this.loadTestFontId++}`;let h=this._loadTestFont;h=spliceString(h,976,l.length,l);const d=1482184792;let c=int32(h,16);for(n=0,s=l.length-3;n<s;n+=4)c=c-d+int32(l,n)|0;n<l.length&&(c=c-d+int32(l+"XXX",n)|0);h=spliceString(h,16,4,(0,i.string32)(c));const u=`@font-face {font-family:"${l}";src:${`url(data:font/opentype;base64,${btoa(h)});`}}`;this.insertRule(u);const p=this._document.createElement("div");p.style.visibility="hidden";p.style.width=p.style.height="10px";p.style.position="absolute";p.style.top=p.style.left="0px";for(const e of[t.loadedName,l]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;p.append(t)}this._document.body.append(p);!function isFontReady(t,e){if(++o>30){(0,i.warn)("Load test font never loaded.");e();return}r.font="30px "+t;r.fillText(".",0,20);r.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(l,(()=>{p.remove();e.complete()}))}}class FontFaceObject{constructor(t,{disableFontFace:e=!1,fontExtraProperties:i=!1,inspectFont:n=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e;this.fontExtraProperties=!0===i;this._inspectFont=n}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,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${(0,i.toBase64Util)(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const n=this.loadedName+"_path_"+e;let s;try{s=t.get(n)}catch(t){(0,i.warn)(`getPathGenerator - ignoring character: "${t}".`)}const a=new Path2D(s||"");this.fontExtraProperties||t.delete(n);return this.compiledGlyphs[e]=a}}var s=e(419);const a=1,r=2,o=1,l=2,h=3,d=4,c=5,u=6,p=7,g=8;function onFn(){}function wrapReason(t){if(t instanceof i.AbortException||t instanceof i.InvalidPDFException||t instanceof i.MissingPDFException||t instanceof i.PasswordException||t instanceof i.UnexpectedResponseException||t instanceof i.UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||(0,i.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new i.AbortException(t.message);case"InvalidPDFException":return new i.InvalidPDFException(t.message);case"MissingPDFException":return new i.MissingPDFException(t.message);case"PasswordException":return new i.PasswordException(t.message,t.code);case"UnexpectedResponseException":return new i.UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new i.UnknownErrorException(t.message,t.details)}return new i.UnknownErrorException(t.message,t.toString())}class MessageHandler{#r=new AbortController;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);i.addEventListener("message",this.#o.bind(this),{signal:this.#r.signal})}#o({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#l(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===a)i.resolve(t.data);else{if(t.callback!==r)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,n=t.sourceName,s=this.comObj;Promise.try(e,t.data).then((function(e){s.postMessage({sourceName:i,targetName:n,callback:a,callbackId:t.callbackId,data:e})}),(function(e){s.postMessage({sourceName:i,targetName:n,callback:r,callbackId:t.callbackId,reason:wrapReason(e)})}))}else t.streamId?this.#h(t):e(t.data)}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 n=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[n]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:n,data:e},i)}catch(t){s.reject(t)}return s.promise}sendWithStream(t,e,n,s){const a=this.streamId++,r=this.sourceName,l=this.targetName,h=this.comObj;return new ReadableStream({start:i=>{const n=Promise.withResolvers();this.streamControllers[a]={controller:i,startCall:n,pullCall:null,cancelCall:null,isClosed:!1};h.postMessage({sourceName:r,targetName:l,action:t,streamId:a,data:e,desiredSize:i.desiredSize},s);return n.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[a].pullCall=e;h.postMessage({sourceName:r,targetName:l,stream:u,streamId:a,desiredSize:t.desiredSize});return e.promise},cancel:t=>{(0,i.assert)(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[a].cancelCall=e;this.streamControllers[a].isClosed=!0;h.postMessage({sourceName:r,targetName:l,stream:o,streamId:a,reason:wrapReason(t)});return e.promise}},n)}#h(t){const e=t.streamId,n=this.sourceName,s=t.sourceName,a=this.comObj,r=this,o=this.actionHandler[t.action],l={enqueue(t,i=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=i;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}a.postMessage({sourceName:n,targetName:s,stream:d,streamId:e,chunk:t},r)},close(){if(!this.isCancelled){this.isCancelled=!0;a.postMessage({sourceName:n,targetName:s,stream:h,streamId:e});delete r.streamSinks[e]}},error(t){(0,i.assert)(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;a.postMessage({sourceName:n,targetName:s,stream:c,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};l.sinkCapability.resolve();l.ready=l.sinkCapability.promise;this.streamSinks[e]=l;Promise.try(o,t.data,l).then((function(){a.postMessage({sourceName:n,targetName:s,stream:g,streamId:e,success:!0})}),(function(t){a.postMessage({sourceName:n,targetName:s,stream:g,streamId:e,reason:wrapReason(t)})}))}#l(t){const e=t.streamId,n=this.sourceName,s=t.sourceName,a=this.comObj,r=this.streamControllers[e],m=this.streamSinks[e];switch(t.stream){case g:t.success?r.startCall.resolve():r.startCall.reject(wrapReason(t.reason));break;case p:t.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(t.reason));break;case u:if(!m){a.postMessage({sourceName:n,targetName:s,stream:p,streamId:e,success:!0});break}m.desiredSize<=0&&t.desiredSize>0&&m.sinkCapability.resolve();m.desiredSize=t.desiredSize;Promise.try(m.onPull||onFn).then((function(){a.postMessage({sourceName:n,targetName:s,stream:p,streamId:e,success:!0})}),(function(t){a.postMessage({sourceName:n,targetName:s,stream:p,streamId:e,reason:wrapReason(t)})}));break;case d:(0,i.assert)(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(t.chunk);break;case h:(0,i.assert)(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#d(r,e);break;case c:(0,i.assert)(r,"error should have stream controller");r.controller.error(wrapReason(t.reason));this.#d(r,e);break;case l:t.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(t.reason));this.#d(r,e);break;case o:if(!m)break;const f=wrapReason(t.reason);Promise.try(m.onCancel||onFn,f).then((function(){a.postMessage({sourceName:n,targetName:s,stream:l,streamId:e,success:!0})}),(function(t){a.postMessage({sourceName:n,targetName:s,stream:l,streamId:e,reason:wrapReason(t)})}));m.sinkCapability.reject(f);m.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#d(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#r?.abort();this.#r=null}}class BaseCanvasFactory{#c=!1;constructor({enableHWA:t=!1}){this.#c=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.#c})}}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){(0,i.unreachable)("Abstract method `_createCanvas` called.")}}class BaseCMapReaderFactory{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":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){(0,i.unreachable)("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await(0,s.fetchData)(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):(0,i.stringToBytes)(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,n,s){return"none"}destroy(t=!1){}}class BaseStandardFontDataFactory{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._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){(0,i.unreachable)("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await(0,s.fetchData)(t,"arraybuffer");return new Uint8Array(e)}}async function fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}const m="Fill",f="Stroke",b="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],n=e[3]-e[1],s=new Path2D;s.rect(e[0],e[1],i,n);t.clip(s)}class BaseShadingPattern{getPattern(){(0,i.unreachable)("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{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,n,a){let r;if(a===f||a===m){const o=e.current.getClippedPathBoundingBox(a,(0,s.getCurrentTransform)(t))||[0,0,0,0],l=Math.ceil(o[2]-o[0])||1,h=Math.ceil(o[3]-o[1])||1,d=e.cachedCanvases.getCanvas("pattern",l,h),c=d.context;c.clearRect(0,0,c.canvas.width,c.canvas.height);c.beginPath();c.rect(0,0,c.canvas.width,c.canvas.height);c.translate(-o[0],-o[1]);n=i.Util.transform(n,[1,0,0,1,o[0],o[1]]);c.transform(...e.baseTransform);this.matrix&&c.transform(...this.matrix);applyBoundingBox(c,this._bbox);c.fillStyle=this._createGradient(c);c.fill();r=t.createPattern(d.canvas,"no-repeat");const u=new DOMMatrix(n);r.setTransform(u)}else{applyBoundingBox(t,this._bbox);r=this._createGradient(t)}return r}}function drawTriangle(t,e,i,n,s,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;if(l[i+1]>l[n+1]){u=i;i=n;n=u;u=a;a=r;r=u}if(l[n+1]>l[s+1]){u=n;n=s;s=u;u=r;r=o;o=u}if(l[i+1]>l[n+1]){u=i;i=n;n=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[n]+e.offsetX)*e.scaleX,f=(l[n+1]+e.offsetY)*e.scaleY,b=(l[s]+e.offsetX)*e.scaleX,w=(l[s+1]+e.offsetY)*e.scaleY;if(g>=w)return;const v=h[a],y=h[a+1],A=h[a+2],x=h[r],E=h[r+1],S=h[r+2],P=h[o],_=h[o+1],C=h[o+2],T=Math.round(g),M=Math.round(w);let I,D,L,k,F,R,N,B;for(let t=T;t<=M;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);I=p-(p-m)*e;D=v-(v-x)*e;L=y-(y-E)*e;k=A-(A-S)*e}else{let e;e=t>w?1:f===w?0:(f-t)/(f-w);I=m-(m-b)*e;D=x-(x-P)*e;L=E-(E-_)*e;k=S-(S-C)*e}let e;e=t<g?0:t>w?1:(g-t)/(g-w);F=p-(p-b)*e;R=v-(v-P)*e;N=y-(y-_)*e;B=A-(A-C)*e;const i=Math.round(Math.min(I,F)),n=Math.round(Math.max(I,F));let s=c*t+4*i;for(let t=i;t<=n;t++){e=(I-t)/(I-F);e<0?e=0:e>1&&(e=1);d[s++]=D-(D-R)*e|0;d[s++]=L-(L-N)*e|0;d[s++]=k-(k-B)*e|0;d[s++]=255}}}function drawFigure(t,e,i){const n=e.coords,s=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(n.length/o)-1,h=o-1;for(a=0;a<l;a++){let e=a*o;for(let a=0;a<h;a++,e++){drawTriangle(t,i,n[e],n[e+1],n[e+o],s[e],s[e+1],s[e+o]);drawTriangle(t,i,n[e+o+1],n[e+1],n[e+o],s[e+o+1],s[e+1],s[e+o])}}break;case"triangles":for(a=0,r=n.length;a<r;a+=3)drawTriangle(t,i,n[a],n[a+1],n[a+2],s[a],s[a+1],s[a+2]);break;default:throw new Error("illegal figure")}}class MeshShadingPattern extends BaseShadingPattern{constructor(t){super();this._coords=t[2];this._colors=t[3];this._figures=t[4];this._bounds=t[5];this._bbox=t[7];this._background=t[8];this.matrix=null}_createMeshCanvas(t,e,i){const n=Math.floor(this._bounds[0]),s=Math.floor(this._bounds[1]),a=Math.ceil(this._bounds[2])-n,r=Math.ceil(this._bounds[3])-s,o=Math.min(Math.ceil(Math.abs(a*t[0]*1.1)),3e3),l=Math.min(Math.ceil(Math.abs(r*t[1]*1.1)),3e3),h=a/o,d=r/l,c={coords:this._coords,colors:this._colors,offsetX:-n,offsetY:-s,scaleX:1/h,scaleY:1/d},u=o+4,p=l+4,g=i.getCanvas("mesh",u,p),m=g.context,f=m.createImageData(o,l);if(e){const t=f.data;for(let i=0,n=t.length;i<n;i+=4){t[i]=e[0];t[i+1]=e[1];t[i+2]=e[2];t[i+3]=255}}for(const t of this._figures)drawFigure(f,t,c);m.putImageData(f,2,2);return{canvas:g.canvas,offsetX:n-2*h,offsetY:s-2*d,scaleX:h,scaleY:d}}getPattern(t,e,n,a){applyBoundingBox(t,this._bbox);let r;if(a===b)r=i.Util.singularValueDecompose2dScale((0,s.getCurrentTransform)(t));else{r=i.Util.singularValueDecompose2dScale(e.baseTransform);if(this.matrix){const t=i.Util.singularValueDecompose2dScale(this.matrix);r=[r[0]*t[0],r[1]*t[1]]}}const o=this._createMeshCanvas(r,a===b?null:this._background,e.cachedCanvases);if(a!==b){t.setTransform(...e.baseTransform);this.matrix&&t.transform(...this.matrix)}t.translate(o.offsetX,o.offsetY);t.scale(o.scaleX,o.scaleY);return t.createPattern(o.canvas,"no-repeat")}}class DummyShadingPattern extends BaseShadingPattern{getPattern(){return"hotpink"}}const w=1,v=2;class TilingPattern{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,n,s){this.operatorList=t[2];this.matrix=t[3];this.bbox=t[4];this.xstep=t[5];this.ystep=t[6];this.paintType=t[7];this.tilingType=t[8];this.color=e;this.ctx=i;this.canvasGraphicsFactory=n;this.baseTransform=s}createPatternCanvas(t){const{bbox:e,operatorList:n,paintType:a,tilingType:r,color:o,canvasGraphicsFactory:l}=this;let{xstep:h,ystep:d}=this;h=Math.abs(h);d=Math.abs(d);(0,i.info)("TilingType: "+r);const c=e[0],u=e[1],p=e[2],g=e[3],m=p-c,f=g-u,b=i.Util.singularValueDecompose2dScale(this.matrix),w=i.Util.singularValueDecompose2dScale(this.baseTransform),v=b[0]*w[0],y=b[1]*w[1];let A=m,x=f,E=!1,S=!1;const P=Math.ceil(h*v),_=Math.ceil(d*y);P>=Math.ceil(m*v)?A=h:E=!0;_>=Math.ceil(f*y)?x=d:S=!0;const C=this.getSizeAndScale(A,this.ctx.canvas.width,v),T=this.getSizeAndScale(x,this.ctx.canvas.height,y),M=t.cachedCanvases.getCanvas("pattern",C.size,T.size),I=M.context,D=l.createCanvasGraphics(I);D.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(D,a,o);I.translate(-C.scale*c,-T.scale*u);D.transform(C.scale,0,0,T.scale,0,0);I.save();this.clipBbox(D,c,u,p,g);D.baseTransform=(0,s.getCurrentTransform)(D.ctx);D.executeOperatorList(n);D.endDrawing();I.restore();if(E||S){const e=M.canvas;E&&(A=h);S&&(x=d);const i=this.getSizeAndScale(A,this.ctx.canvas.width,v),n=this.getSizeAndScale(x,this.ctx.canvas.height,y),s=i.size,a=n.size,r=t.cachedCanvases.getCanvas("pattern-workaround",s,a),o=r.context,l=E?Math.floor(m/h):0,p=S?Math.floor(f/d):0;for(let t=0;t<=l;t++)for(let i=0;i<=p;i++)o.drawImage(e,s*t,a*i,s,a,0,0,s,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:n.scale,offsetX:c,offsetY:u}}return{canvas:M.canvas,scaleX:C.scale,scaleY:T.scale,offsetX:c,offsetY:u}}getSizeAndScale(t,e,i){const n=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let s=Math.ceil(t*i);s>=n?s=n:i=s/t;return{scale:i,size:s}}clipBbox(t,e,i,n,a){const r=n-e,o=a-i;t.ctx.rect(e,i,r,o);t.current.updateRectMinMax((0,s.getCurrentTransform)(t.ctx),[e,i,n,a]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,n){const s=t.ctx,a=t.current;switch(e){case w:const t=this.ctx;s.fillStyle=t.fillStyle;s.strokeStyle=t.strokeStyle;a.fillColor=t.fillStyle;a.strokeColor=t.strokeStyle;break;case v:const r=i.Util.makeHexColor(n[0],n[1],n[2]);s.fillStyle=r;s.strokeStyle=r;a.fillColor=r;a.strokeColor=r;break;default:throw new i.FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,n,s){let a=n;if(s!==b){a=i.Util.transform(a,e.baseTransform);this.matrix&&(a=i.Util.transform(a,this.matrix))}const r=this.createPatternCanvas(e);let o=new DOMMatrix(a);o=o.translate(r.offsetX,r.offsetY);o=o.scale(1/r.scaleX,1/r.scaleY);const l=t.createPattern(r.canvas,"repeat");l.setTransform(o);return l}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:n,width:s,height:a,nonBlackColor:r=4294967295,inverseDecode:o=!1}){const l=i.FeatureTest.isLittleEndian?4278190080:255,[h,d]=o?[r,l]:[l,r],c=s>>3,u=7&s,p=t.length;n=new Uint32Array(n.buffer);let g=0;for(let i=0;i<a;i++){for(const i=e+c;e<i;e++){const i=e<p?t[e]:255;n[g++]=128&i?d:h;n[g++]=64&i?d:h;n[g++]=32&i?d:h;n[g++]=16&i?d:h;n[g++]=8&i?d:h;n[g++]=4&i?d:h;n[g++]=2&i?d:h;n[g++]=1&i?d:h}if(0===u)continue;const i=e<p?t[e++]:255;for(let t=0;t<u;t++)n[g++]=i&1<<7-t?d:h}return{srcPos:e,destPos:g}}const y=16;class CachedCanvases{constructor(t){this.canvasFactory=t;this.cache=Object.create(null)}getCanvas(t,e,i){let n;if(void 0!==this.cache[t]){n=this.cache[t];this.canvasFactory.reset(n,e,i)}else{n=this.canvasFactory.create(e,i);this.cache[t]=n}return n}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e);delete this.cache[t]}}}function drawImageAtIntegerCoords(t,e,i,n,a,r,o,l,h,d){const[c,u,p,g,m,f]=(0,s.getCurrentTransform)(t);if(0===u&&0===p){const s=o*c+m,b=Math.round(s),w=l*g+f,v=Math.round(w),y=(o+h)*c+m,A=Math.abs(Math.round(y)-b)||1,x=(l+d)*g+f,E=Math.abs(Math.round(x)-v)||1;t.setTransform(Math.sign(c),0,0,Math.sign(g),b,v);t.drawImage(e,i,n,a,r,0,0,A,E);t.setTransform(c,u,p,g,m,f);return[A,E]}if(0===c&&0===g){const s=l*p+m,b=Math.round(s),w=o*u+f,v=Math.round(w),y=(l+d)*p+m,A=Math.abs(Math.round(y)-b)||1,x=(o+h)*u+f,E=Math.abs(Math.round(x)-v)||1;t.setTransform(0,Math.sign(u),Math.sign(p),0,b,v);t.drawImage(e,i,n,a,r,0,0,E,A);t.setTransform(c,u,p,g,m,f);return[E,A]}t.drawImage(e,i,n,a,r,o,l,h,d);return[Math.hypot(c,u)*h,Math.hypot(p,g)*d]}class CanvasExtraState{constructor(t,e){this.alphaIsShape=!1;this.fontSize=0;this.fontSizeScale=1;this.textMatrix=i.IDENTITY_MATRIX;this.textMatrixScale=1;this.fontMatrix=i.FONT_IDENTITY_MATRIX;this.leading=0;this.x=0;this.y=0;this.lineX=0;this.lineY=0;this.charSpacing=0;this.wordSpacing=0;this.textHScale=1;this.textRenderingMode=i.TextRenderingMode.FILL;this.textRise=0;this.fillColor="#000000";this.strokeColor="#000000";this.patternFill=!1;this.patternStroke=!1;this.fillAlpha=1;this.strokeAlpha=1;this.lineWidth=1;this.activeSMask=null;this.transferMaps="none";this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);t.clipBox=this.clipBox.slice();return t}setCurrentPoint(t,e){this.x=t;this.y=e}updatePathMinMax(t,e,n){[e,n]=i.Util.applyTransform([e,n],t);this.minX=Math.min(this.minX,e);this.minY=Math.min(this.minY,n);this.maxX=Math.max(this.maxX,e);this.maxY=Math.max(this.maxY,n)}updateRectMinMax(t,e){const n=i.Util.applyTransform(e,t),s=i.Util.applyTransform(e.slice(2),t),a=i.Util.applyTransform([e[0],e[3]],t),r=i.Util.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,n[0],s[0],a[0],r[0]);this.minY=Math.min(this.minY,n[1],s[1],a[1],r[1]);this.maxX=Math.max(this.maxX,n[0],s[0],a[0],r[0]);this.maxY=Math.max(this.maxY,n[1],s[1],a[1],r[1])}updateScalingPathMinMax(t,e){i.Util.scaleMinMax(t,e);this.minX=Math.min(this.minX,e[0]);this.minY=Math.min(this.minY,e[1]);this.maxX=Math.max(this.maxX,e[2]);this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,n,s,a,r,o,l,h,d){const c=i.Util.bezierBoundingBox(e,n,s,a,r,o,l,h,d);d||this.updateRectMinMax(t,c)}getPathBoundingBox(t=m,e=null){const n=[this.minX,this.minY,this.maxX,this.maxY];if(t===f){e||(0,i.unreachable)("Stroke bounding box must include transform.");const t=i.Util.singularValueDecompose2dScale(e),s=t[0]*this.lineWidth/2,a=t[1]*this.lineWidth/2;n[0]-=s;n[1]-=a;n[2]+=s;n[3]+=a}return n}updateClipFromPath(){const t=i.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t;this.minX=1/0;this.minY=1/0;this.maxX=0;this.maxY=0}getClippedPathBoundingBox(t=m,e=null){return i.Util.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function putBinaryImageData(t,e){if(e instanceof ImageData){t.putImageData(e,0,0);return}const n=e.height,s=e.width,a=n%y,r=(n-a)/y,o=0===a?r:r+1,l=t.createImageData(s,y);let h,d=0;const c=e.data,u=l.data;let p,g,m,f;if(e.kind===i.ImageKind.GRAYSCALE_1BPP){const e=c.byteLength,n=new Uint32Array(u.buffer,0,u.byteLength>>2),f=n.length,b=s+7>>3,w=4294967295,v=i.FeatureTest.isLittleEndian?4278190080:255;for(p=0;p<o;p++){m=p<r?y:a;h=0;for(g=0;g<m;g++){const t=e-d;let i=0;const a=t>b?s:8*t-7,r=-8&a;let o=0,l=0;for(;i<r;i+=8){l=c[d++];n[h++]=128&l?w:v;n[h++]=64&l?w:v;n[h++]=32&l?w:v;n[h++]=16&l?w:v;n[h++]=8&l?w:v;n[h++]=4&l?w:v;n[h++]=2&l?w:v;n[h++]=1&l?w:v}for(;i<a;i++){if(0===o){l=c[d++];o=128}n[h++]=l&o?w:v;o>>=1}}for(;h<f;)n[h++]=0;t.putImageData(l,0,p*y)}}else if(e.kind===i.ImageKind.RGBA_32BPP){g=0;f=s*y*4;for(p=0;p<r;p++){u.set(c.subarray(d,d+f));d+=f;t.putImageData(l,0,g);g+=y}if(p<o){f=s*a*4;u.set(c.subarray(d,d+f));t.putImageData(l,0,g)}}else{if(e.kind!==i.ImageKind.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);m=y;f=s*m;for(p=0;p<o;p++){if(p>=r){m=a;f=s*m}h=0;for(g=f;g--;){u[h++]=c[d++];u[h++]=c[d++];u[h++]=c[d++];u[h++]=255}t.putImageData(l,0,p*y)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,n=e.width,s=i%y,a=(i-s)/y,r=0===s?a:a+1,o=t.createImageData(n,y);let l=0;const h=e.data,d=o.data;for(let e=0;e<r;e++){const i=e<a?y:s;({srcPos:l}=convertBlackAndWhiteToRGBA({src:h,srcPos:l,dest:d,width:n,height:i,nonBlackColor:0}));t.putImageData(o,0,e*y)}}function copyCtxState(t,e){const i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const n of i)void 0!==t[n]&&(e[n]=t[n]);if(void 0!==t.setLineDash){e.setLineDash(t.getLineDash());e.lineDashOffset=t.lineDashOffset}}function resetCtxToDefault(t){t.strokeStyle=t.fillStyle="#000000";t.fillRule="nonzero";t.globalAlpha=1;t.lineWidth=1;t.lineCap="butt";t.lineJoin="miter";t.miterLimit=10;t.globalCompositeOperation="source-over";t.font="10px sans-serif";if(void 0!==t.setLineDash){t.setLineDash([]);t.lineDashOffset=0}if(!i.isNodeJS){const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}}function getImageSmoothingEnabled(t,e){if(e)return!0;const n=i.Util.singularValueDecompose2dScale(t);n[0]=Math.fround(n[0]);n[1]=Math.fround(n[1]);const a=Math.fround((globalThis.devicePixelRatio||1)*s.PixelsPerInch.PDF_TO_CSS_UNITS);return n[0]<=a&&n[1]<=a}const A=["butt","round","square"],x=["miter","round","bevel"],E={},S={};class CanvasGraphics{constructor(t,e,i,n,s,{optionalContentConfig:a,markedContentStack:r=null},o,l){this.ctx=t;this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.stateStack=[];this.pendingClip=null;this.pendingEOFill=!1;this.res=null;this.xobjs=null;this.commonObjs=e;this.objs=i;this.canvasFactory=n;this.filterFactory=s;this.groupStack=[];this.processingType3=null;this.baseTransform=null;this.baseTransformStack=[];this.groupLevel=0;this.smaskStack=[];this.smaskCounter=0;this.tempSMask=null;this.suspendedCtx=null;this.contentVisible=!0;this.markedContentStack=r||[];this.optionalContentConfig=a;this.cachedCanvases=new CachedCanvases(this.canvasFactory);this.cachedPatterns=new Map;this.annotationCanvasMap=o;this.viewportScale=1;this.outputScaleX=1;this.outputScaleY=1;this.pageColors=l;this._cachedScaleForStroking=[-1,0];this._cachedGetSinglePixelWidth=null;this._cachedBitmapsMap=new Map}getObject(t,e=null){return"string"==typeof t?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:n=null}){const a=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;this.ctx.fillStyle=n||"#ffffff";this.ctx.fillRect(0,0,a,r);this.ctx.fillStyle=o;if(i){const t=this.cachedCanvases.getCanvas("transparent",a,r);this.compositeCtx=this.ctx;this.transparentCanvas=t.canvas;this.ctx=t.context;this.ctx.save();this.ctx.transform(...(0,s.getCurrentTransform)(this.compositeCtx))}this.ctx.save();resetCtxToDefault(this.ctx);if(t){this.ctx.transform(...t);this.outputScaleX=t[0];this.outputScaleY=t[0]}this.ctx.transform(...e.transform);this.viewportScale=e.scale;this.baseTransform=(0,s.getCurrentTransform)(this.ctx)}executeOperatorList(t,e,n,s){const a=t.argsArray,r=t.fnArray;let o=e||0;const l=a.length;if(l===o)return o;const h=l-o>10&&"function"==typeof n,d=h?Date.now()+15:0;let c=0;const u=this.commonObjs,p=this.objs;let g;for(;;){if(void 0!==s&&o===s.nextBreakPoint){s.breakIt(o,n);return o}g=r[o];if(g!==i.OPS.dependency)this[g].apply(this,a[o]);else for(const t of a[o]){const e=t.startsWith("g_")?u:p;if(!e.has(t)){e.get(t,n);return o}}o++;if(o===l)return o;if(h&&++c>10){if(Date.now()>d){n();return o}c=0}}}#u(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(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.#u();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.#p()}#p(){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??t.displayWidth,n=t.height??t.displayHeight;let s,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=n,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;if(r>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);r/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}s=this.cachedCanvases.getCanvas(d,e,i);a=s.context;a.clearRect(0,0,e,i);a.drawImage(t,0,0,l,h,0,0,e,i);t=s.canvas;l=e;h=i;d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:n,height:a}=t,r=this.current.fillColor,o=this.current.patternFill,l=(0,s.getCurrentTransform)(e);let h,d,c,u;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;d=JSON.stringify(o?l:[l.slice(0,4),r]);h=this._cachedBitmapsMap.get(e);if(!h){h=new Map;this._cachedBitmapsMap.set(e,h)}const i=h.get(d);if(i&&!o){return{canvas:i,offsetX:Math.round(Math.min(l[0],l[2])+l[4]),offsetY:Math.round(Math.min(l[1],l[3])+l[5])}}c=i}if(!c){u=this.cachedCanvases.getCanvas("maskCanvas",n,a);putBinaryImageMask(u.context,t)}let p=i.Util.transform(l,[1/n,0,0,-1/a,0,0]);p=i.Util.transform(p,[1,0,0,1,0,-a]);const[g,f,b,w]=i.Util.getAxialAlignedBoundingBox([0,0,n,a],p),v=Math.round(b-g)||1,y=Math.round(w-f)||1,A=this.cachedCanvases.getCanvas("fillCanvas",v,y),x=A.context,E=g,S=f;x.translate(-E,-S);x.transform(...p);if(!c){c=this._scaleImage(u.canvas,(0,s.getCurrentTransformInverse)(x));c=c.img;h&&o&&h.set(d,c)}x.imageSmoothingEnabled=getImageSmoothingEnabled((0,s.getCurrentTransform)(x),t.interpolate);drawImageAtIntegerCoords(x,c,0,0,c.width,c.height,0,0,n,a);x.globalCompositeOperation="source-in";const P=i.Util.transform((0,s.getCurrentTransformInverse)(x),[1,0,0,1,-E,-S]);x.fillStyle=o?r.getPattern(e,this,P,m):r;x.fillRect(0,0,n,a);if(h&&!o){this.cachedCanvases.delete("fillCanvas");h.set(d,A.canvas)}return{canvas:A.canvas,offsetX:Math.round(E),offsetY:Math.round(S)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=A[t]}setLineJoin(t){this.ctx.lineJoin=x[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;if(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,n=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;this.ctx=n.context;const a=this.ctx;a.setTransform(...(0,s.getCurrentTransform)(this.suspendedCtx));copyCtxState(this.suspendedCtx,a);!function mirrorContextOperations(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 ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function ctxScale(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function ctxTransform(t,i,n,s,a,r){e.transform(t,i,n,s,a,r);this.__originalTransform(t,i,n,s,a,r)};t.setTransform=function ctxSetTransform(t,i,n,s,a,r){e.setTransform(t,i,n,s,a,r);this.__originalSetTransform(t,i,n,s,a,r)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(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,n,s,a,r){e.bezierCurveTo(t,i,n,s,a,r);this.__originalBezierCurveTo(t,i,n,s,a,r)};t.rect=function(t,i,n,s){e.rect(t,i,n,s);this.__originalRect(t,i,n,s)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(a,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();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(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])}else 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,n){const s=n[0],a=n[1],r=n[2]-s,o=n[3]-a;if(0!==r&&0!==o){this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,s,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,n,s,a,r,o,l,h,d,c){let u=t.canvas,p=l-d,g=h-c;if(r){const e=i.Util.makeHexColor(...r);if(p<0||g<0||p+n>u.width||g+s>u.height){const t=this.cachedCanvases.getCanvas("maskExtension",n,s),i=t.context;i.drawImage(u,-p,-g);i.globalCompositeOperation="destination-atop";i.fillStyle=e;i.fillRect(0,0,n,s);i.globalCompositeOperation="source-over";u=t.canvas;p=g=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const i=new Path2D;i.rect(p,g,n,s);t.clip(i);t.globalCompositeOperation="destination-atop";t.fillStyle=e;t.fillRect(p,g,n,s);t.restore()}}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===a&&o?e.filter=this.filterFactory.addAlphaFilter(o):"Luminosity"===a&&(e.filter=this.filterFactory.addLuminosityFilter(o));const m=new Path2D;m.rect(l,h,n,s);e.clip(m);e.globalCompositeOperation="destination-in";e.drawImage(u,p,g,n,s,l,h,n,s);e.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}transform(t,e,i,n,s,a){this.ctx.transform(t,e,i,n,s,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,n){const a=this.ctx,r=this.current;let o,l,h=r.x,d=r.y;const c=(0,s.getCurrentTransform)(a),u=0===c[0]&&0===c[3]||0===c[1]&&0===c[2],p=u?n.slice(0):null;for(let n=0,s=0,g=t.length;n<g;n++)switch(0|t[n]){case i.OPS.rectangle:h=e[s++];d=e[s++];const t=e[s++],n=e[s++],g=h+t,m=d+n;a.moveTo(h,d);if(0===t||0===n)a.lineTo(g,m);else{a.lineTo(g,d);a.lineTo(g,m);a.lineTo(h,m)}u||r.updateRectMinMax(c,[h,d,g,m]);a.closePath();break;case i.OPS.moveTo:h=e[s++];d=e[s++];a.moveTo(h,d);u||r.updatePathMinMax(c,h,d);break;case i.OPS.lineTo:h=e[s++];d=e[s++];a.lineTo(h,d);u||r.updatePathMinMax(c,h,d);break;case i.OPS.curveTo:o=h;l=d;h=e[s+4];d=e[s+5];a.bezierCurveTo(e[s],e[s+1],e[s+2],e[s+3],h,d);r.updateCurvePathMinMax(c,o,l,e[s],e[s+1],e[s+2],e[s+3],h,d,p);s+=6;break;case i.OPS.curveTo2:o=h;l=d;a.bezierCurveTo(h,d,e[s],e[s+1],e[s+2],e[s+3]);r.updateCurvePathMinMax(c,o,l,h,d,e[s],e[s+1],e[s+2],e[s+3],p);h=e[s+2];d=e[s+3];s+=4;break;case i.OPS.curveTo3:o=h;l=d;h=e[s+2];d=e[s+3];a.bezierCurveTo(e[s],e[s+1],h,d,h,d);r.updateCurvePathMinMax(c,o,l,e[s],e[s+1],h,d,h,d,p);s+=4;break;case i.OPS.closePath:a.closePath()}u&&r.updateScalingPathMinMax(c,p);r.setCurrentPoint(h,d)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,i=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha;if(this.contentVisible)if("object"==typeof i&&i?.getPattern){e.save();e.strokeStyle=i.getPattern(e,this,(0,s.getCurrentTransformInverse)(e),f);this.rescaleAndStroke(!1);e.restore()}else this.rescaleAndStroke(!0);t&&this.consumePath(this.current.getClippedPathBoundingBox());e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath();this.stroke()}fill(t=!0){const e=this.ctx,i=this.current.fillColor;let n=!1;if(this.current.patternFill){e.save();e.fillStyle=i.getPattern(e,this,(0,s.getCurrentTransformInverse)(e),m);n=!0}const a=this.current.getClippedPathBoundingBox();if(this.contentVisible&&null!==a)if(this.pendingEOFill){e.fill("evenodd");this.pendingEOFill=!1}else e.fill();n&&e.restore();t&&this.consumePath(a)}eoFill(){this.pendingEOFill=!0;this.fill()}fillStroke(){this.fill(!1);this.stroke(!1);this.consumePath()}eoFillStroke(){this.pendingEOFill=!0;this.fillStroke()}closeFillStroke(){this.closePath();this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0;this.closePath();this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=E}eoClip(){this.pendingClip=S}beginText(){this.current.textMatrix=i.IDENTITY_MATRIX;this.current.textMatrixScale=1;this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(void 0===t){e.beginPath();return}const i=new Path2D,n=e.getTransform().invertSelf();for(const{transform:e,x:s,y:a,fontSize:r,path:o}of t)i.addPath(o,new DOMMatrix(e).preMultiplySelf(n).translate(s,a).scale(r,-r));e.clip(i);e.beginPath();delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const n=this.commonObjs.get(t),s=this.current;if(!n)throw new Error(`Can't find font for ${t}`);s.fontMatrix=n.fontMatrix||i.FONT_IDENTITY_MATRIX;0!==s.fontMatrix[0]&&0!==s.fontMatrix[3]||(0,i.warn)("Invalid font matrix for font "+t);if(e<0){e=-e;s.fontDirection=-1}else s.fontDirection=1;this.current.font=n;this.current.fontSize=e;if(n.isType3Font)return;const a=n.loadedName||"sans-serif",r=n.systemFontInfo?.css||`"${a}", ${n.fallbackName}`;let o="normal";n.black?o="900":n.bold&&(o="bold");const l=n.italic?"italic":"normal";let h=e;e<16?h=16:e>100&&(h=100);this.current.fontSizeScale=e/h;this.ctx.font=`${l} ${o} ${h}px ${r}`}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,n,s,a){this.current.textMatrix=[t,e,i,n,s,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)}#g(t,e,i){const n=new Path2D;n.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return n}paintChar(t,e,n,a,r){const o=this.ctx,l=this.current,h=l.font,d=l.textRenderingMode,c=l.fontSize/l.fontSizeScale,u=d&i.TextRenderingMode.FILL_STROKE_MASK,p=!!(d&i.TextRenderingMode.ADD_TO_PATH_FLAG),g=l.patternFill&&!h.missingFile,m=l.patternStroke&&!h.missingFile;let f;(h.disableFontFace||p||g||m)&&(f=h.getPathGenerator(this.commonObjs,t));if(h.disableFontFace||g||m){o.save();o.translate(e,n);o.scale(c,-c);if(u===i.TextRenderingMode.FILL||u===i.TextRenderingMode.FILL_STROKE)if(a){const t=o.getTransform();o.setTransform(...a);o.fill(this.#g(f,t,a))}else o.fill(f);if(u===i.TextRenderingMode.STROKE||u===i.TextRenderingMode.FILL_STROKE)if(r){const t=o.getTransform();o.setTransform(...r);o.stroke(this.#g(f,t,r))}else{o.lineWidth/=c;o.stroke(f)}o.restore()}else{u!==i.TextRenderingMode.FILL&&u!==i.TextRenderingMode.FILL_STROKE||o.fillText(t,e,n);u!==i.TextRenderingMode.STROKE&&u!==i.TextRenderingMode.FILL_STROKE||o.strokeText(t,e,n)}if(p){(this.pendingTextPaths||=[]).push({transform:(0,s.getCurrentTransform)(o),x:e,y:n,fontSize:c,path:f})}}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 n=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){n=!0;break}return(0,i.shadow)(this,"isFontSubpixelAAEnabled",n)}showText(t){const e=this.current,n=e.font;if(n.isType3Font)return this.showType3Text(t);const a=e.fontSize;if(0===a)return;const r=this.ctx,o=e.fontSizeScale,l=e.charSpacing,h=e.wordSpacing,d=e.fontDirection,c=e.textHScale*d,u=t.length,p=n.vertical,g=p?1:-1,b=n.defaultVMetrics,w=a*e.fontMatrix[0],v=e.textRenderingMode===i.TextRenderingMode.FILL&&!n.disableFontFace&&!e.patternFill;r.save();r.transform(...e.textMatrix);r.translate(e.x,e.y+e.textRise);d>0?r.scale(c,-1):r.scale(c,1);let y,A;if(e.patternFill){r.save();const t=e.fillColor.getPattern(r,this,(0,s.getCurrentTransformInverse)(r),m);y=(0,s.getCurrentTransform)(r);r.restore();r.fillStyle=t}if(e.patternStroke){r.save();const t=e.strokeColor.getPattern(r,this,(0,s.getCurrentTransformInverse)(r),f);A=(0,s.getCurrentTransform)(r);r.restore();r.strokeStyle=t}let x=e.lineWidth;const E=e.textMatrixScale;if(0===E||0===x){const t=e.textRenderingMode&i.TextRenderingMode.FILL_STROKE_MASK;t!==i.TextRenderingMode.STROKE&&t!==i.TextRenderingMode.FILL_STROKE||(x=this.getSinglePixelWidth())}else x/=E;if(1!==o){r.scale(o,o);x/=o}r.lineWidth=x;if(n.isInvalidPDFjsFont){const i=[];let n=0;for(const e of t){i.push(e.unicode);n+=e.width}r.fillText(i.join(""),0,0);e.x+=n*w*c;r.restore();this.compose();return}let S,P=0;for(S=0;S<u;++S){const e=t[S];if("number"==typeof e){P+=g*e*a/1e3;continue}let i=!1;const s=(e.isSpace?h:0)+l,c=e.fontChar,u=e.accent;let m,f,x=e.width;if(p){const t=e.vmetric||b,i=-(e.vmetric?t[1]:.5*x)*w,n=t[2]*w;x=t?-t[0]:x;m=i/o;f=(P+n)/o}else{m=P/o;f=0}if(n.remeasure&&x>0){const t=1e3*r.measureText(c).width/a*o;if(x<t&&this.isFontSubpixelAAEnabled){const e=x/t;i=!0;r.save();r.scale(e,1);m/=e}else x!==t&&(m+=(x-t)/2e3*a/o)}if(this.contentVisible&&(e.isInFont||n.missingFile))if(v&&!u)r.fillText(c,m,f);else{this.paintChar(c,m,f,y,A);if(u){const t=m+a*u.offset.x/o,e=f-a*u.offset.y/o;this.paintChar(u.fontChar,t,e,y,A)}}P+=p?x*w-s*d:x*w+s*d;i&&r.restore()}p?e.y-=P:e.x+=P*c;r.restore();this.compose()}showType3Text(t){const e=this.ctx,n=this.current,s=n.font,a=n.fontSize,r=n.fontDirection,o=s.vertical?1:-1,l=n.charSpacing,h=n.wordSpacing,d=n.textHScale*r,c=n.fontMatrix||i.FONT_IDENTITY_MATRIX,u=t.length;let p,g,m,f;if(!(n.textRenderingMode===i.TextRenderingMode.INVISIBLE)&&0!==a){this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null;e.save();e.transform(...n.textMatrix);e.translate(n.x,n.y);e.scale(d,r);for(p=0;p<u;++p){g=t[p];if("number"==typeof g){f=o*g*a/1e3;this.ctx.translate(f,0);n.x+=f*d;continue}const r=(g.isSpace?h:0)+l,u=s.charProcOperatorList[g.operatorListId];if(!u){(0,i.warn)(`Type3 character "${g.operatorListId}" is not available.`);continue}if(this.contentVisible){this.processingType3=g;this.save();e.scale(a,a);e.transform(...c);this.executeOperatorList(u);this.restore()}m=i.Util.applyTransform([g.width,0],c)[0]*a+r;e.translate(m,0);n.x+=m*d}e.restore();this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,i,n,s,a){this.ctx.rect(i,n,s-i,a-n);this.ctx.clip();this.endPath()}getColorN_Pattern(t){let e;if("TilingPattern"===t[0]){const i=t[1],n=this.baseTransform||(0,s.getCurrentTransform)(this.ctx),a={createCanvasGraphics:t=>new CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new TilingPattern(t,i,this.ctx,a,n)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments);this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments);this.current.patternFill=!0}setStrokeRGBColor(t,e,n){this.ctx.strokeStyle=this.current.strokeColor=i.Util.makeHexColor(t,e,n);this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e,n){this.ctx.fillStyle=this.current.fillColor=i.Util.makeHexColor(t,e,n);this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e=null){let i;if(this.cachedPatterns.has(t))i=this.cachedPatterns.get(t);else{i=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t));this.cachedPatterns.set(t,i)}e&&(i.matrix=e);return i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const n=this._getPattern(t);e.fillStyle=n.getPattern(e,this,(0,s.getCurrentTransformInverse)(e),b);const a=(0,s.getCurrentTransformInverse)(e);if(a){const{width:t,height:n}=e.canvas,[s,r,o,l]=i.Util.getAxialAlignedBoundingBox([0,0,t,n],a);this.ctx.fillRect(s,r,o-s,l-r)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){(0,i.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,i.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);t&&this.transform(...t);this.baseTransform=(0,s.getCurrentTransform)(this.ctx);if(e){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i);this.current.updateRectMinMax((0,s.getCurrentTransform)(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||(0,i.info)("TODO: Support non-isolated groups.");t.knockout&&(0,i.warn)("Knockout groups not supported.");const n=(0,s.getCurrentTransform)(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let a=i.Util.getAxialAlignedBoundingBox(t.bbox,(0,s.getCurrentTransform)(e));const r=[0,0,e.canvas.width,e.canvas.height];a=i.Util.intersect(a,r)||[0,0,0,0];const o=Math.floor(a[0]),l=Math.floor(a[1]),h=Math.max(Math.ceil(a[2])-o,1),d=Math.max(Math.ceil(a[3])-l,1);this.current.startNewPathAndClipBox([0,0,h,d]);let c="groupAt"+this.groupLevel;t.smask&&(c+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(c,h,d),p=u.context;p.translate(-o,-l);p.transform(...n);if(t.smask)this.smaskStack.push({canvas:u.canvas,context:p,offsetX:o,offsetY:l,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(o,l);e.save()}copyCtxState(e,p);this.ctx=p;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,n=this.groupStack.pop();this.ctx=n;this.ctx.imageSmoothingEnabled=!1;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=(0,s.getCurrentTransform)(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const n=i.Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(n)}}beginAnnotation(t,e,n,a,r){this.#u();resetCtxToDefault(this.ctx);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(e){const a=e[2]-e[0],o=e[3]-e[1];if(r&&this.annotationCanvasMap){(n=n.slice())[4]-=e[0];n[5]-=e[1];(e=e.slice())[0]=e[1]=0;e[2]=a;e[3]=o;const[r,l]=i.Util.singularValueDecompose2dScale((0,s.getCurrentTransform)(this.ctx)),{viewportScale:h}=this,d=Math.ceil(a*this.outputScaleX*h),c=Math.ceil(o*this.outputScaleY*h);this.annotationCanvas=this.canvasFactory.create(d,c);const{canvas:u,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,u);this.annotationCanvas.savedCtx=this.ctx;this.ctx=p;this.ctx.save();this.ctx.setTransform(r,0,0,-l,0,o*l);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath();this.ctx.rect(e[0],e[1],a,o);this.ctx.clip();this.ctx.beginPath()}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...n);this.transform(...a)}endAnnotation(){if(this.annotationCanvas){this.ctx.restore();this.#p();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,n=this.processingType3;if(n){void 0===n.compiled&&(n.compiled=function compileType3Glyph(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const n=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),s=e+1;let a,r,o,l=new Uint8Array(s*(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;c=0;if(0!==d[c]){l[0]=1;++u}for(r=1;r<e;r++){if(d[c]!==d[c+1]){l[r]=d[c]?2:1;++u}c++}if(0!==d[c]){l[r]=2;++u}for(a=1;a<i;a++){c=a*h;o=a*s;if(d[c-h]!==d[c]){l[o]=d[c]?1:8;++u}let t=(d[c]?4:0)+(d[c-h]?8:0);for(r=1;r<e;r++){t=(t>>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0);if(n[t]){l[o+r]=n[t];++u}c++}if(d[c-h]!==d[c]){l[o+r]=d[c]?2:4;++u}if(u>1e3)return null}c=h*(i-1);o=a*s;if(0!==d[c]){l[o]=8;++u}for(r=1;r<e;r++){if(d[c]!==d[c+1]){l[o+r]=d[c]?4:8;++u}c++}if(0!==d[c]){l[o+r]=4;++u}if(u>1e3)return null;const p=new Int32Array([0,s,-1,0,-s,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*s;const i=t+e;for(;t<i&&!l[t];)t++;if(t===i)continue;g.moveTo(t%s,a);const n=t;let r=l[t];do{const e=p[r];do{t+=e}while(!l[t]);const i=l[t];if(5!==i&&10!==i){r=i;l[t]=0}else{r=i&51*r>>4;l[t]&=r>>2|r<<2}g.lineTo(t%s,t/s|0);l[t]||--u}while(n!==t);--a}d=null;l=null;return function(t){t.save();t.scale(1/e,-1/i);t.translate(0,-i);t.fill(g);t.beginPath();t.restore()}}(t));if(n.compiled){n.compiled(i);return}}const s=this._createMaskCanvas(t),a=s.canvas;i.save();i.setTransform(1,0,0,1,0,0);i.drawImage(a,s.offsetX,s.offsetY);i.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,n=0,a=0,r,o){if(!this.contentVisible)return;t=this.getObject(t.data,t);const l=this.ctx;l.save();const h=(0,s.getCurrentTransform)(l);l.transform(e,n,a,r,0,0);const d=this._createMaskCanvas(t);l.setTransform(1,0,0,1,d.offsetX-h[4],d.offsetY-h[5]);for(let t=0,s=o.length;t<s;t+=2){const s=i.Util.transform(h,[e,n,a,r,o[t],o[t+1]]),[c,u]=i.Util.applyTransform([0,0],s);l.drawImage(d.canvas,c,u)}l.restore();this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,i=this.current.fillColor,n=this.current.patternFill;for(const a of t){const{data:t,width:r,height:o,transform:l}=a,h=this.cachedCanvases.getCanvas("maskCanvas",r,o),d=h.context;d.save();putBinaryImageMask(d,this.getObject(t,a));d.globalCompositeOperation="source-in";d.fillStyle=n?i.getPattern(d,this,(0,s.getCurrentTransformInverse)(e),m):i;d.fillRect(0,0,r,o);d.restore();e.save();e.transform(...l);e.scale(1,-1);drawImageAtIntegerCoords(e,h.canvas,0,0,r,o,0,-1,1,1);e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);e?this.paintInlineImageXObject(e):(0,i.warn)("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,n,s){if(!this.contentVisible)return;const a=this.getObject(t);if(!a){(0,i.warn)("Dependent image isn't ready yet");return}const r=a.width,o=a.height,l=[];for(let t=0,i=s.length;t<i;t+=2)l.push({transform:[e,0,0,n,s[t],s[t+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(a,l)}applyTransferMapsToCanvas(t){if("none"!==this.current.transferMaps){t.filter=this.current.transferMaps;t.drawImage(t.canvas,0,0);t.filter="none"}return t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return t.bitmap;const{bitmap:e,width:i,height:n}=t,s=this.cachedCanvases.getCanvas("inlineImage",i,n),a=s.context;a.filter=this.current.transferMaps;a.drawImage(e,0,0);a.filter="none";return s.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,n=t.height,a=this.ctx;this.save();if(!i.isNodeJS){const{filter:t}=a;"none"!==t&&""!==t&&(a.filter="none")}a.scale(1/e,-1/n);let r;if(t.bitmap)r=this.applyTransferMapsToBitmap(t);else if("function"==typeof HTMLElement&&t instanceof HTMLElement||!t.data)r=t;else{const i=this.cachedCanvases.getCanvas("inlineImage",e,n).context;putBinaryImageData(i,t);r=this.applyTransferMapsToCanvas(i)}const o=this._scaleImage(r,(0,s.getCurrentTransformInverse)(a));a.imageSmoothingEnabled=getImageSmoothingEnabled((0,s.getCurrentTransform)(a),t.interpolate);drawImageAtIntegerCoords(a,o.img,0,0,o.paintWidth,o.paintHeight,0,-n,e,n);this.compose();this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.ctx;let n;if(t.bitmap)n=t.bitmap;else{const e=t.width,i=t.height,s=this.cachedCanvases.getCanvas("inlineImage",e,i).context;putBinaryImageData(s,t);n=this.applyTransferMapsToCanvas(s)}for(const t of e){i.save();i.transform(...t.transform);i.scale(1,-1);drawImageAtIntegerCoords(i,n,t.x,t.y,t.w,t.h,0,-1,1,1);i.restore()}this.compose()}paintSolidColorImageMask(){if(this.contentVisible){this.ctx.fillRect(0,0,1,1);this.compose()}}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){"OC"===t?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0});this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop();this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath();this.pendingClip||this.compose(t);const i=this.ctx;if(this.pendingClip){e||(this.pendingClip===S?i.clip("evenodd"):i.clip());this.pendingClip=null}this.current.startNewPathAndClipBox(this.current.clipBox);i.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=(0,s.getCurrentTransform)(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),i=Math.hypot(t[0],t[2]),n=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,n)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:i,c:n,d:s}=this.ctx.getTransform();let a,r;if(0===i&&0===n){const i=Math.abs(e),n=Math.abs(s);if(i===n)if(0===t)a=r=1/i;else{const e=i*t;a=r=e<1?1/e:1}else if(0===t){a=1/i;r=1/n}else{const e=i*t,s=n*t;a=e<1?1/e:1;r=s<1?1/s:1}}else{const o=Math.abs(e*s-i*n),l=Math.hypot(e,i),h=Math.hypot(n,s);if(0===t){a=h/o;r=l/o}else{const e=t*o;a=h>e?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,[n,s]=this.getScaleForStroking();e.lineWidth=i||1;if(1===n&&1===s){e.stroke();return}const a=e.getLineDash();t&&e.save();e.scale(n,s);if(a.length>0){const t=Math.max(n,s);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 i.OPS)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[i.OPS[t]]=CanvasGraphics.prototype[t]);var P=e(164);class Metadata{#m;#f;constructor({parsedData:t,rawData:e}){this.#m=t;this.#f=e}getRaw(){return this.#f}get(t){return this.#m.get(t)??null}getAll(){return(0,i.objectFromMap)(this.#m)}has(t){return this.#m.has(t)}}var _=e(651);const C=Symbol("INTERNAL");class OptionalContentGroup{#b=!1;#w=!1;#v=!1;#y=!0;constructor(t,{name:e,intent:n,usage:s,rbGroups:a}){this.#b=!!(t&i.RenderingIntentFlag.DISPLAY);this.#w=!!(t&i.RenderingIntentFlag.PRINT);this.name=e;this.intent=n;this.usage=s;this.rbGroups=a}get visible(){if(this.#v)return this.#y;if(!this.#y)return!1;const{print:t,view:e}=this.usage;return this.#b?"OFF"!==e?.viewState:!this.#w||"OFF"!==t?.printState}_setVisible(t,e,n=!1){t!==C&&(0,i.unreachable)("Internal method `_setVisible` called.");this.#v=n;this.#y=e}}class OptionalContentConfig{#A=null;#x=new Map;#E=null;#S=null;constructor(t,e=i.RenderingIntentFlag.DISPLAY){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#S=t.order;for(const i of t.groups)this.#x.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#x.values())t._setVisible(C,!1);for(const e of t.on)this.#x.get(e)._setVisible(C,!0);for(const e of t.off)this.#x.get(e)._setVisible(C,!1);this.#E=this.getHash()}}#P(t){const e=t.length;if(e<2)return!0;const n=t[0];for(let s=1;s<e;s++){const e=t[s];let a;if(Array.isArray(e))a=this.#P(e);else{if(!this.#x.has(e)){(0,i.warn)(`Optional content group not found: ${e}`);return!0}a=this.#x.get(e).visible}switch(n){case"And":if(!a)return!1;break;case"Or":if(a)return!0;break;case"Not":return!a;default:return!0}}return"And"===n}isVisible(t){if(0===this.#x.size)return!0;if(!t){(0,i.info)("Optional content group not defined.");return!0}if("OCG"===t.type){if(!this.#x.has(t.id)){(0,i.warn)(`Optional content group not found: ${t.id}`);return!0}return this.#x.get(t.id).visible}if("OCMD"===t.type){if(t.expression)return this.#P(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#x.has(e)){(0,i.warn)(`Optional content group not found: ${e}`);return!0}if(this.#x.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#x.has(e)){(0,i.warn)(`Optional content group not found: ${e}`);return!0}if(!this.#x.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#x.has(e)){(0,i.warn)(`Optional content group not found: ${e}`);return!0}if(!this.#x.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#x.has(e)){(0,i.warn)(`Optional content group not found: ${e}`);return!0}if(this.#x.get(e).visible)return!1}return!0}(0,i.warn)(`Unknown optional content policy ${t.policy}.`);return!0}(0,i.warn)(`Unknown group type ${t.type}.`);return!0}setVisibility(t,e=!0,n=!0){const s=this.#x.get(t);if(s){if(n&&e&&s.rbGroups.length)for(const e of s.rbGroups)for(const i of e)i!==t&&this.#x.get(i)?._setVisible(C,!1,!0);s._setVisible(C,!!e,!0);this.#A=null}else(0,i.warn)(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(const n of t){switch(n){case"ON":case"OFF":case"Toggle":i=n;continue}const t=this.#x.get(n);if(t)switch(i){case"ON":this.setVisibility(n,!0,e);break;case"OFF":this.setVisibility(n,!1,e);break;case"Toggle":this.setVisibility(n,!t.visible,e)}}this.#A=null}get hasInitialVisibility(){return null===this.#E||this.getHash()===this.#E}getOrder(){return this.#x.size?this.#S?this.#S.slice():[...this.#x.keys()]:null}getGroups(){return this.#x.size>0?(0,i.objectFromMap)(this.#x):null}getGroup(t){return this.#x.get(t)||null}getHash(){if(null!==this.#A)return this.#A;const t=new _.MurmurHash3_64;for(const[e,i]of this.#x)t.update(`${e}:${i.visible}`);return this.#A=t.hexdigest()}}class PDFDataTransportStream{constructor(t,{disableRange:e=!1,disableStream:n=!1}){(0,i.assert)(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:a,progressiveDone:r,contentDispositionFilename:o}=t;this._queuedChunks=[];this._progressiveDone=r;this._contentDispositionFilename=o;if(a?.length>0){const t=a instanceof Uint8Array&&a.byteLength===a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t;this._isStreamingSupported=!n;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 n=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(n):this._queuedChunks.push(n);else{const e=this._rangeReaders.some((function(e){if(e._begin!==t)return!1;e._enqueue(n);return!0}));(0,i.assert)(e,"_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(){(0,i.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,i=!1,n=null){this._stream=t;this._done=i||!1;this._filename=(0,s.isPdfFile)(n)?n: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){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else 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();this._requests.push(t);return 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 PDFDataTransportStreamRangeReader{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;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return 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 createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const n=e[t];void 0!==n&&i.append(t,n)}return i}function getResponseOrigin(t){try{return new URL(t).origin}catch{}return null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:n}){const s={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return s;s.suggestedLength=a;if(a<=2*i)return s;if(n||!e)return s;if("bytes"!==t.get("Accept-Ranges"))return s;if("identity"!==(t.get("Content-Encoding")||"identity"))return s;s.allowRangeRequests=!0;return s}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,n=toParamRegExp("filename\\*","i").exec(t);if(n){n=n[1];let t=rfc2616unquote(n);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}n=function rfc2231getparam(t){const e=[];let i;const n=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,n,s]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[n,s]}const s=[];for(let t=0;t<e.length&&t in e;++t){let[i,n]=e[t];n=rfc2616unquote(n);if(i){n=unescape(n);0===t&&(n=rfc5987decode(n))}s.push(n)}return s.join("")}(t);if(n)return fixupEncoding(rfc2047decode(n));n=toParamRegExp("filename","i").exec(t);if(n){n=n[1];let t=rfc2616unquote(n);t=rfc2047decode(t);return fixupEncoding(t)}function toParamRegExp(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function textdecode(t,n){if(t){if(!/^[\x00-\xFF]+$/.test(n))return n;try{const s=new TextDecoder(t,{fatal:!0}),a=(0,i.stringToBytes)(n);n=s.decode(a);e=!1}catch{}}return n}function fixupEncoding(t){if(e&&/[\x80-\xff]/.test(t)){t=textdecode("utf-8",t);e&&(t=textdecode("iso-8859-1",t))}return t}function rfc2616unquote(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const i=e[t].indexOf('"');if(-1!==i){e[t]=e[t].slice(0,i);e.length=t+1}e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function rfc5987decode(t){const e=t.indexOf("'");return-1===e?t:textdecode(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function rfc2047decode(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(t,e,i,n){if("q"===i||"Q"===i)return textdecode(e,n=(n=n.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(t,e){return String.fromCharCode(parseInt(e,16))})));try{n=atob(n)}catch{}return textdecode(e,n)}))}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if((0,s.isPdfFile)(t))return t}return null}function createResponseStatusError(t,e){return 404===t||0===t&&e.startsWith("file:")?new i.MissingPDFException('Missing PDF "'+e+'".'):new i.UnexpectedResponseException(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t)}function validateResponseStatus(t){return 200===t||206===t}function createFetchOptions(t,e,i){return{method:"GET",headers:t,signal:i.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function getArrayBuffer(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;(0,i.warn)(`getArrayBuffer - unexpected data format: ${t}`);return new Uint8Array(t).buffer}class PDFFetchStream{_responseOrigin=null;constructor(t){this.source=t;this.isHttp=/^https?:/i.test(t.url);this.headers=createHeaders(this.isHttp,t.httpHeaders);this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){(0,i.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once.");this._fullRequestReader=new PDFFetchStreamReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFFetchStreamRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFFetchStreamReader{constructor(t){this._stream=t;this._reader=null;this._loaded=0;this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1;this._contentLength=e.length;this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._abortController=new AbortController;this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;const n=new Headers(t.headers),s=e.url;fetch(s,createFetchOptions(n,this._withCredentials,this._abortController)).then((e=>{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,s);this._reader=e.body.getReader();this._headersCapability.resolve();const n=e.headers,{allowRangeRequests:a,suggestedLength:r}=validateRangeRequestCapabilities({responseHeaders:n,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=a;this._contentLength=r||this._contentLength;this._filename=extractFilenameFromHeader(n);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new i.AbortException("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();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,i){this._stream=t;this._reader=null;this._loaded=0;const n=t.source;this._withCredentials=n.withCredentials||!1;this._readCapability=Promise.withResolvers();this._isStreamingSupported=!n.disableStream;this._abortController=new AbortController;const s=new Headers(t.headers);s.append("Range",`bytes=${e}-${i-1}`);const a=n.url;fetch(a,createFetchOptions(s,this._withCredentials,this._abortController)).then((e=>{const i=getResponseOrigin(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,a);this._readCapability.resolve();this._reader=e.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();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(this.isHttp,e);this.withCredentials=i||!1;this.currXhrId=0;this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,n=this.currXhrId++,s=this.pendingRequests[n]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);s.expectedStatus=206}else s.expectedStatus=200;e.responseType="arraybuffer";(0,i.assert)(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>{t.onError(e.status)};e.onreadystatechange=this.onStateChange.bind(this,n);e.onprogress=this.onProgress.bind(this,n);s.onHeadersReceived=t.onHeadersReceived;s.onDone=t.onDone;s.onError=t.onError;s.onProgress=t.onProgress;e.send(null);return n}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const n=this.pendingRequests[t];if(!n)return;const s=n.xhr;if(s.readyState>=2&&n.onHeadersReceived){n.onHeadersReceived();delete n.onHeadersReceived}if(4!==s.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===s.status&&this.isHttp){n.onError(s.status);return}const a=s.status||200;if(!(200===a&&206===n.expectedStatus)&&a!==n.expectedStatus){n.onError(s.status);return}const r=function network_getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:(0,i.stringToBytes)(e).buffer}(s);if(206===a){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)n.onDone({begin:parseInt(e[1],10),chunk:r});else{(0,i.warn)('Missing or invalid "Content-Range" header.');n.onError(0)}}else r?n.onDone({begin:0,chunk:r}):n.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 PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(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(){(0,i.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const i=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);i.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;this._url=e.url;this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});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);this._manager._responseOrigin=getResponseOrigin(e.responseURL);const i=e.getAllResponseHeaders(),n=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]})):[]),{allowRangeRequests:s,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:n,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});s&&(this._isRangeSupported=!0);this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(n);this._isRangeSupported&&this._manager.abortRequest(t);this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);this._done=!0;if(!(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=createResponseStatusError(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(){await this._headersCapability.promise;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();this._requests.push(t);return 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 PDFNetworkStreamRangeRequestReader{constructor(t,e,i){this._manager=t;this._url=t.url;this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._requests=[];this._queuedChunk=null;this._done=!1;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_onHeadersReceived(){const t=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(t!==this._manager._responseOrigin){this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`);this._onError(0)}}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else 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??=createResponseStatusError(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;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return 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 T=/^[a-z][a-z0-9\-+.]+:/i;class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrlOrPath(t){if(T.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);(0,i.assert)("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){(0,i.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{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();const n=process.getBuiltinModule("fs");n.promises.lstat(this._url).then((t=>{this._contentLength=t.size;this._setReadableStream(n.createReadStream(this._url));this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new i.MissingPDFException(`Missing PDF "${this._url}".`));this._storedError=t;this._headersCapability.reject(t)}))}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._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{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 i.AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{constructor(t,e,i){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=Promise.withResolvers();const n=t.source;this._isStreamingSupported=!n.disableStream;const s=process.getBuiltinModule("fs");this._setReadableStream(s.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});return{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)}}var M=e(814),I=e(50);const D=65536,L=i.isNodeJS?class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}:class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}},k=i.isNodeJS?class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return fetchData(t)}}:DOMCMapReaderFactory,F=i.isNodeJS?class NodeFilterFactory extends BaseFilterFactory{}:class DOMFilterFactory extends BaseFilterFactory{#_;#C;#T;#M;#I;#D;#L=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#M=t;this.#I=e}get#k(){return this.#C||=new Map}get#F(){return this.#D||=new Map}get#R(){if(!this.#T){const t=this.#I.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.#I.createElementNS(s.SVG_NS,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#T=this.#I.createElementNS(s.SVG_NS,"defs");t.append(i);i.append(this.#T);this.#I.body.append(t)}return this.#T}#N(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 n=i.join(",");return[n,n,n]}const[e,i,n]=t,s=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++){s[t]=e[t]/255;a[t]=i[t]/255;r[t]=n[t]/255}return[s.join(","),a.join(","),r.join(",")]}#B(t){if(void 0===this.#_){this.#_="";const t=this.#I.URL;t!==this.#I.baseURI&&((0,s.isDataScheme)(t)?(0,i.warn)('#createUrl: ignore "data:"-URL for performance reasons.'):this.#_=t.split("#",1)[0])}return`url(${this.#_}#${t})`}addFilter(t){if(!t)return"none";let e=this.#k.get(t);if(e)return e;const[i,n,s]=this.#N(t),a=1===t.length?i:`${i}${n}${s}`;e=this.#k.get(a);if(e){this.#k.set(t,e);return e}const r=`g_${this.#M}_transfer_map_${this.#L++}`,o=this.#B(r);this.#k.set(t,o);this.#k.set(a,o);const l=this.#O(r);this.#V(i,n,s,l);return o}addHCMFilter(t,e){const n=`${t}-${e}`,s="base";let a=this.#F.get(s);if(a?.key===n)return a.url;if(a){a.filter?.remove();a.key=n;a.url="none";a.filter=null}else{a={key:n,url:"none",filter:null};this.#F.set(s,a)}if(!t||!e)return a.url;const r=this.#H(t);t=i.Util.makeHexColor(...r);const o=this.#H(e);e=i.Util.makeHexColor(...o);this.#R.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return a.url;const l=new Array(256);for(let t=0;t<=255;t++){const e=t/255;l[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const h=l.join(","),d=`g_${this.#M}_hcm_filter`,c=a.filter=this.#O(d);this.#V(h,h,h,c);this.#z(c);const getSteps=(t,e)=>{const i=r[t]/255,n=o[t]/255,s=new Array(e+1);for(let t=0;t<=e;t++)s[t]=i+t/e*(n-i);return s.join(",")};this.#V(getSteps(0,5),getSteps(1,5),getSteps(2,5),c);a.url=this.#B(d);return a.url}addAlphaFilter(t){let e=this.#k.get(t);if(e)return e;const[i]=this.#N([t]),n=`alpha_${i}`;e=this.#k.get(n);if(e){this.#k.set(t,e);return e}const s=`g_${this.#M}_alpha_map_${this.#L++}`,a=this.#B(s);this.#k.set(t,a);this.#k.set(n,a);const r=this.#O(s);this.#U(i,r);return a}addLuminosityFilter(t){let e,i,n=this.#k.get(t||"luminosity");if(n)return n;if(t){[e]=this.#N([t]);i=`luminosity_${e}`}else i="luminosity";n=this.#k.get(i);if(n){this.#k.set(t,n);return n}const s=`g_${this.#M}_luminosity_map_${this.#L++}`,a=this.#B(s);this.#k.set(t,a);this.#k.set(i,a);const r=this.#O(s);this.#j(r);t&&this.#U(e,r);return a}addHighlightHCMFilter(t,e,i,n,s){const a=`${e}-${i}-${n}-${s}`;let r=this.#F.get(t);if(r?.key===a)return r.url;if(r){r.filter?.remove();r.key=a;r.url="none";r.filter=null}else{r={key:a,url:"none",filter:null};this.#F.set(t,r)}if(!e||!i)return r.url;const[o,l]=[e,i].map(this.#H.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]=[n,s].map(this.#H.bind(this));d<h&&([h,d,c,u]=[d,h,u,c]);this.#R.style.color="";const getSteps=(t,e,i)=>{const n=new Array(256),s=(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*s),i=a+t*r;for(let t=o;t<=e;t++)n[t]=i;o=e+1}for(let t=o;t<256;t++)n[t]=n[o-1];return n.join(",")},p=`g_${this.#M}_hcm_${t}_filter`,g=r.filter=this.#O(p);this.#z(g);this.#V(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);r.url=this.#B(p);return r.url}destroy(t=!1){if(!t||!this.#D?.size){this.#T?.parentNode.parentNode.remove();this.#T=null;this.#C?.clear();this.#C=null;this.#D?.clear();this.#D=null;this.#L=0}}#j(t){const e=this.#I.createElementNS(s.SVG_NS,"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)}#z(t){const e=this.#I.createElementNS(s.SVG_NS,"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)}#O(t){const e=this.#I.createElementNS(s.SVG_NS,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#R.append(e);return e}#W(t,e,i){const n=this.#I.createElementNS(s.SVG_NS,e);n.setAttribute("type","discrete");n.setAttribute("tableValues",i);t.append(n)}#V(t,e,i,n){const a=this.#I.createElementNS(s.SVG_NS,"feComponentTransfer");n.append(a);this.#W(a,"feFuncR",t);this.#W(a,"feFuncG",e);this.#W(a,"feFuncB",i)}#U(t,e){const i=this.#I.createElementNS(s.SVG_NS,"feComponentTransfer");e.append(i);this.#W(i,"feFuncA",t)}#H(t){this.#R.style.color=t;return(0,s.getRGB)(getComputedStyle(this.#R).getPropertyValue("color"))}},R=i.isNodeJS?class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return fetchData(t)}}:DOMStandardFontDataFactory;function getDocument(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new PDFDocumentLoadingTask,{docId:n}=e,a=t.url?function getUrlProp(t,e){if(t instanceof URL)return t.href;try{return e?new URL(t,window.location.origin+e).href:new URL(t,window.location).href}catch(e){if(i.isNodeJS&&"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,t.baseHref):null,r=t.data?function getDataProp(t){if(i.isNodeJS&&"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(0,i.stringToBytes)(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,o=t.httpHeaders||null,l=!0===t.withCredentials,h=t.password??null,d=t.range instanceof PDFDataRangeTransport?t.range:null,c=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:D;let u=t.worker instanceof PDFWorker?t.worker:null;const p=t.verbosity,g="string"!=typeof t.docBaseUrl||(0,s.isDataScheme)(t.docBaseUrl)?null:t.docBaseUrl,m="function"==typeof t.cMapUrl?t.cMapUrl():"string"==typeof t.cMapUrl?t.cMapUrl:null,f=!1!==t.cMapPacked,b=t.CMapReaderFactory||k,w="function"==typeof t.standardFontDataUrl?t.standardFontDataUrl():"string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,v=t.StandardFontDataFactory||R,y=!0!==t.stopAtErrors,A=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,x=!1!==t.isEvalSupported,E="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!i.isNodeJS,S="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!i.isNodeJS&&(i.FeatureTest.platform.isFirefox||!globalThis.chrome),_=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,C="boolean"==typeof t.disableFontFace?t.disableFontFace:i.isNodeJS,T=!0===t.fontExtraProperties,M=!0===t.enableXfa,I=t.ownerDocument||globalThis.document,N=!0===t.disableRange,B=!0===t.disableStream,O=!0===t.disableAutoFetch,V=!0===t.pdfBug,H=t.CanvasFactory||L,z=t.FilterFactory||F,U=!0===t.enableHWA,j=d?d.length:t.length??NaN,W="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!i.isNodeJS&&!C,$="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:b===DOMCMapReaderFactory&&v===DOMStandardFontDataFactory&&m&&w&&(0,s.isValidFetchUrl)(m,document.baseURI)&&(0,s.isValidFetchUrl)(w,document.baseURI);(0,i.setVerbosityLevel)(p);const G={canvasFactory:new H({ownerDocument:I,enableHWA:U}),filterFactory:new z({docId:n,ownerDocument:I}),cMapReaderFactory:$?null:new b({baseUrl:m,isCompressed:f}),standardFontDataFactory:$?null:new v({baseUrl:w})};if(!u){const i={verbosity:p,port:P.GlobalWorkerOptions.workerPort,cspPolicyService:t.cspPolicyService};u=i.port?PDFWorker.fromPort(i):new PDFWorker(i);e._worker=u}const q={docId:n,apiVersion:"4.10.708",data:r,password:h,disableAutoFetch:O,rangeChunkSize:c,length:j,docBaseUrl:g,enableXfa:M,evaluatorOptions:{maxImageSize:A,disableFontFace:C,ignoreErrors:y,isEvalSupported:x,isOffscreenCanvasSupported:E,isImageDecoderSupported:S,canvasMaxAreaInBytes:_,fontExtraProperties:T,useSystemFonts:W,cMapUrl:$?m:null,standardFontDataUrl:$?w:null}},X={disableFontFace:C,fontExtraProperties:T,ownerDocument:I,pdfBug:V,styleElement:null,loadingParams:{disableAutoFetch:O,enableXfa:M}};u.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const t=u.messageHandler.sendWithPromise("GetDocRequest",q,r?[r.buffer]:null);let h;if(d)h=new PDFDataTransportStream(d,{disableRange:N,disableStream:B});else if(!r){if(!a)throw new Error("getDocument - no `url` parameter provided.");let t;if(i.isNodeJS)if((0,s.isValidFetchUrl)(a)){if("undefined"==typeof fetch||"undefined"==typeof Response||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");t=PDFFetchStream}else t=PDFNodeStream;else t=(0,s.isValidFetchUrl)(a)?PDFFetchStream:PDFNetworkStream;h=new t({url:a,length:j,httpHeaders:o,withCredentials:l,rangeChunkSize:c,disableRange:N,disableStream:B})}return t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const i=new MessageHandler(n,t,u.port),s=new WorkerTransport(i,e,h,X,G);e._transport=s;i.send("Ready",null)}))})).catch(e._capability.reject);return e}function isRefProxy(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class PDFDocumentLoadingTask{static#M=0;constructor(){this._capability=Promise.withResolvers();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#M++;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){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}}class PDFDataRangeTransport{constructor(t,e,i=!1,n=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=n;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){(0,i.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{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(0,i.shadow)(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 PDFPageProxy{#$=null;#G=!1;constructor(t,e,i,n=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=n?new s.StatTimer:null;this._pdfBug=n;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;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:n=0,dontFlip:a=!1}={}){return new s.PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:a})}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(0,i.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:n="display",annotationMode:s=i.AnnotationMode.ENABLE,transform:a=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(n,s,d,c),{renderingIntent:p,cacheKey:g}=u;this.#G=!1;this.#q();o||=this._transport.getOptionalContentConfig(p);let m=this._intentStates.get(g);if(!m){m=Object.create(null);this._intentStates.set(g,m)}if(m.streamReaderCancelTimeout){clearTimeout(m.streamReaderCancelTimeout);m.streamReaderCancelTimeout=null}const f=!!(p&i.RenderingIntentFlag.PRINT);if(!m.displayReadyCapability){m.displayReadyCapability=Promise.withResolvers();m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(u)}const complete=t=>{m.renderTasks.delete(b);(this._maybeCleanupAfterRender||f)&&(this.#G=!0);this.#X(!f);if(t){b.capability.reject(t);this._abortOperatorList({intentState:m,reason:t instanceof Error?t:new Error(t)})}else b.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},b=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:a,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,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(b);const w=b.task;Promise.all([m.displayReadyCapability.promise,o]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:t,optionalContentConfig:e});b.operatorListChanged()}})).catch(complete);return w}getOperatorList({intent:t="display",annotationMode:e=i.AnnotationMode.ENABLE,printAnnotationStorage:n=null,isEditing:s=!1}={}){const a=this._transport.getRenderingIntent(t,e,n,s,!0);let r,o=this._intentStates.get(a.cacheKey);if(!o){o=Object.create(null);this._intentStates.set(a.cacheKey,o)}if(!o.opListReadCapability){r=Object.create(null);r.operatorListChanged=function operatorListChanged(){if(o.operatorList.lastChunk){o.opListReadCapability.resolve(o.operatorList);o.renderTasks.delete(r)}};o.opListReadCapability=Promise.withResolvers();(o.renderTasks||=new Set).add(r);o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(a)}return o.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=>I.XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const n=e.getReader(),s={items:[],styles:Object.create(null),lang:null};!function pump(){n.read().then((function({value:e,done:i}){if(i)t(s);else{s.lang??=e.lang;Object.assign(s.styles,e.styles);s.items.push(...e.items);pump()}}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#G=!1;this.#q();return Promise.all(t)}cleanup(t=!1){this.#G=!0;const e=this.#X(!1);t&&e&&(this._stats&&=new s.StatTimer);return e}#X(t=!1){this.#q();if(!this.#G||this.destroyed)return!1;if(t){this.#$=setTimeout((()=>{this.#$=null;this.#X(!1)}),5e3);return!1}for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#G=!1;return!0}#q(){if(this.#$){clearTimeout(this.#$);this.#$=null}}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,n=t.length;i<n;i++){e.operatorList.fnArray.push(t.fnArray[i]);e.operatorList.argsArray.push(t.argsArray[i])}e.operatorList.lastChunk=t.lastChunk;e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#X(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:n}){const{map:s,transfer:a}=i,r=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:s,modifiedIds:n},a).getReader(),o=this._intentStates.get(e);o.streamReader=r;const pump=()=>{r.read().then((({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}}),(t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#X(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:n=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!n){if(t.renderTasks.size>0)return;if(e instanceof s.RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),i);return}}t.streamReader.cancel(new i.AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!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 LoopbackPort{#K=new Map;#Y=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#Y.then((()=>{for(const[t]of this.#K)t.call(this,i)}))}addEventListener(t,e,n=null){let s=null;if(n?.signal instanceof AbortSignal){const{signal:a}=n;if(a.aborted){(0,i.warn)("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>a.removeEventListener("abort",onAbort);a.addEventListener("abort",onAbort)}this.#K.set(e,s)}removeEventListener(t,e){const i=this.#K.get(e);i?.();this.#K.delete(e)}terminate(){for(const[,t]of this.#K)t?.();this.#K.clear()}}class PDFWorker{static#Z=0;static#Q=!1;static#J;static{if(i.isNodeJS){this.#Q=!0;P.GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{let i;try{i=new URL(t);if(!i.origin||"null"===i.origin)return!1}catch{return!1}const n=new URL(e,i);return i.origin===n.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:n=(0,i.getVerbosityLevel)(),cspPolicyService:s}={}){this.name=t;this.destroyed=!1;this.verbosity=n;this._readyCapability=Promise.withResolvers();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#J?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(PDFWorker.#J||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize(s)}get promise(){return this._readyCapability.promise}#tt(){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 MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this.#tt()}_initialize(t){if(PDFWorker.#Q||PDFWorker.#et){this._setupFakeWorker();return}let{workerSrc:e}=PDFWorker;try{PDFWorker._isSameOrigin(window.location.href,e)||(e=PDFWorker._createCDNWrapper(new URL(e,window.location).href));const i=new Worker(t.generateTrustedURL(e),{type:"module"}),n=new MessageHandler("main","worker",i),terminateEarly=()=>{s.abort();n.destroy();i.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},s=new AbortController;i.addEventListener("error",(()=>{this._webWorker||terminateEarly()}),{signal:s.signal});n.on("test",(t=>{s.abort();if(!this.destroyed&&t){this._messageHandler=n;this._port=i;this._webWorker=i;this.#tt()}else terminateEarly()}));n.on("ready",(t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;n.send("test",t,[t.buffer])};sendTest();return}catch{(0,i.info)("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorker.#Q){(0,i.warn)("Setting up fake worker.");PDFWorker.#Q=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const i="fake"+PDFWorker.#Z++,n=new MessageHandler(i+"_worker",i,e);t.setup(n,e);this._messageHandler=new MessageHandler(i,i+"_worker",e);this.#tt()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;this._webWorker?.terminate();this._webWorker=null;PDFWorker.#J?.delete(this._port);this._port=null;this._messageHandler?.destroy();this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#J?.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 PDFWorker(t)}static get workerSrc(){if(P.GlobalWorkerOptions.workerSrc)return P.GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#et(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return(0,i.shadow)(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#et)return this.#et;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{#it=new Map;#nt=new Map;#st=new Map;#at=new Map;#rt=null;constructor(t,e,i,n,s){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:n.ownerDocument,styleElement:n.styleElement});this.loadingParams=n.loadingParams;this._params=n;this.canvasFactory=s.canvasFactory;this.filterFactory=s.filterFactory;this.cMapReaderFactory=s.cMapReaderFactory;this.standardFontDataFactory=s.standardFontDataFactory;this.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.setupMessageHandler()}#ot(t,e=null){const i=this.#it.get(t);if(i)return i;const n=this.messageHandler.sendWithPromise(t,e);this.#it.set(t,n);return n}get annotationStorage(){return(0,i.shadow)(this,"annotationStorage",new n.AnnotationStorage)}getRenderingIntent(t,e=i.AnnotationMode.ENABLE,s=null,a=!1,r=!1){let o=i.RenderingIntentFlag.DISPLAY,l=n.SerializableEmpty;switch(t){case"any":o=i.RenderingIntentFlag.ANY;break;case"display":break;case"print":o=i.RenderingIntentFlag.PRINT;break;default:(0,i.warn)(`getRenderingIntent - invalid intent: ${t}`)}const h=o&i.RenderingIntentFlag.PRINT&&s instanceof n.PrintAnnotationStorage?s:this.annotationStorage;switch(e){case i.AnnotationMode.DISABLE:o+=i.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case i.AnnotationMode.ENABLE:break;case i.AnnotationMode.ENABLE_FORMS:o+=i.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case i.AnnotationMode.ENABLE_STORAGE:o+=i.RenderingIntentFlag.ANNOTATIONS_STORAGE;l=h.serializable;break;default:(0,i.warn)(`getRenderingIntent - invalid annotationMode: ${e}`)}a&&(o+=i.RenderingIntentFlag.IS_EDITING);r&&(o+=i.RenderingIntentFlag.OPLIST);const{ids:d,hash:c}=h.modifiedIds;return{renderingIntent:o,cacheKey:[o,l.hash,c].join("_"),annotationStorageSerializable:l,modifiedIds:d}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#rt?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#nt.values())t.push(e._destroy());this.#nt.clear();this.#st.clear();this.#at.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#it.clear();this.filterFactory.destroy();M.TextLayer.cleanup();this._networkStream?.cancelAllRequests(new i.AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{(0,i.assert)(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:n}){if(n)e.close();else{(0,i.assert)(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",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:s}=this._fullReader;if(!i||!n){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:i,isRangeSupported:n,contentLength:s}}));t.on("GetRangeReader",((t,e)=>{(0,i.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const n=this._networkStream.getRangeReader(t.begin,t.end);if(n){e.onPull=()=>{n.read().then((function({value:t,done:n}){if(n)e.close();else{(0,i.assert)(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{n.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(t=>{e._capability.reject(wrapReason(t))}));t.on("PasswordRequest",(t=>{this.#rt=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#rt.reject(t):this.#rt.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#rt.reject(t)}return this.#rt.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#nt.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,n,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(n){case"Font":const{disableFontFace:a,fontExtraProperties:r,pdfBug:o}=this._params;if("error"in s){const t=s.error;(0,i.warn)(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const l=o&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,h=new FontFaceObject(s,{disableFontFace:a,fontExtraProperties:r,inspectFont:l});this.fontLoader.bind(h).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!r&&h.data&&(h.data=null);this.commonObjs.resolve(e,h)}));break;case"CopyLocalImage":const{imageRef:d}=s;(0,i.assert)(d,"The imageRef must be defined.");for(const t of this.#nt.values())for(const[,i]of t.objs)if(i?.ref===d){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${n}`)}return null}));t.on("obj",(([t,e,n,s])=>{if(this.destroyed)return;const a=this.#nt.get(e);if(!a.objs.has(t))if(0!==a._intentStates.size)switch(n){case"Image":a.objs.resolve(t,s);s?.dataLen>i.MAX_IMAGE_SIZE_TO_CACHE&&(a._maybeCleanupAfterRender=!0);break;case"Pattern":a.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${n}`)}else s?.bitmap?.close()}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("FetchBuiltInCMap",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(t)}));t.on("FetchStandardFontData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&(0,i.warn)("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.#st.get(e);if(i)return i;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#at.set(i.refStr,t);const n=new PDFPageProxy(e,i,this,this._params.pdfBug);this.#nt.set(e,n);return n}));this.#st.set(e,n);return n}getPageIndex(t){return isRefProxy(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.#ot("GetFieldObjects")}hasJSActions(){return this.#ot("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.#ot("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.#ot("GetOptionalContentConfig").then((e=>new OptionalContentConfig(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#it.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#it.set(t,i);return 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.#nt.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#it.clear();this.filterFactory.destroy(!0);M.TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#at.get(e)??null}}const N=Symbol("INITIAL_DATA");class PDFObjects{#lt=Object.create(null);#ht(t){return this.#lt[t]||={...Promise.withResolvers(),data:N}}get(t,e=null){if(e){const i=this.#ht(t);i.promise.then((()=>e(i.data)));return null}const i=this.#lt[t];if(!i||i.data===N)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#lt[t];return!!e&&e.data!==N}delete(t){const e=this.#lt[t];if(!e||e.data===N)return!1;delete this.#lt[t];return!0}resolve(t,e=null){const i=this.#ht(t);i.data=e;i.resolve()}clear(){for(const t in this.#lt){const{data:e}=this.#lt[t];e?.bitmap?.close()}this.#lt=Object.create(null)}*[Symbol.iterator](){for(const t in this.#lt){const{data:e}=this.#lt[t];e!==N&&(yield[t,e])}}}class RenderTask{#dt=null;constructor(t){this.#dt=t;this.onContinue=null}get promise(){return this.#dt.capability.promise}cancel(t=0){this.#dt.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#dt.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#dt;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#ct=null;static#ut=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:n,annotationCanvasMap:s,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=n;this.annotationCanvasMap=s;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 RenderTask(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(InternalRenderTask.#ut.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.");InternalRenderTask.#ut.add(this._canvas)}if(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:n,transform:s,background:a}=this.params;this.gfx=new CanvasGraphics(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:s,viewport:n,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();if(this.#ct){window.cancelAnimationFrame(this.#ct);this.#ct=null}InternalRenderTask.#ut.delete(this._canvas);this.callback(t||new s.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#ct=window.requestAnimationFrame((()=>{this.#ct=null;this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#ut.delete(this._canvas);this.callback()}}}}}const B="4.10.708",O="f47106c3e"},419:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{OutputScale:()=>OutputScale,PDFDateString:()=>PDFDateString,PageViewport:()=>PageViewport,PixelsPerInch:()=>PixelsPerInch,RenderingCancelledException:()=>RenderingCancelledException,SVG_NS:()=>n,StatTimer:()=>StatTimer,fetchData:()=>fetchData,getColorValues:()=>getColorValues,getCurrentTransform:()=>getCurrentTransform,getCurrentTransformInverse:()=>getCurrentTransformInverse,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getRGB:()=>getRGB,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,isValidFetchUrl:()=>isValidFetchUrl,noContextMenu:()=>noContextMenu,setLayerDimensions:()=>setLayerDimensions,stopEvent:()=>stopEvent});var i=e(292);const n="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(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,n)=>{const s=new XMLHttpRequest;s.open("GET",t,!0);s.responseType=e;s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE)if(200!==s.status&&0!==s.status)n(new Error(s.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":i(s.response);return}i(s.responseText)}};s.send(null)}))}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:n,offsetX:s=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=n;this.offsetX=s;this.offsetY=a;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;(n%=360)<0&&(n+=360);switch(n){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(r){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+s;g=Math.abs(o-t[0])*i+a;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+s;g=Math.abs(l-t[1])*i+a;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const{userUnit:t,viewBox:e}=this,n=e.map((e=>e*t));return(0,i.shadow)(this,"rawDims",{pageWidth:n[2]-n[0],pageHeight:n[3]-n[1],pageX:n[0],pageY:n[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:n=this.offsetY,dontFlip:s=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}convertToViewportPoint(t,e){return i.Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=i.Util.applyTransform([t[0],t[1]],this.transform),n=i.Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],n[0],n[1]]}convertToPdfPoint(t,e){return i.Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends i.BaseException{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function isPdfFile(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function getFilenameFromUrl(t){[t]=t.split(/[#?]/,1);return t.substring(t.lastIndexOf("/")+1)}function getPdfFilenameFromUrl(t,e="document.pdf"){if(e&&"document.pdf"!==e)return e;if("string"!=typeof t)return e;if(isDataScheme(t)){(0,i.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');return e}const n=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,s=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(t);let a=n.exec(s[1])||n.exec(s[2])||n.exec(s[3]);if(a){a=a[0];if(a.includes("%"))try{a=n.exec(decodeURIComponent(a))[0]}catch{}}return a||e}class StatTimer{started=Object.create(null);times=[];time(t){t in this.started&&(0,i.warn)(`Timer is already running for ${t}`);this.started[t]=Date.now()}timeEnd(t){t in this.started||(0,i.warn)(`Timer has not been started for ${t}`);this.times.push({name:t,start:this.started[t],end:Date.now()});delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:n,end:s}of this.times)t.push(`${i.padEnd(e)} ${s-n}ms\n`);return t.join("")}}function isValidFetchUrl(t,e){try{const{protocol:i}=e?new URL(t,e):new URL(t);return"http:"===i||"https:"===i||"capacitor:"===i}catch{return!1}}function noContextMenu(t){t.preventDefault()}function stopEvent(t){t.preventDefault();t.stopPropagation()}class PDFDateString{static#pt;static toDateObject(t){if(!t||"string"!=typeof t)return null;this.#pt||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#pt.exec(t);if(!e)return null;const i=parseInt(e[1],10);let n=parseInt(e[2],10);n=n>=1&&n<=12?n-1:0;let s=parseInt(e[3],10);s=s>=1&&s<=31?s: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;d=d>=0&&d<=59?d:0;if("-"===l){a+=h;r+=d}else if("+"===l){a-=h;r-=d}return new Date(Date.UTC(i,n,s,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:n,height:s}=t.attributes.style,a=[0,0,parseInt(n),parseInt(s)];return new PageViewport({viewBox:a,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);(0,i.warn)(`Not a valid color format: "${t}"`);return[0,0,0]}function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const i of t.keys()){e.style.color=i;const n=window.getComputedStyle(e).color;t.set(i,getRGB(n))}e.remove()}function getCurrentTransform(t){const{a:e,b:i,c:n,d:s,e:a,f:r}=t.getTransform();return[e,i,n,s,a,r]}function getCurrentTransformInverse(t){const{a:e,b:i,c:n,d:s,e:a,f:r}=t.getTransform().invertSelf();return[e,i,n,s,a,r]}function setLayerDimensions(t,e,n=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:a}=e.rawDims,{style:r}=t,o=i.FeatureTest.isCSSRoundSupported,l=`var(--scale-factor) * ${s}px`,h=`var(--scale-factor) * ${a}px`,d=o?`round(down, ${l}, var(--scale-round-x, 1px))`:`calc(${l})`,c=o?`round(down, ${h}, var(--scale-round-y, 1px))`:`calc(${h})`;if(n&&e.rotation%180!=0){r.width=c;r.height=d}else{r.width=d;r.height=c}}s&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{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}}},310:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{AnnotationEditor:()=>AnnotationEditor});var i=e(830),n=e(292),s=e(419);class AltText{#gt=null;#mt=!1;#ft=null;#bt=null;#wt=null;#vt=null;#yt=!1;#At=null;#xt=null;#Et=null;#St=null;#Pt=!1;static#_t=null;static _l10n=null;constructor(t){this.#xt=t;this.#Pt=t._uiManager.useNewAltTextFlow;AltText.#_t||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){AltText._l10n??=t}async render(){const t=this.#ft=document.createElement("button");t.className="altText";t.tabIndex="0";const e=this.#bt=document.createElement("span");t.append(e);if(this.#Pt){t.classList.add("new");t.setAttribute("data-l10n-id",AltText.#_t.missing);e.setAttribute("data-l10n-id",AltText.#_t["missing-label"])}else{t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button");e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label")}const i=this.#xt._uiManager._signal;t.addEventListener("contextmenu",s.noContextMenu,{signal:i});t.addEventListener("pointerdown",(t=>t.stopPropagation()),{signal:i});const onClick=t=>{t.preventDefault();this.#xt._uiManager.editAltText(this.#xt);this.#Pt&&this.#xt._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Ct}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",(e=>{if(e.target===t&&"Enter"===e.key){this.#yt=!0;onClick(e)}}),{signal:i});await this.#Tt();return t}get#Ct(){return(this.#gt?"added":null===this.#gt&&this.guessedText&&"review")||"missing"}finish(){if(this.#ft){this.#ft.focus({focusVisible:this.#yt});this.#yt=!1}}isEmpty(){return this.#Pt?null===this.#gt:!this.#gt&&!this.#mt}hasData(){return this.#Pt?null!==this.#gt||!!this.#Et:this.isEmpty()}get guessedText(){return this.#Et}async setGuessedText(t){if(null===this.#gt){this.#Et=t;this.#St=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#Tt()}}toggleAltTextBadge(t=!1){if(this.#Pt&&!this.#gt){if(!this.#At){const t=this.#At=document.createElement("div");t.className="noAltTextBadge";this.#xt.div.append(t)}this.#At.classList.toggle("hidden",!t)}else{this.#At?.remove();this.#At=null}}serialize(t){let e=this.#gt;t||this.#Et!==e||(e=this.#St);return{altText:e,decorative:this.#mt,guessedText:this.#Et,textWithDisclaimer:this.#St}}get data(){return{altText:this.#gt,decorative:this.#mt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:n,cancel:s=!1}){if(i){this.#Et=i;this.#St=n}if(this.#gt!==t||this.#mt!==e){if(!s){this.#gt=t;this.#mt=e}this.#Tt()}}toggle(t=!1){if(this.#ft){if(!t&&this.#vt){clearTimeout(this.#vt);this.#vt=null}this.#ft.disabled=!t}}shown(){this.#xt._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Ct}})}destroy(){this.#ft?.remove();this.#ft=null;this.#bt=null;this.#wt=null;this.#At?.remove();this.#At=null}async#Tt(){const t=this.#ft;if(!t)return;if(this.#Pt){t.classList.toggle("done",!!this.#gt);t.setAttribute("data-l10n-id",AltText.#_t[this.#Ct]);this.#bt?.setAttribute("data-l10n-id",AltText.#_t[`${this.#Ct}-label`]);if(!this.#gt){this.#wt?.remove();return}}else{if(!this.#gt&&!this.#mt){t.classList.remove("done");this.#wt?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#wt;if(!e){this.#wt=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#xt.id}`;const i=100,n=this.#xt._uiManager._signal;n.addEventListener("abort",(()=>{clearTimeout(this.#vt);this.#vt=null}),{once:!0});t.addEventListener("mouseenter",(()=>{this.#vt=setTimeout((()=>{this.#vt=null;this.#wt.classList.add("show");this.#xt._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:n});t.addEventListener("mouseleave",(()=>{if(this.#vt){clearTimeout(this.#vt);this.#vt=null}this.#wt?.classList.remove("show")}),{signal:n})}if(this.#mt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#gt}e.parentNode||t.append(e);const i=this.#xt.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}var a=e(362),r=e(900);class AnnotationEditor{#Mt=null;#It=null;#gt=null;#Dt=!1;#Lt=null;#kt="";#Ft=!1;#Rt=null;#Nt=null;#Bt=null;#Ot=null;#Vt="";#Ht=!1;#zt=null;#Ut=!1;#jt=!1;#Wt=!1;#$t=null;#Gt=0;#qt=0;#Xt=null;#Kt=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#Yt=!1;#Zt=AnnotationEditor._zIndex++;doNotMove=!1;static _borderLineWidth=-1;static _colorManager=new i.ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=i.AnnotationEditorUIManager.TRANSLATE_SMALL,s=i.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,n.shadow)(this,"_resizerKeyboardManager",new i.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],AnnotationEditor.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:n,pageX:s,pageY:a}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,n];this.pageTranslation=[s,a];const[r,o]=this.parentDimensions;this.x=t.x/r;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1;this.eventBus=t.eventBus}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return(0,n.shadow)(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({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){AnnotationEditor._l10n??=t;AnnotationEditor._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"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){(0,n.unreachable)("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#Yt}set _isDraggable(t){this.#Yt=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.#Zt}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Qt();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ht?this.#Ht=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage();this._eventBus?.dispatch("annotation-editor-event",{source:this,type:"commit",page:this.pageIndex+1,editorType:this.constructor.name,value:this})}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,n){const[s,a]=this.parentDimensions;[i,n]=this.screenToPageTranslation(i,n);this.doNotMove&&([i,n]=[0,0]);this.x=(t+i)/s;this.y=(e+n)/a;this.fixAndSetPosition()}#Jt([t,e],i,n){[i,n]=this.screenToPageTranslation(i,n);this.x+=i/t;this.y+=n/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#Jt(this.parentDimensions,t,e)}translateInPage(t,e){this.#zt||=[this.x,this.y,this.width,this.height];this.#Jt(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#zt||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[n,s]}=this;this.x+=t/n;this.y+=e/s;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o;r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`;h.top=`${(100*r).toFixed(2)}%`;this._onTranslating(a,r);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#zt&&(this.#zt[0]!==this.x||this.#zt[1]!==this.y)}get _hasBeenResized(){return!!this.#zt&&(this.#zt[2]!==this.width||this.#zt[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,n=i/t,s=i/e;switch(this.rotation){case 90:return[-n,s];case 180:return[n,s];case 270:return[n,-s];default:return[-n,-s]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,n]}=this;let{x:s,y:a,width:r,height:o}=this;r*=i;o*=n;s*=i;a*=n;if(this._mustFixPosition)switch(t){case 0:s=Math.max(0,Math.min(i-r,s));a=Math.max(0,Math.min(n-o,a));break;case 90:s=Math.max(0,Math.min(i-o,s));a=Math.min(n,Math.max(r,a));break;case 180:s=Math.min(i,Math.max(r,s));a=Math.min(n,Math.max(o,a));break;case 270:s=Math.min(i,Math.max(o,s));a=Math.max(0,Math.min(n-r,a))}this.x=s/=i;this.y=a/=n;const[l,h]=this.getBaseTranslation();s+=l;a+=h;e.left=`${(100*s).toFixed(2)}%`;e.top=`${(100*a).toFixed(2)}%`;this.moveInDOM()}static#te(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 AnnotationEditor.#te(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#te(t,e,360-this.parentRotation)}#ee(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,n]=this.parentDimensions,{style:s}=this.div;s.width=`${(100*t/i).toFixed(2)}%`;this.#Ft||(s.height=`${(100*e/n).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,n=i.endsWith("%"),s=!this.#Ft&&e.endsWith("%");if(n&&s)return;const[a,r]=this.parentDimensions;n||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`);this.#Ft||s||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#ie(){if(this.#Rt)return;this.#Rt=document.createElement("div");this.#Rt.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.#Rt.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#ne.bind(this,i),{signal:e});t.addEventListener("contextmenu",s.noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#Rt)}#ne(t,e){e.preventDefault();const{isMac:i}=n.FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#gt?.toggle(!1);const a=this._isDraggable;this._isDraggable=!1;this.#Nt=[e.screenX,e.screenY];const r=new AbortController,o=this._uiManager.combinedSignal(r);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#se.bind(this,t),{passive:!0,capture:!0,signal:o});window.addEventListener("touchmove",s.stopEvent,{passive:!1,signal:o});window.addEventListener("contextmenu",s.noContextMenu,{signal:o});this.#Bt={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const l=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{r.abort();this.parent.togglePointerEvents(!0);this.#gt?.toggle(!0);this._isDraggable=a;this.parent.div.style.cursor=l;this.div.style.cursor=h;this.#ae()};window.addEventListener("pointerup",pointerUpCallback,{signal:o});window.addEventListener("blur",pointerUpCallback,{signal:o})}#re(t,e,i,n){this.width=i;this.height=n;this.x=t;this.y=e;const[s,a]=this.parentDimensions;this.setDims(s*i,a*n);this.fixAndSetPosition();this._onResized()}_onResized(){}#ae(){if(!this.#Bt)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:n}=this.#Bt;this.#Bt=null;const s=this.x,a=this.y,r=this.width,o=this.height;if(s!==t||a!==e||r!==i||o!==n){this.eventBus?.dispatch("annotation-editor-event",{source:this,type:"sizeChanged",editorType:this.constructor.name,page:this.pageIndex+1,value:{x:t,y:e,width:i,height:n}});this.addCommands({cmd:this.#re.bind(this,s,a,r,o),undo:this.#re.bind(this,t,e,i,n),mustExec:!0})}}static _round(t){return Math.round(1e4*t)/1e4}#se(t,e){const[i,n]=this.parentDimensions,s=this.x,a=this.y,r=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/n,d=this.#ee(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#ee(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(r,o),b=p(r,o);let w=transf(...b);const v=AnnotationEditor._round(s+w[0]),y=AnnotationEditor._round(a+w[1]);let A,x,E=1,S=1;if(e.fromKeyboard)({deltaX:A,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[n,s]=this.#Nt;[A,x]=this.screenToPageTranslation(t-n,i-s);this.#Nt[0]=t;this.#Nt[1]=i}[A,x]=(P=A/i,_=x/n,[c[0]*P+c[2]*_,c[1]*P+c[3]*_]);var P,_;if(g){const t=Math.hypot(r,o);E=S=Math.max(Math.min(Math.hypot(b[0]-f[0]-A,b[1]-f[1]-x)/t,1/r,1/o),l/r,h/o)}else m?E=Math.max(l,Math.min(1,Math.abs(b[0]-f[0]-A)))/r:S=Math.max(h,Math.min(1,Math.abs(b[1]-f[1]-x)))/o;const C=AnnotationEditor._round(r*E),T=AnnotationEditor._round(o*S);w=transf(...p(C,T));const M=v-w[0],I=y-w[1];this.#zt||=[this.x,this.y,this.width,this.height];this.width=C;this.height=T;this.x=M;this.y=I;this.setDims(i*C,n*T);this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#gt?.finish();this.eventBus?.dispatch("annotation-editor-event",{source:this,type:"altTextChanged",page:this.pageIndex+1,editorType:this.constructor.name,value:this.#gt})}async addEditToolbar(){if(this._editToolbar||this.#jt)return this._editToolbar;this._editToolbar=new a.EditorToolbar(this);this.div.append(this._editToolbar.render());this.#gt&&await this._editToolbar.addAltText(this.#gt);return this._editToolbar}removeEditToolbar(){if(this._editToolbar){this._editToolbar.remove();this._editToolbar=null;this.#gt?.destroy()}}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){if(!this.#gt){AltText.initialize(AnnotationEditor._l10n);this.#gt=new AltText(this);if(this.#Mt){this.#gt.data=this.#Mt;this.#Mt=null}await this.addEditToolbar()}}get altTextData(){return this.#gt?.data}set altTextData(t){this.#gt&&(this.#gt.data=t)}get guessedAltText(){return this.#gt?.guessedText}async setGuessedAltText(t){await(this.#gt?.setGuessedText(t))}serializeAltText(t){return this.#gt?.serialize(t)}hasAltText(){return!!this.#gt&&!this.#gt.isEmpty()}hasAltTextData(){return this.#gt?.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.#Dt?-1:0;this._isVisible||this.div.classList.add("hidden");this.setInForeground();this.#oe();const[t,e]=this.parentDimensions;if(this.parentRotation%180!=0){this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`;this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`}const[n,s]=this.getInitialTranslation();this.translate(n,s);(0,i.bindEvents)(this,this.div,["pointerdown"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Kt||=new r.TouchManager({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#le.bind(this),onPinching:this.#he.bind(this),onPinchEnd:this.#de.bind(this),signal:this._uiManager._signal}));this._uiManager._editorUndoBar?.hide();return this.div}#le(){this.#Bt={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#gt?.toggle(!1);this.parent.togglePointerEvents(!1)}#he(t,e,i){let n=i/e*.7+1-.7;if(1===n)return;const s=this.#ee(this.rotation),transf=(t,e)=>[s[0]*t+s[2]*e,s[1]*t+s[3]*e],[a,r]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/a,u=AnnotationEditor.MIN_SIZE/r;n=Math.max(Math.min(n,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*n),g=AnnotationEditor._round(d*n);if(p===h&&g===d)return;this.#zt||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),w=transf(p/2,g/2);this.x=f-w[0];this.y=b-w[1];this.width=p;this.height=g;this.setDims(a*p,r*g);this.fixAndSetPosition();this._onResizing()}#de(){this.#gt?.toggle(!0);this.parent.togglePointerEvents(!0);this.#ae()}pointerdown(t){const{isMac:e}=n.FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#Ht=!0;this._isDraggable?this.#ce(t):this.#ue(t)}}get isSelected(){return this._uiManager.isSelected(this)}#ue(t){const{isMac:e}=n.FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#ce(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const n=new AbortController,a=this._uiManager.combinedSignal(n),r={capture:!0,passive:!1,signal:a},cancelDrag=t=>{n.abort();this.#Lt=null;this.#Ht=!1;this._uiManager.endDragSession()||this.#ue(t);i&&this._onStopDragging()};if(e){this.#Gt=t.clientX;this.#qt=t.clientY;this.#Lt=t.pointerId;this.#kt=t.pointerType;window.addEventListener("pointermove",(t=>{if(!i){i=!0;this._onStartDragging()}const{clientX:e,clientY:n,pointerId:a}=t;if(a!==this.#Lt){(0,s.stopEvent)(t);return}const[r,o]=this.screenToPageTranslation(e-this.#Gt,n-this.#qt);this.#Gt=e;this.#qt=n;this._uiManager.dragSelectedEditors(r,o)}),r);window.addEventListener("touchmove",s.stopEvent,r);window.addEventListener("pointerdown",(t=>{t.pointerType===this.#kt&&(this.#Kt||t.isPrimary)&&cancelDrag(t);(0,s.stopEvent)(t)}),r)}const pointerUpCallback=t=>{this.#Lt&&this.#Lt!==t.pointerId?(0,s.stopEvent)(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:a});window.addEventListener("blur",pointerUpCallback,{signal:a})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#$t&&clearTimeout(this.#$t);this.#$t=setTimeout((()=>{this.#$t=null;this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const n=this.parentScale,[s,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/n,h=e/n,d=this.x*s,c=this.y*a,u=this.width*s,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,n,s,a]=t,r=s-i,o=a-n;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-n,o,r];case 180:return[s,e-n,r,o];case 270:return[s,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#jt=!0}disableEditMode(){this.#jt=!1}isInEditMode(){return this.#jt}shouldGetKeyboardEvents(){return this.#Wt}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:n}=this.getClientDimensions(),{innerHeight:s,innerWidth:a}=window;return e<a&&n>0&&t<s&&i>0}#oe(){if(this.#Ot||!this.div)return;this.#Ot=new AbortController;const t=this._uiManager.combinedSignal(this.#Ot);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#oe()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){(0,n.unreachable)("An editor must be serializable")}static async deserialize(t,e,i){const n=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i,eventBus:e.eventBus});n.rotation=t.rotation;n.#Mt=t.accessibilityData;const[s,a]=n.pageDimensions,[r,o,l,h]=n.getRectInCurrentCoords(t.rect,a);n.x=r/s;n.y=o/a;n.width=l/s;n.height=h/a;return n}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#Ot?.abort();this.#Ot=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#$t){clearTimeout(this.#$t);this.#$t=null}this.#Qt();this.removeEditToolbar();if(this.#Xt){for(const t of this.#Xt.values())clearTimeout(t);this.#Xt=null}this.parent=null;this.eventBus?.dispatch("annotation-editor-event",{source:this,type:"removed",page:this.pageIndex+1,editorType:this.constructor.name,value:this});this.#Kt?.destroy();this.#Kt=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#ie();this.#Rt.classList.remove("hidden");(0,i.bindEvents)(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.#Bt={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Rt.children;if(!this.#It){this.#It=Array.from(e);const t=this.#pe.bind(this),i=this.#ge.bind(this),n=this._uiManager._signal;for(const e of this.#It){const s=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:n});e.addEventListener("blur",i,{signal:n});e.addEventListener("focus",this.#me.bind(this,s),{signal:n});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[s])}}const i=this.#It[0];let n=0;for(const t of e){if(t===i)break;n++}const s=(360-this.rotation+this.parentRotation)%360/90*(this.#It.length/4);if(s!==n){if(s<n)for(let t=0;t<n-s;t++)this.#Rt.append(this.#Rt.firstChild);else if(s>n)for(let t=0;t<s-n;t++)this.#Rt.firstChild.before(this.#Rt.lastChild);let t=0;for(const i of e){const e=this.#It[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[e])}}this.#fe(0);this.#Wt=!0;this.#Rt.firstChild.focus({focusVisible:!0});t.preventDefault();t.stopImmediatePropagation()}#pe(t){AnnotationEditor._resizerKeyboardManager.exec(this,t)}#ge(t){this.#Wt&&t.relatedTarget?.parentNode!==this.#Rt&&this.#Qt()}#me(t){this.#Vt=this.#Wt?t:""}#fe(t){if(this.#It)for(const e of this.#It)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#Wt&&this.#se(this.#Vt,{deltaX:t,deltaY:e,fromKeyboard:!0})}#Qt(){this.#Wt=!1;this.#fe(-1);this.#ae()}_stopResizingWithKeyboard(){this.#Qt();this.div.focus()}select(){this.makeResizable();this.div?.classList.add("selectedEditor");if(this._editToolbar){this._editToolbar?.show();this.#gt?.toggleAltTextBadge(!1)}else this.addEditToolbar().then((()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#Rt?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#gt?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#Ut}set isEditing(t){this.#Ut=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}setAspectRatio(t,e){this.#Ft=!0;const i=t/e,{style:n}=this.div;n.aspectRatio=i;n.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.#Xt||=new Map;const{action:e}=t;let i=this.#Xt.get(e);i&&clearTimeout(i);i=setTimeout((()=>{this._reportTelemetry(t);this.#Xt.delete(e);0===this.#Xt.size&&(this.#Xt=null)}),AnnotationEditor._telemetryTimeout);this.#Xt.set(e,i)}else{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.#Dt=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#Dt=!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 FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}},362:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{EditorToolbar:()=>EditorToolbar,HighlightToolbar:()=>HighlightToolbar});var i=e(419);class EditorToolbar{#be=null;#we=null;#xt;#ve=null;#gt=null;static#ye=null;constructor(t){this.#xt=t;EditorToolbar.#ye||=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.#be=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#xt._uiManager._signal;t.addEventListener("contextmenu",i.noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#Ae,{signal:e});const n=this.#ve=document.createElement("div");n.className="buttons";t.append(n);const s=this.#xt.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#xt._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%";e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}this.#xe();return t}get div(){return this.#be}static#Ae(t){t.stopPropagation()}#Ee(t){this.#xt._focusEventsAllowed=!1;(0,i.stopEvent)(t)}#Se(t){this.#xt._focusEventsAllowed=!0;(0,i.stopEvent)(t)}#Pe(t){const e=this.#xt._uiManager._signal;t.addEventListener("focusin",this.#Ee.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#Se.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",i.noContextMenu,{signal:e})}hide(){this.#be.classList.add("hidden");this.#we?.hideDropdown()}show(){this.#be.classList.remove("hidden");this.#gt?.shown()}#xe(){const{editorType:t,_uiManager:e}=this.#xt,i=document.createElement("button");i.className="delete";i.tabIndex=0;i.setAttribute("data-l10n-id",EditorToolbar.#ye[t]);this.#Pe(i);i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal});this.#ve.append(i)}get#_e(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#Pe(e);this.#ve.prepend(e,this.#_e);this.#gt=t}addColorPicker(t){this.#we=t;const e=t.renderButton();this.#Pe(e);this.#ve.prepend(e,this.#_e)}remove(){this.#be.remove();this.#we?.destroy();this.#we=null}}class HighlightToolbar{#ve=null;#be=null;#Ce;constructor(t){this.#Ce=t}#Te(){const t=this.#be=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");t.addEventListener("contextmenu",i.noContextMenu,{signal:this.#Ce._signal});const e=this.#ve=document.createElement("div");e.className="buttons";t.append(e);this.#Me();return t}#Ie(t,e){let i=0,n=0;for(const s of t){const t=s.y+s.height;if(t<i)continue;const a=s.x+(e?s.width:0);if(t>i){n=a;i=t}else e?a>n&&(n=a):a<n&&(n=a)}return[e?1-n:n,i]}show(t,e,i){const[n,s]=this.#Ie(e,i),{style:a}=this.#be||=this.#Te();t.append(this.#be);a.insetInlineEnd=100*n+"%";a.top=`calc(${100*s}% + var(--editor-toolbar-vert-offset))`}hide(){this.#be.remove()}#Me(){const t=document.createElement("button");t.className="highlightButton";t.tabIndex=0;t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e);e.className="visuallyHidden";e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const n=this.#Ce._signal;t.addEventListener("contextmenu",i.noContextMenu,{signal:n});t.addEventListener("click",(()=>{this.#Ce.highlightSelection("floating_button")}),{signal:n});this.#ve.append(t)}}},830:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{AnnotationEditorUIManager:()=>AnnotationEditorUIManager,ColorManager:()=>ColorManager,KeyboardManager:()=>KeyboardManager,bindEvents:()=>bindEvents});var i=e(292),n=e(419),s=e(362);function bindEvents(t,e,i){for(const n of i)e.addEventListener(n,t[n].bind(t))}class IdManager{#L=0;get id(){return`${i.AnnotationEditorPrefix}${this.#L++}`}}class ImageManager{#De=(0,i.getUuid)();#L=0;#k=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';const n=e.decode().then((()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]}));return(0,i.shadow)(this,"_isSVGFittingCanvas",n)}async#Le(t,e){this.#k||=new Map;let s=this.#k.get(t);if(null===s)return null;if(s?.bitmap){s.refCounter+=1;return s}try{s||={bitmap:null,id:`image_${this.#De}_${this.#L++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){s.url=e;t=await(0,n.fetchData)(e,"blob")}else e instanceof File?t=s.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,i=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{s.bitmap=n;s.isSvg=!0;t()};i.onload=async()=>{const t=s.svgUrl=i.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=i.onerror=a}));i.readAsDataURL(t);await a}else s.bitmap=await createImageBitmap(t);s.refCounter=1}catch(t){(0,i.warn)(t);s=null}this.#k.set(t,s);s&&this.#k.set(s.id,s);return s}async getFromFile(t){const{lastModified:e,name:i,size:n,type:s}=t;return this.#Le(`${e}_${i}_${n}_${s}`,t)}async getFromUrl(t){return this.#Le(t,t)}async getFromBlob(t,e){const i=await e;return this.#Le(t,i)}async getFromId(t){this.#k||=new Map;const e=this.#k.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#k||=new Map;let i=this.#k.get(t);if(i?.bitmap){i.refCounter+=1;return i}const n=new OffscreenCanvas(e.width,e.height);n.getContext("2d").drawImage(e,0,0);i={bitmap:n.transferToImageBitmap(),id:`image_${this.#De}_${this.#L++}`,refCounter:1,isSvg:!1};this.#k.set(t,i);this.#k.set(i.id,i);return i}getSvgUrl(t){const e=this.#k.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#k||=new Map;const e=this.#k.get(t);if(!e)return;e.refCounter-=1;if(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.#De}_`)}}class CommandManager{#ke=[];#Fe=!1;#Re;#Ne=-1;constructor(t=128){this.#Re=t}add({cmd:t,undo:e,post:i,mustExec:n,type:s=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){n&&t();if(this.#Fe)return;const o={cmd:t,undo:e,post:i,type:s};if(-1===this.#Ne){this.#ke.length>0&&(this.#ke.length=0);this.#Ne=0;this.#ke.push(o);return}if(a&&this.#ke[this.#Ne].type===s){r&&(o.undo=this.#ke[this.#Ne].undo);this.#ke[this.#Ne]=o;return}const l=this.#Ne+1;if(l===this.#Re)this.#ke.splice(0,1);else{this.#Ne=l;l<this.#ke.length&&this.#ke.splice(l)}this.#ke.push(o)}undo(){if(-1===this.#Ne)return;this.#Fe=!0;const{undo:t,post:e}=this.#ke[this.#Ne];t();e?.();this.#Fe=!1;this.#Ne-=1}redo(){if(this.#Ne<this.#ke.length-1){this.#Ne+=1;this.#Fe=!0;const{cmd:t,post:e}=this.#ke[this.#Ne];t();e?.();this.#Fe=!1}}hasSomethingToUndo(){return-1!==this.#Ne}hasSomethingToRedo(){return this.#Ne<this.#ke.length-1}cleanType(t){if(-1!==this.#Ne){for(let e=this.#Ne;e>=0;e--)if(this.#ke[e].type!==t){this.#ke.splice(e+1,this.#Ne-e);this.#Ne=e;return}this.#ke.length=0;this.#Ne=-1}}destroy(){this.#ke=null}reset(){this.#ke=[];this.#Ne=-1;this.#Fe=!1}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=i.FeatureTest.platform;for(const[i,n,s={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:n,options:s});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:n,options:s});this.allKeys.add(t.split("+").at(-1))}}}#Be(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#Be(e));if(!i)return;const{callback:s,options:{bubbles:a=!1,args:r=[],checker:o=null}}=i;if(!o||o(t,e)){s.bind(t,...r,e)();a||(0,n.stopEvent)(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);(0,n.getColorValues)(t);return(0,i.shadow)(this,"_colors",t)}convert(t){const e=(0,n.getRGB)(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?i.Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#Oe=new AbortController;#Ve=null;#He=new Map;#ze=new Map;#Ue=null;#je=null;#We=null;#$e=new CommandManager;#Ge=null;#qe=null;#Xe=0;#Ke=new Set;#Ye=null;#Ze=null;#Qe=new Set;_editorUndoBar=null;#Je=!1;#ti=!1;#ei=!1;#ii=null;#ni=null;#si=null;#ai=null;#ri=!1;#oi=null;#li=new IdManager;#hi=!1;#di=!1;#ci=null;#ui=null;#pi=null;#gi=null;#mi=i.AnnotationEditorType.NONE;#fi=new Set;#bi=null;#wi=null;#vi=null;#yi={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Ai=[0,0];#xi=null;#Ei=null;#Si=null;#Pi=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#Ei.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["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:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#Ei.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#Ei.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:arrowChecker}]]))}constructor(t,e,i,s,a,r,o,l,h,d,c,u,p){const g=this._signal=this.#Oe.signal;this.#Ei=t;this.#Si=e;this.#Ue=i;this._eventBus=s;s._on("editingaction",this.onEditingAction.bind(this),{signal:g});s._on("pagechanging",this.onPageChanging.bind(this),{signal:g});s._on("scalechanging",this.onScaleChanging.bind(this),{signal:g});s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g});s._on("setpreference",this.onSetPreference.bind(this),{signal:g});s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:g});this.#_i();this.#Ci();this.#Ti();this.#je=a.annotationStorage;this.#ii=a.filterFactory;this.#wi=r;this.#ai=o||null;this.#Je=l;this.#ti=h;this.#ei=d;this.#gi=c||null;this.viewParameters={realScale:n.PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=u||null;this._supportsPinchToZoom=!1!==p}destroy(){this.#Pi?.resolve();this.#Pi=null;this.#Oe?.abort();this.#Oe=null;this._signal=null;for(const t of this.#ze.values())t.destroy();this.#ze.clear();this.#He.clear();this.#Qe.clear();this.#Ve=null;this.#fi.clear();this.#$e.destroy();this.#Ue?.destroy();this.#oi?.hide();this.#oi=null;if(this.#ni){clearTimeout(this.#ni);this.#ni=null}if(this.#xi){clearTimeout(this.#xi);this.#xi=null}this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#gi}get useNewAltTextFlow(){return this.#ti}get useNewAltTextWhenAddingImage(){return this.#ei}get hcmFilter(){return(0,i.shadow)(this,"hcmFilter",this.#wi?this.#ii.addHCMFilter(this.#wi.foreground,this.#wi.background):"none")}get direction(){return(0,i.shadow)(this,"direction",getComputedStyle(this.#Ei).direction)}get highlightColors(){return(0,i.shadow)(this,"highlightColors",this.#ai?new Map(this.#ai.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return(0,i.shadow)(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#qe=t}setMainHighlightColorPicker(t){this.#pi=t}editAltText(t,e=!1){this.#Ue?.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}){if("enableNewAltTextWhenAddingImage"===t)this.#ei=e}onPageChanging({pageNumber:t}){this.#Xe=t-1}focusMainContainer(){this.#Ei.focus()}findParent(t,e){for(const i of this.#ze.values()){const{x:n,y:s,width:a,height:r}=i.div.getBoundingClientRect();if(t>=n&&t<=n+a&&e>=s&&e<=s+r)return i}return null}disableUserSelect(t=!1){this.#Si.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#Qe.add(t)}removeShouldRescale(t){this.#Qe.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*n.PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#Qe)t.onScaleChanging();this.#qe?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#Mi({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Ii(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#ze.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:n,anchorOffset:s,focusNode:a,focusOffset:r}=e,o=e.toString(),l=this.#Mi(e).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;e.empty();const d=this.#Ii(l),c=this.#mi===i.AnnotationEditorType.NONE,callback=()=>{d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:n,anchorOffset:s,focusNode:a,focusOffset:r,text:o});c&&this.showAllEditors("highlight",!0,!0)};c?this.switchToMode(i.AnnotationEditorType.HIGHLIGHT,callback):callback()}#Di(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Mi(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#oi||=new s.HighlightToolbar(this);this.#oi.show(e,i,"ltr"===this.direction)}}addToAnnotationStorage(t){t.isEmpty()||!this.#je||this.#je.has(t.id)||this.#je.setValue(t.id,t)}#Li(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#bi){this.#oi?.hide();this.#bi=null;this.#ki({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#bi)return;const n=this.#Mi(t).closest(".textLayer");if(n){this.#oi?.hide();this.#bi=e;this.#ki({hasSelectedText:!0});if(this.#mi===i.AnnotationEditorType.HIGHLIGHT||this.#mi===i.AnnotationEditorType.NONE){this.#mi===i.AnnotationEditorType.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#ri=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#mi===i.AnnotationEditorType.HIGHLIGHT?this.#Ii(n):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Fi("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:s});window.addEventListener("blur",pointerup,{signal:s})}}}else if(this.#bi){this.#oi?.hide();this.#bi=null;this.#ki({hasSelectedText:!1})}}#Fi(t=""){this.#mi===i.AnnotationEditorType.HIGHLIGHT?this.highlightSelection(t):this.#Je&&this.#Di()}#_i(){document.addEventListener("selectionchange",this.#Li.bind(this),{signal:this._signal})}#Ri(){if(this.#si)return;this.#si=new AbortController;const t=this.combinedSignal(this.#si);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Ni(){this.#si?.abort();this.#si=null}blur(){this.isShiftKeyDown=!1;if(this.#ri){this.#ri=!1;this.#Fi("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#fi)if(e.div.contains(t)){this.#ui=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#ui)return;const[t,e]=this.#ui;this.#ui=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal});e.focus()}#Ti(){if(this.#ci)return;this.#ci=new AbortController;const t=this.combinedSignal(this.#ci);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Bi(){this.#ci?.abort();this.#ci=null}#Oi(){if(this.#Ge)return;this.#Ge=new AbortController;const t=this.combinedSignal(this.#Ge);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})}#Vi(){this.#Ge?.abort();this.#Ge=null}#Ci(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Ti();this.#Oi()}removeEditListeners(){this.#Bi();this.#Vi()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#Ze)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#Ze)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#Ve?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#fi){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.#Ze)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}const i=e.getData("application/pdfjs");await this.addSerializedEditor(i)}async addSerializedEditor(t,e=!1,n=!1,s=!0){if(!t)return;try{"string"==typeof t&&(t=JSON.parse(t))}catch(t){(0,i.warn)(`paste: "${t.message}".`);return}if(!Array.isArray(t))return;const a=this.#mi;e&&a===i.AnnotationEditorType.NONE&&this.updateMode(i.AnnotationEditorType.FREETEXT);this.unselectAll();try{const e=[];for(const i of t){const t=void 0===i.pageIndex,a=s||t?this.currentLayer:this.getLayer(i.pageIndex),r=await a.deserialize(i);if(!r)return;r.doNotMove=n;e.push(r)}const cmd=()=>{for(const t of e)this.#Hi(t);this.#zi(e)},undo=()=>{for(const t of e)t.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){(0,i.warn)(`paste: "${t.message}".`)}e&&a!==this.#mi&&this.updateMode(a)}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#mi===i.AnnotationEditorType.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#ri){this.#ri=!1;this.#Fi("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#ki(t){if(Object.entries(t).some((([t,e])=>this.#yi[t]!==e))){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#yi,t)});this.#mi===i.AnnotationEditorType.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Ui([[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]])}}#Ui(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#Ri();this.#Oi();this.#ki({isEditing:this.#mi!==i.AnnotationEditorType.NONE,isEmpty:this.#ji(),hasSomethingToUndo:this.#$e.hasSomethingToUndo(),hasSomethingToRedo:this.#$e.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Ni();this.#Vi();this.#ki({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#Ze){this.#Ze=t;for(const t of this.#Ze)this.#Ui(t.defaultPropertiesToUpdate)}}getId(){return this.#li.id}get currentLayer(){return this.#ze.get(this.#Xe)}getLayer(t){return this.#ze.get(t)}get currentPageIndex(){return this.#Xe}addLayer(t){this.#ze.set(t.pageIndex,t);this.#hi?t.enable():t.disable()}removeLayer(t){this.#ze.delete(t.pageIndex)}async updateMode(t,e=null,n=!1){if(this.#mi!==t){if(this.#Pi){await this.#Pi.promise;if(!this.#Pi)return}this.#Pi=Promise.withResolvers();this.#mi=t;if(t!==i.AnnotationEditorType.NONE){this.setEditingState(!0);await this.#Wi();this.unselectAll();for(const e of this.#ze.values())e.updateMode(t);if(e){for(const t of this.#He.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode()}else t.unselect();this.#Pi.resolve()}else{n&&this.addNewEditorFromKeyboard();this.#Pi.resolve()}}else{this.setEditingState(!1);this.#$i();this._editorUndoBar?.hide();this.#Pi.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#mi&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#Ze){switch(t){case i.AnnotationEditorParamsType.CREATE:this.currentLayer.addNewEditor();return;case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:this.#pi?.updateColor(e);break;case i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#vi||=new Map).set(t,e);this.showAllEditors("highlight",e)}for(const i of this.#fi)i.updateParams(t,e);for(const i of this.#Ze)i.updateDefaultParams(t,e)}}showAllEditors(t,e,n=!1){for(const i of this.#He.values())i.editorType===t&&i.show(e);(this.#vi?.get(i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Ui([[i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#di!==t){this.#di=t;for(const e of this.#ze.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Wi(){if(!this.#hi){this.#hi=!0;const t=[];for(const e of this.#ze.values())t.push(e.enable());await Promise.all(t);for(const t of this.#He.values())t.enable()}}#$i(){this.unselectAll();if(this.#hi){this.#hi=!1;for(const t of this.#ze.values())t.disable();for(const t of this.#He.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#He.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#He.get(t)}addEditor(t){this.#He.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#ni&&clearTimeout(this.#ni);this.#ni=setTimeout((()=>{this.focusMainContainer();this.#ni=null}),0)}this.#He.delete(t.id);this.unselect(t);t.annotationElementId&&this.#Ke.has(t.annotationElementId)||this.#je?.remove(t.id)}addDeletedAnnotationElement(t){this.#Ke.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#Ke.has(t)}removeDeletedAnnotationElement(t){this.#Ke.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Hi(t){const e=this.#ze.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#Ve!==t){this.#Ve=t;t&&this.#Ui(t.propertiesToUpdate)}}get#Gi(){let t=null;for(t of this.#fi);return t}updateUI(t){this.#Gi===t&&this.#Ui(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Ui(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#fi.has(t)){this.#fi.delete(t);t.unselect();this.#ki({hasSelectedEditor:this.hasSelection})}else{this.#fi.add(t);t.select();this.#Ui(t.propertiesToUpdate);this.#ki({hasSelectedEditor:!0})}}setSelected(t){this.#qe?.commitOrRemove();for(const e of this.#fi)e!==t&&e.unselect();this.#fi.clear();this.#fi.add(t);t.select();this.#Ui(t.propertiesToUpdate);this.#ki({hasSelectedEditor:!0})}isSelected(t){return this.#fi.has(t)}get firstSelectedEditor(){return this.#fi.values().next().value}unselect(t){t.unselect();this.#fi.delete(t);this.#ki({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#fi.size}get isEnterHandled(){return 1===this.#fi.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#$e.undo();this.#ki({hasSomethingToUndo:this.#$e.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#ji()});this._editorUndoBar?.hide()}redo(){this.#$e.redo();this.#ki({hasSomethingToUndo:!0,hasSomethingToRedo:this.#$e.hasSomethingToRedo(),isEmpty:this.#ji()})}addCommands(t){this.#$e.add(t);this.#ki({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#ji()})}cleanUndoStack(t){this.#$e.cleanType(t)}#ji(){if(0===this.#He.size)return!0;if(1===this.#He.size)for(const t of this.#He.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#fi],undo=()=>{for(const t of e)this.#Hi(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#Ve?.commitOrRemove()}hasSomethingToControl(){return this.#Ve||this.hasSelection}#zi(t){for(const t of this.#fi)t.unselect();this.#fi.clear();for(const e of t)if(!e.isEmpty()){this.#fi.add(e);e.select()}this.#ki({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#fi)t.commit();this.#zi(this.#He.values())}unselectAll(){if(this.#Ve){this.#Ve.commitOrRemove();if(this.#mi!==i.AnnotationEditorType.NONE)return}if(!this.#qe?.commitOrRemove()&&this.hasSelection){for(const t of this.#fi)t.unselect();this.#fi.clear();this.#ki({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#Ai[0]+=t;this.#Ai[1]+=e;const[n,s]=this.#Ai,a=[...this.#fi];this.#xi&&clearTimeout(this.#xi);this.#xi=setTimeout((()=>{this.#xi=null;this.#Ai[0]=this.#Ai[1]=0;this.addCommands({cmd:()=>{for(const t of a)this.#He.has(t.id)&&t.translateInPage(n,s)},undo:()=>{for(const t of a)this.#He.has(t.id)&&t.translateInPage(-n,-s)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#Ye=new Map;for(const t of this.#fi)this.#Ye.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#Ye)return!1;this.disableUserSelect(!1);const t=this.#Ye;this.#Ye=null;let e=!1;for(const[{x:i,y:n,pageIndex:s},a]of t){a.newX=i;a.newY=n;a.newPageIndex=s;e||=i!==a.savedX||n!==a.savedY||s!==a.savedPageIndex}if(!e)return!1;const move=(t,e,i,n)=>{if(this.#He.has(t.id)){const s=this.#ze.get(n);if(s)t._setParentAndPosition(s,e,i);else{t.pageIndex=n;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:n,newPageIndex:s,savedX:a,savedY:r,savedPageIndex:o}]of t){move(e,i,n,s);this._eventBus?.dispatch("annotation-editor-event",{source:e,type:"moved",page:s+1,editorType:e.constructor.name,previousValue:{x:a,y:r,page:o+1},value:{x:i,y:n,page:s+1}})}},undo:()=>{for(const[e,{savedX:i,savedY:n,savedPageIndex:s}]of t)move(e,i,n,s)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#Ye)for(const i of this.#Ye.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#fi.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#Ve===t}getActive(){return this.#Ve}getMode(){return this.#mi}get imageManager(){return(0,i.shadow)(this,"imageManager",new ImageManager)}removeEditors(t=()=>!0){let e=!1;this.#He.forEach((i=>{if(i?.serialize()&&t(i.serialize())){i.remove();e=!0}}));if(e){this.#ki({hasSomethingToUndo:!1,hasSomethingToRedo:!1,isEmpty:this.#ji()});this.#$e.reset()}}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,n=e.rangeCount;i<n;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;const{x:i,y:n,width:s,height:a}=t.getBoundingClientRect();let r;switch(t.getAttribute("data-main-rotation")){case"90":r=(t,e,r,o)=>({x:(e-n)/a,y:1-(t+r-i)/s,width:o/a,height:r/s});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/s,y:1-(e+o-n)/a,width:r/s,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-n)/a,y:(t-i)/s,width:o/a,height:r/s});break;default:r=(t,e,r,o)=>({x:(t-i)/s,y:(e-n)/a,width:r/s,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;t<i;t++){const i=e.getRangeAt(t);if(!i.collapsed)for(const{x:t,y:e,width:n,height:s}of i.getClientRects())0!==n&&0!==s&&o.push(r(t,e,n,s))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#We||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#We?.delete(t)}renderAnnotationElement(t){const e=this.#We?.get(t.data.id);if(!e)return;const n=this.#je.getRawValue(e);n&&(this.#mi!==i.AnnotationEditorType.NONE||n.hasBeenModified)&&n.renderAnnotationElement(t)}}},814:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{TextLayer:()=>TextLayer});var i=e(292),n=e(419);const s=30;class TextLayer{#qi=Promise.withResolvers();#Ei=null;#Xi=!1;#Ki=!!globalThis.FontInspector?.enabled;#Yi=null;#Zi=null;#Qi=0;#Ji=0;#tn=null;#en=null;#in=0;#nn=0;#sn=Object.create(null);#an=[];#rn=null;#on=[];#ln=new WeakMap;#hn=null;static#dn=new Map;static#cn=new Map;static#un=new WeakMap;static#pn=null;static#gn=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#rn=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#rn=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#Ei=this.#en=e;this.#nn=i.scale*(globalThis.devicePixelRatio||1);this.#in=i.rotation;this.#Zi={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:a,pageX:r,pageY:o}=i.rawDims;this.#hn=[1,0,0,-1,-r,o+a];this.#Ji=s;this.#Qi=a;TextLayer.#mn();(0,n.setLayerDimensions)(e,i);this.#qi.promise.finally((()=>{TextLayer.#gn.delete(this);this.#Zi=null;this.#sn=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=i.FeatureTest.platform;return(0,i.shadow)(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#tn.read().then((({value:t,done:e})=>{if(e)this.#qi.resolve();else{this.#Yi??=t.lang;Object.assign(this.#sn,t.styles);this.#fn(t.items);pump()}}),this.#qi.reject)};this.#tn=this.#rn.getReader();TextLayer.#gn.add(this);pump();return this.#qi.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#in){e?.();this.#in=s;(0,n.setLayerDimensions)(this.#en,{rotation:s})}if(i!==this.#nn){e?.();this.#nn=i;const t={div:null,properties:null,ctx:TextLayer.#bn(this.#Yi)};for(const e of this.#on){t.properties=this.#ln.get(e);t.div=e;this.#wn(t)}}}cancel(){const t=new i.AbortException("TextLayer task cancelled.");this.#tn?.cancel(t).catch((()=>{}));this.#tn=null;this.#qi.reject(t)}get textDivs(){return this.#on}get textContentItemsStr(){return this.#an}#fn(t){if(this.#Xi)return;this.#Zi.ctx??=TextLayer.#bn(this.#Yi);const e=this.#on,n=this.#an;for(const s of t){if(e.length>1e5){(0,i.warn)("Ignoring additional textDivs for performance reasons.");this.#Xi=!0;return}if(void 0!==s.str){n.push(s.str);this.#vn(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#Ei;this.#Ei=document.createElement("span");this.#Ei.classList.add("markedContent");null!==s.id&&this.#Ei.setAttribute("id",`${s.id}`);t.append(this.#Ei)}else"endMarkedContent"===s.type&&(this.#Ei=this.#Ei.parentNode)}}#vn(t){const e=document.createElement("span"),n={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#on.push(e);const s=i.Util.transform(this.#hn,t.transform);let a=Math.atan2(s[1],s[0]);const r=this.#sn[t.fontName];r.vertical&&(a+=Math.PI/2);let o=this.#Ki&&r.fontSubstitution||r.fontFamily;o=TextLayer.fontFamilyMap.get(o)||o;const l=Math.hypot(s[2],s[3]),h=l*TextLayer.#yn(o,this.#Yi);let d,c;if(0===a){d=s[4];c=s[5]-h}else{d=s[4]+h*Math.sin(a);c=s[5]-h*Math.cos(a)}const u="calc(var(--scale-factor)*",p=e.style;if(this.#Ei===this.#en){p.left=`${(100*d/this.#Ji).toFixed(2)}%`;p.top=`${(100*c/this.#Qi).toFixed(2)}%`}else{p.left=`${u}${d.toFixed(2)}px)`;p.top=`${u}${c.toFixed(2)}px)`}p.fontSize=`${u}${(TextLayer.#pn*l).toFixed(2)}px)`;p.fontFamily=o;n.fontSize=l;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ki&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName);0!==a&&(n.angle=a*(180/Math.PI));let g=!1;if(t.str.length>1)g=!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&&(g=!0)}g&&(n.canvasWidth=r.vertical?t.height:t.width);this.#ln.set(e,n);this.#Zi.div=e;this.#Zi.properties=n;this.#wn(this.#Zi);n.hasText&&this.#Ei.append(e);if(n.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#Ei.append(t)}}#wn(t){const{div:e,properties:i,ctx:n}=t,{style:s}=e;let a="";TextLayer.#pn>1&&(a=`scale(${1/TextLayer.#pn})`);if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=s,{canvasWidth:r,fontSize:o}=i;TextLayer.#An(n,o*this.#nn,t);try{const{width:t}=n.measureText(e.textContent);t>0&&(a=`scaleX(${r*this.#nn/t}) ${a}`)}catch(t){}}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`);a.length>0&&(s.transform=a)}static cleanup(){if(!(this.#gn.size>0)){this.#dn.clear();for(const{canvas:t}of this.#cn.values())t.remove();this.#cn.clear()}}static#bn(t=null){let e=this.#cn.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;i.width=i.height=0;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#cn.set(t,e);this.#un.set(e,{size:0,family:""})}return e}static#An(t,e,i){const n=this.#un.get(t);if(e!==n.size||i!==n.family){t.font=`${e}px ${i}`;n.size=e;n.family=i}}static#mn(){if(null!==this.#pn)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.#pn=t.getBoundingClientRect().height;t.remove()}static#yn(t,e){const i=this.#dn.get(t);if(i)return i;const n=this.#bn(e);n.canvas.width=n.canvas.height=s;this.#An(n,s,t);const a=n.measureText("");let r=a?.fontBoundingBoxAscent,o=Math.abs(a?.fontBoundingBoxDescent);if(r){const e=r/(r+o);this.#dn.set(t,e);n.canvas.width=n.canvas.height=0;return e}n.strokeStyle="red";n.clearRect(0,0,s,s);n.strokeText("g",0,0);let l=n.getImageData(0,0,s,s).data;o=0;for(let t=l.length-1-3;t>=0;t-=4)if(l[t]>0){o=Math.ceil(t/4/s);break}n.clearRect(0,0,s,s);n.strokeText("A",0,s);l=n.getImageData(0,0,s,s).data;r=0;for(let t=0,e=l.length;t<e;t+=4)if(l[t]>0){r=s-Math.floor(t/4/s);break}n.canvas.width=n.canvas.height=0;const h=r?r/(r+o):.8;this.#dn.set(t,h);return h}}},900:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{TouchManager:()=>TouchManager});var i=e(292),n=e(419);class TouchManager{#Ei;#xn=!1;#En=null;#Sn;#Pn;#_n;#Cn;#Tn;#Mn=null;#In;#Dn=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:n=null,onPinching:s=null,onPinchEnd:a=null,signal:r}){this.#Ei=t;this.#En=i;this.#Sn=e;this.#Pn=n;this.#_n=s;this.#Cn=a;this.#In=new AbortController;this.#Tn=AbortSignal.any([r,this.#In.signal]);t.addEventListener("touchstart",this.#Ln.bind(this),{passive:!1,signal:this.#Tn})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return(0,i.shadow)(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#Ln(t){if(this.#Sn?.()||t.touches.length<2)return;if(!this.#Dn){this.#Dn=new AbortController;const t=AbortSignal.any([this.#Tn,this.#Dn.signal]),e=this.#Ei,i={signal:t,passive:!1};e.addEventListener("touchmove",this.#kn.bind(this),i);e.addEventListener("touchend",this.#Fn.bind(this),i);e.addEventListener("touchcancel",this.#Fn.bind(this),i);this.#Pn?.()}(0,n.stopEvent)(t);if(2!==t.touches.length||this.#En?.()){this.#Mn=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#Mn={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#kn(t){if(!this.#Mn||2!==t.touches.length)return;let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:n,screenY:s}=e,{screenX:a,screenY:r}=i,o=this.#Mn,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=a-n,m=r-s,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#xn&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=n;o.touch0Y=s;o.touch1X=a;o.touch1Y=r;t.preventDefault();if(!this.#xn){this.#xn=!0;return}const w=[(n+a)/2,(s+r)/2];this.#_n?.(w,b,f)}#Fn(t){this.#Dn.abort();this.#Dn=null;this.#Cn?.();if(this.#Mn){t.preventDefault();this.#Mn=null;this.#xn=!1}}destroy(){this.#In?.abort();this.#In=null}}},164:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{GlobalWorkerOptions:()=>GlobalWorkerOptions});class GlobalWorkerOptions{static#Rn=null;static#Nn="";static get workerPort(){return this.#Rn}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Rn=t}static get workerSrc(){return this.#Nn}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Nn=t}}},50:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{XfaText:()=>XfaText});class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const n=t.name;if("#text"===n)i=t.value;else{if(!XfaText.shouldBuildText(n))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}},909:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{AbortException:()=>i.AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>i.AnnotationEditorParamsType,AnnotationEditorType:()=>i.AnnotationEditorType,AnnotationEditorUIManager:()=>r.AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>i.AnnotationMode,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>i.FeatureTest,GlobalWorkerOptions:()=>u.GlobalWorkerOptions,ImageKind:()=>i.ImageKind,InvalidPDFException:()=>i.InvalidPDFException,MissingPDFException:()=>i.MissingPDFException,OPS:()=>i.OPS,OutputScale:()=>s.OutputScale,PDFDataRangeTransport:()=>n.PDFDataRangeTransport,PDFDateString:()=>s.PDFDateString,PDFWorker:()=>n.PDFWorker,PasswordResponses:()=>i.PasswordResponses,PermissionFlag:()=>i.PermissionFlag,PixelsPerInch:()=>s.PixelsPerInch,RenderingCancelledException:()=>s.RenderingCancelledException,TextLayer:()=>p.TextLayer,TouchManager:()=>g.TouchManager,UnexpectedResponseException:()=>i.UnexpectedResponseException,Util:()=>i.Util,VerbosityLevel:()=>i.VerbosityLevel,XfaLayer:()=>XfaLayer,build:()=>n.build,createValidAbsoluteUrl:()=>i.createValidAbsoluteUrl,fetchData:()=>s.fetchData,getDocument:()=>n.getDocument,getFilenameFromUrl:()=>s.getFilenameFromUrl,getPdfFilenameFromUrl:()=>s.getPdfFilenameFromUrl,getXfaPageViewport:()=>s.getXfaPageViewport,isDataScheme:()=>s.isDataScheme,isPdfFile:()=>s.isPdfFile,noContextMenu:()=>s.noContextMenu,normalizeUnicode:()=>i.normalizeUnicode,setLayerDimensions:()=>s.setLayerDimensions,shadow:()=>i.shadow,stopEvent:()=>s.stopEvent,version:()=>n.version});var i=e(292),n=e(925),s=e(419),a=e(310),r=e(830),o=e(792);function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,n]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+n)]}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=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(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(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,n]){return["RGB",1-Math.min(1,t+n),1-Math.min(1,i+n),1-Math.min(1,e+n)]}static CMYK_rgb([t,e,i,n]){return[scaleAndClamp(1-Math.min(1,t+n)),scaleAndClamp(1-Math.min(1,i+n)),scaleAndClamp(1-Math.min(1,e+n))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const n=1-t,s=1-e,a=1-i;return["CMYK",n,s,a,Math.min(n,s,a)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const n=this._createSVG("svg:svg");n.setAttribute("version","1.1");if(!i){n.setAttribute("width",`${t}px`);n.setAttribute("height",`${e}px`)}n.setAttribute("preserveAspectRatio","none");n.setAttribute("viewBox",`0 0 ${t} ${e}`);return n}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){(0,i.unreachable)("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(s.SVG_NS,t)}}var l=e(50);class XfaLayer{static setupStorage(t,e,i,n,s){const a=window.getFormValueFromAngular(t);a.value&&n.setValue(e,a);const r=n.getValue(e,{value:null}),o=a.value?a:r;window.registerXFAField(t,o,r);t.addEventListener("updateFromAngular",(t=>n.setValue(e,{value:t.detail})));switch(i.name){case"textarea":null!==o.value&&(t.textContent=o.value);if("print"===s)break;t.addEventListener("input",(i=>{window.updateAngularFormValue(t,{value:i.target.value});n.setValue(e,{value:i.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){o.value===i.attributes.xfaOn?t.setAttribute("checked",!0):t.removeAttribute("checked");if("print"===s)break;t.addEventListener("change",(i=>{window.updateAngularFormValue(t,{value:i.target.checked?i.target.getAttribute("xfaOn"):i.target.getAttribute("xfaOff")});n.setValue(e,{value:i.target.checked?i.target.getAttribute("xfaOn"):i.target.getAttribute("xfaOff")})}))}else{null!==o.value&&t.setAttribute("value",o.value);if("print"===s)break;t.addEventListener("input",(i=>{window.updateAngularFormValue(t,{value:i.target.value});n.setValue(e,{value:i.target.value})}))}break;case"select":if(null!==o.value){t.setAttribute("value",o.value);for(const t of i.children)t.attributes.value===o.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(i=>{const s=i.target.options,a=-1===s.selectedIndex?"":s[s.selectedIndex].value;window.updateAngularFormValue(t,{value:a});n.setValue(e,{value:a})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:n,linkService:s}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${n}`);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&&s.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,n=t.xfaHtml,s=t.intent||"display",a=document.createElement(n.name);n.attributes&&this.setAttributes({html:a,element:n,intent:s,linkService:i});const r="richText"!==s,o=t.div;o.append(a);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const h=[];if(0===n.children.length){if(n.value){const t=document.createTextNode(n.value);a.append(t);r&&l.XfaText.shouldBuildText(n.name)&&h.push(t)}return{textDivs:h}}const d=[[n,-1,a]];for(;d.length>0;){const[t,n,a]=d.at(-1);if(n+1===t.children.length){d.pop();continue}const o=t.children[++d.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);h.push(t);a.append(t);continue}const u=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);a.append(u);o.attributes&&this.setAttributes({html:u,element:o,storage:e,intent:s,linkService:i});if(o.children?.length>0)d.push([o,-1,u]);else if(o.value){const t=document.createTextNode(o.value);r&&l.XfaText.shouldBuildText(c)&&h.push(t);u.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:h}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const h=1e3,d=new WeakSet;function getRectDims(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case i.AnnotationType.LINK:return new LinkAnnotationElement(t);case i.AnnotationType.TEXT:return new TextAnnotationElement(t);case i.AnnotationType.WIDGET:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case i.AnnotationType.POPUP:return new PopupAnnotationElement(t);case i.AnnotationType.FREETEXT:return new FreeTextAnnotationElement(t);case i.AnnotationType.LINE:return new LineAnnotationElement(t);case i.AnnotationType.SQUARE:return new SquareAnnotationElement(t);case i.AnnotationType.CIRCLE:return new CircleAnnotationElement(t);case i.AnnotationType.POLYLINE:return new PolylineAnnotationElement(t);case i.AnnotationType.CARET:return new CaretAnnotationElement(t);case i.AnnotationType.INK:return new InkAnnotationElement(t);case i.AnnotationType.POLYGON:return new PolygonAnnotationElement(t);case i.AnnotationType.HIGHLIGHT:return new HighlightAnnotationElement(t);case i.AnnotationType.UNDERLINE:return new UnderlineAnnotationElement(t);case i.AnnotationType.SQUIGGLY:return new SquigglyAnnotationElement(t);case i.AnnotationType.STRIKEOUT:return new StrikeOutAnnotationElement(t);case i.AnnotationType.STAMP:return new StampAnnotationElement(t);case i.AnnotationType.FILEATTACHMENT:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Bn=null;#On=!1;#Vn=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:n=!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));n&&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 AnnotationElement._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Bn||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#Hn(e);this.#Vn?.popup.updateEdited(t)}resetEdited(){if(this.#Bn){this.#Hn(this.#Bn.rect);this.#Vn?.popup.resetEdited();this.#Bn=null}}#Hn(t){const{container:{style:e},data:{rect:i,rotation:n},parent:{viewport:{rawDims:{pageWidth:s,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=getRectDims(t);e.left=100*(t[0]-r)/s+"%";e.top=100*(a-t[3]+o)/a+"%";if(0===n){e.width=100*l/s+"%";e.height=100*h/a+"%"}else this.setRotation(n)}_createContainer(t){const{data:e,parent:{page:n,viewport:s}}=this,a=document.createElement("section");a.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||(a.tabIndex=h);const{style:r}=a;r.zIndex=this.parent.zIndex++;e.alternativeText&&(a.title=e.alternativeText);e.noRotate&&a.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,a);return a}const{width:o,height:l}=getRectDims(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,n=e.borderStyle.verticalCornerRadius;if(t>0||n>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${n}px * var(--scale-factor))`;r.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${o}px * var(--scale-factor)) / calc(${l}px * var(--scale-factor))`;r.borderRadius=t}switch(e.borderStyle.style){case i.AnnotationBorderStyleType.SOLID:r.borderStyle="solid";break;case i.AnnotationBorderStyleType.DASHED:r.borderStyle="dashed";break;case i.AnnotationBorderStyleType.BEVELED:(0,i.warn)("Unimplemented border style: beveled");break;case i.AnnotationBorderStyleType.INSET:(0,i.warn)("Unimplemented border style: inset");break;case i.AnnotationBorderStyleType.UNDERLINE:r.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#On=!0;r.borderColor=i.Util.makeHexColor(0|s[0],0|s[1],0|s[2])}else r.borderWidth=0}const d=i.Util.normalizeRect([e.rect[0],n.view[3]-e.rect[1]+n.view[1],e.rect[2],n.view[3]-e.rect[3]+n.view[1]]),{pageWidth:c,pageHeight:u,pageX:p,pageY:g}=s.rawDims;r.left=100*(d[0]-p)/c+"%";r.top=100*(d[1]-g)/u+"%";const{rotation:m}=e;if(e.hasOwnCanvas||0===m){r.width=100*o/c+"%";r.height=100*l/u+"%"}else this.setRotation(m,a);return a}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:n}=this.parent.viewport.rawDims,{width:s,height:a}=getRectDims(this.data.rect);let r,o;if(t%180==0){r=100*s/i;o=100*a/n}else{r=100*a/i;o=100*s/n}e.style.width=`${r}%`;e.style.height=`${o}%`;e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const n=i.detail[t],s=n[0],a=n.slice(1);i.target.style[e]=ColorConverters[`${s}_HTML`](a);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${s}_rgb`](a)})};return(0,i.shadow)(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:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},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 n of Object.keys(e.detail)){const s=t[n]||i[n];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[n,s]of Object.entries(e)){const a=i[n];if(a){a({detail:{[n]:s},target:t});delete e[n]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,n,s]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(n===a&&s===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#On){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0;r=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${t}" stroke-width="${e}">`];this.container.classList.add("hasBorder")}const o=n-e,l=s-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,n=t.length;i<n;i+=8){const n=t[i],a=t[i+1],d=t[i+2],c=t[i+3],p=h.createElement("rect"),g=(d-e)/o,m=(s-a)/l,f=(n-d)/o,b=(a-c)/l;p.setAttribute("x",g);p.setAttribute("y",m);p.setAttribute("width",f);p.setAttribute("height",b);u.append(p);r?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}if(this.#On){r.push("</g></svg>')");a.backgroundImage=r.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#Vn=new PopupAnnotationElement({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){(0,i.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const n=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:a,exportValues:r}of s){if(-1===t)continue;if(a===e)continue;const s="string"==typeof r?r:null,o=document.querySelector(`[data-element-id="${a}"]`);!o||d.has(o)?n.push({id:a,exportValue:s,domElement:o}):(0,i.warn)(`_getElementsByName - element not allowed: ${a}`)}return n}for(const i of document.getElementsByName(t)){const{exportValue:t}=i,s=i.getAttribute("data-element-id");s!==e&&(d.has(i)&&n.push({id:s,exportValue:t,domElement:i}))}return n}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 LinkAnnotationElement extends AnnotationElement{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 n=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);n=!0}else if(t.action){this._bindNamedAction(i,t.action);n=!0}else if(t.attachment){this.#zn(i,t.attachment,t.attachmentDest);n=!0}else if(t.setOCGState){this.#Un(i,t.setOCGState);n=!0}else if(t.dest){this._bindLink(i,t.dest);n=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);n=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);n=!0}else if(this.isTooltipOnly&&!n){this._bindLink(i,"");n=!0}}this.container.classList.add("linkAnnotation");n&&this.container.append(i);return this.container}#jn(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#jn()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};this.#jn()}#zn(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);return!1};this.#jn()}#Un(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};this.#jn()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(e.actions)){const s=i.get(n);s&&(t[s]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:n}});return!1})}t.onclick||(t.onclick=()=>!1);this.#jn()}_bindResetFormAction(t,e){const n=t.onclick;n||(t.href=this.linkService.getAnchorUrl(""));this.#jn();if(this._fieldObjects)t.onclick=()=>{n?.();const{fields:t,refs:s,include:a}=e,r=[];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)===a&&r.push(i)}else for(const t of Object.values(this._fieldObjects))r.push(...t);const o=this.annotationStorage,l=[];for(const t of r){const{id:e}=t;l.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";o.setValue(e,{value:i});window.updateAngularFormValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;o.setValue(e,{value:i});window.updateAngularFormValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";o.setValue(e,{value:i});window.updateAngularFormValue(e,{value:i});break}default:continue}const n=document.querySelector(`[data-element-id="${e}"]`);n&&(d.has(n)?n.dispatchEvent(new Event("resetform")):(0,i.warn)(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:l,name:"ResetForm"}});return!1};else{(0,i.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');n||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");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);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return i.FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,n,s){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t)}})}))}_setEventListeners(t,e,i,n){for(const[s,a]of i)if("Action"===a||this.data.actions?.[a]){"Focus"!==a&&"Blur"!==a||(e||={focused:!1});this._setEventListener(t,e,s,a,n);"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":i.Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:n}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,a=t.style;let r;const roundToOneDecimal=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/(i.LINE_FACTOR*s))||1);r=Math.min(s,roundToOneDecimal(e/i.LINE_FACTOR))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(s,roundToOneDecimal(t/i.LINE_FACTOR))}a.fontSize=`calc(${r}px * var(--scale-factor))`;a.color=i.Util.makeHexColor(n[0],n[1],n[2]);null!==this.data.textAlignment&&(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,n){const s=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id)){a.domElement&&(a.domElement[e]=i);s.setValue(a.id,{[n]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const n=window.getFormValueFromAngular(this.data.fieldName),s=t.getValue(e,{value:this.data.fieldValue}),a=n.value?n:s;if(n!==s){t.setValue(e,{value:n.value});a.formattedValue=n.value}let r=a.value||"";const o=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;o&&r.length>o&&(r=r.slice(0,o));let l=a.formattedValue||this.data.textContent?.join("\n")||null;l&&this.data.comb&&(l=l.replaceAll(/\s+/g,""));const c={userValue:r,formattedValue:l,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=l??r;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type="text";i.setAttribute("value",l??r);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);d.add(i);i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=h;this._setRequired(i,this.data.required);o&&(i.maxLength=o);i.addEventListener("input",(n=>{t.setValue(e,{value:n.target.value});window.updateAngularFormValue(e,{value:n.target.value});this.setPropertyOnSiblings(i,"value",n.target.value,"value");c.formattedValue=null}));i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=c.userValue=e;c.formattedValue=null}));let blurListener=t=>{const{formattedValue:e}=c;null!=e&&(t.target.value=e);t.target.scrollLeft=0};window.registerAcroformField(e,i,a.value,void 0,this.data.fieldValue);i.addEventListener("updateFromAngular",(i=>{c.formattedValue=null;t.setValue(e,{value:i.detail})}));if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(c.focused)return;const{target:e}=t;c.userValue&&(e.value=c.userValue);c.lastCommittedValue=e.value;c.commitKey=1;this.data.actions?.Focus||(c.focused=!0)}));i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const n={value(i){c.userValue=i.detail.value??"";t.setValue(e,{value:c.userValue.toString()});window.updateAngularFormValue(e,{value:c.userValue.toString()});i.target.value=c.userValue},formattedValue(i){const{formattedValue:n}=i.detail;c.formattedValue=n;null!=n&&i.target!==document.activeElement&&(i.target.value=n);t.setValue(e,{formattedValue:n});window.updateAngularFormValue(e,{formattedValue:n})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:n}=i.detail,{target:s}=i;if(0===n){s.removeAttribute("maxLength");return}s.setAttribute("maxLength",n);let a=c.userValue;if(a&&!(a.length<=n)){a=a.slice(0,n);s.value=c.userValue=a;t.setValue(e,{value:a});window.updateAngularFormValue(e,{value:a});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:s.selectionStart,selEnd:s.selectionEnd}})}}};this._dispatchEventFromSandbox(n,i)}));i.addEventListener("keydown",(t=>{c.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(c.commitKey=3):i=2;if(-1===i)return;const{value:n}=t.target;if(c.lastCommittedValue!==n){c.lastCommittedValue=n;c.userValue=n;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const n=blurListener;blurListener=null;i.addEventListener("blur",(t=>{if(!c.focused)return;this.data.actions?.Blur||(c.focused=!1);const{value:i}=t.target;c.userValue=i;c.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:c.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});n(t)}));this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{c.lastCommittedValue=null;const{data:i,target:n}=t,{value:s,selectionStart:a,selectionEnd:r}=n;let o=a,l=r;switch(t.inputType){case"deleteWordBackward":{const t=s.substring(0,a).match(/\w*[^\w]*$/);t&&(o-=t[0].length);break}case"deleteWordForward":{const t=s.substring(a).match(/^[^\w]*\w*/);t&&(l+=t[0].length);break}case"deleteContentBackward":a===r&&(o-=1);break;case"deleteContentForward":a===r&&(l+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,change:i||"",willCommit:!1,selStart:o,selEnd:l}})}));this._setEventListeners(i,c,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/o;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)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id,n=window.getFormValueFromAngular(this.data.fieldName),s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;let a;n.value&&(a=!0===n.value||n.value===e.exportValue);let r=void 0!==a?a:s,o=!1;if("string"==typeof r){r=r===e.exportValue;t.setValue(i,{value:r});o=!0}else if(void 0!==n?.value&&n.value!==s){r=!0===n.value||n.value===e.exportValue?e.exportValue:void 0;t.setValue(i,{value:r})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const l=document.createElement("input");d.add(l);l.setAttribute("data-element-id",i);l.disabled=e.readOnly;this._setRequired(l,this.data.required);l.type="checkbox";l.name=e.fieldName;r&&l.setAttribute("checked",!0);l.setAttribute("exportValue",e.exportValue);l.tabIndex=h;l.addEventListener("change",(n=>{const{name:s,checked:a}=n.target;for(const n of this._getElementsByName(s,i)){const s=a&&n.exportValue===e.exportValue;n.domElement&&(n.domElement.checked=s);t.setValue(n.id,{value:s});window.updateAngularFormValue(i,{value:s})}t.setValue(i,{value:a});window.updateAngularFormValue(i,{value:a})}));l.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}));window.registerAcroformField(i,l,r?e.exportValue:void 0,void 0,this.data.fieldValue);l.addEventListener("updateFromAngular",(e=>t.setValue(i,{value:e.detail})));o&&window.updateAngularFormValue(i,{value:r});if(this.enableScripting&&this.hasJSActions){l.addEventListener("updatefromsandbox",(e=>{const n={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked});window.updateAngularFormValue(i,{value:e.target.value})}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(l,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(l);this._setDefaultPropertiesFromJS(l);this.container.append(l);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id,n=window.getFormValueFromAngular(this.data.fieldName),s=e.fieldValue===e.buttonValue?e.buttonValue:void 0,a=t.getValue(i,{value:s}).value;let r=n.value??a;if("string"==typeof r||n!==a){r=r===e.buttonValue;t.setValue(i,{value:r})}else r&&window.updateAngularFormValue(i,{value:e.buttonValue});if(r)for(const n of this._getElementsByName(e.fieldName,i))t.setValue(n.id,{value:!1});const o=document.createElement("input");d.add(o);o.setAttribute("data-element-id",i);o.disabled=e.readOnly;this._setRequired(o,this.data.required);o.type="radio";o.name=e.fieldName;r&&o.setAttribute("checked",!0);o.tabIndex=h;o.addEventListener("change",(e=>{const{name:n,checked:s}=e.target;for(const e of this._getElementsByName(n,i)){t.setValue(e.id,{value:!1});window.updateAngularFormValue(e.id,{value:!1})}t.setValue(i,{value:s});window.updateAngularFormValue(i,{value:s})}));o.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}));window.registerAcroformField(i,o,r?e.buttonValue:void 0,e.buttonValue,this.data.fieldValue);o.addEventListener("updateFromAngular",(e=>t.setValue(i,{value:e.detail})));if(this.enableScripting&&this.hasJSActions){const n=e.buttonValue;o.addEventListener("updatefromsandbox",(e=>{const s={value:e=>{const s=n===e.detail.value;for(const n of this._getElementsByName(e.target.name)){const e=s&&n.id===i;n.domElement&&(n.domElement.checked=e);t.setValue(n.id,{value:e});window.updateAngularFormValue(i,{value:e})}}};this._dispatchEventFromSandbox(s,e)}));this._setEventListeners(o,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(o);this._setDefaultPropertiesFromJS(o);this.container.append(o);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=window.getFormValueFromAngular(this.data.fieldName),n=t.getValue(e,{value:this.data.fieldValue}),s=i.value?i:n;i!==n&&t.setValue(e,{value:i.value});const a=document.createElement("select");d.add(a);a.setAttribute("data-element-id",e);a.disabled=this.data.readOnly;this._setRequired(a,this.data.required);a.name=this.data.fieldName;a.tabIndex=h;let r=this.data.combo&&this.data.options.length>0;if(!this.data.combo){a.size=this.data.options.length;this.data.multiSelect&&(a.multiple=!0)}a.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of a.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;if(s.value.includes(t.exportValue)){e.setAttribute("selected",!0);r=!1}a.append(e)}let o=null;if(r){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);a.prepend(t);o=()=>{t.remove();a.removeEventListener("input",o);o=null};a.addEventListener("input",o)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=a;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let l=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};window.registerAcroformField(e,a,l,void 0,this.data.fieldValue);a.addEventListener("updateFromAngular",(i=>t.setValue(e,{value:i.detail})));if(this.enableScripting&&this.hasJSActions){a.addEventListener("updatefromsandbox",(i=>{const n={value(i){o?.();const n=i.detail.value,s=new Set(Array.isArray(n)?n:[n]);for(const t of a.options)t.selected=s.has(t.value);t.setValue(e,{value:getValue(!0)});l=getValue(!1);window.updateAngularFormValue(e,{value:l})},multipleSelection(t){a.multiple=!0},remove(i){const n=a.options,s=i.detail.remove;n[s].selected=!1;a.remove(s);if(n.length>0){-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});l=getValue(!1)},clear(i){for(;0!==a.length;)a.remove(0);t.setValue(e,{value:null,items:[]});l=getValue(!1);window.updateAngularFormValue(e,{value:l})},insert(i){const{index:n,displayValue:s,exportValue:r}=i.detail.insert,o=a.children[n],h=document.createElement("option");h.textContent=s;h.value=r;o?o.before(h):a.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});l=getValue(!1);window.updateAngularFormValue(e,{value:l})},items(i){const{items:n}=i.detail;for(;0!==a.length;)a.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e;n.value=i;a.append(n)}a.options.length>0&&(a.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});l=getValue(!1);window.updateAngularFormValue(e,{value:l})},indices(i){const n=new Set(i.detail.indices);for(const t of i.target.options)t.selected=n.has(t.index);t.setValue(e,{value:getValue(!0)});l=getValue(!1);window.updateAngularFormValue(e,{value:l})},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)}));a.addEventListener("input",(i=>{const n=getValue(!0),s=getValue(!1);t.setValue(e,{value:n});window.updateAngularFormValue(e,{value:n});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:l,change:s,changeEx:n,willCommit:!1,commitKey:1,keyDown:!1}})}));this._setEventListeners(a,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))}else a.addEventListener("input",(function(i){t.setValue(e,{value:getValue(!0)});window.updateAngularFormValue(e,{value:getValue(!0)})}));this.data.combo&&this._setTextStyle(a);this._setBackgroundColor(a);this._setDefaultPropertiesFromJS(a);this.container.append(a);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:AnnotationElement._hasPopupData(e)});this.elements=i;this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new PopupElement({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;i.container.ariaHasPopup="dialog";e.push(i.data.id);i.addHighlightArea()}this.container.setAttribute("aria-controls",e.map((t=>`${i.AnnotationPrefix}${t}`)).join(","));return this.container}}class PopupElement{#Wn=this.#$n.bind(this);#Gn=this.#qn.bind(this);#Xn=this.#Kn.bind(this);#Yn=this.#Zn.bind(this);#Qn=null;#Ei=null;#Jn=null;#ts=null;#es=null;#is=null;#ns=null;#ss=!1;#as=null;#Ne=null;#rs=null;#os=null;#ls=null;#Bn=null;#hs=!1;constructor({container:t,color:e,elements:i,titleObj:n,modificationDate:a,contentsObj:r,richText:o,parent:l,rect:h,parentRect:d,open:c}){this.#Ei=t;this.#ls=n;this.#Jn=r;this.#os=o;this.#is=l;this.#Qn=e;this.#rs=h;this.#ns=d;this.#es=i;this.#ts=s.PDFDateString.toDateObject(a);this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger){t.addEventListener("click",this.#Yn);t.addEventListener("mouseenter",this.#Xn);t.addEventListener("mouseleave",this.#Gn);t.classList.add("popupTriggerArea")}for(const t of i)t.container?.addEventListener("keydown",this.#Wn);this.#Ei.hidden=!0;c&&this.#Zn()}render(){if(this.#as)return;const t=this.#as=document.createElement("div");t.className="popup";if(this.#Qn){const e=t.style.outlineColor=i.Util.makeHexColor(...this.#Qn);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=i.Util.makeHexColor(...this.#Qn.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const n=document.createElement("h1");e.append(n);({dir:n.dir,str:n.textContent}=this.#ls);t.append(e);if(this.#ts){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.#ts.valueOf()}));e.append(t)}const s=this.#ds;if(s){XfaLayer.render({xfaHtml:s,intent:"richText",div:t});t.lastChild.classList.add("richText","popupContent")}else{const e=this._formatContents(this.#Jn);t.append(e)}this.#Ei.append(t)}get#ds(){const t=this.#os,e=this.#Jn;return!t?.str||e?.str&&e.str!==t.str?null:this.#os.html||null}get#cs(){return this.#ds?.attributes?.style?.fontSize||0}get#us(){return this.#ds?.attributes?.style?.color||null}#ps(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},n={style:{color:this.#us,fontSize:this.#cs?`calc(${this.#cs}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:n});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent");i.dir=e;const n=t.split(/(?:\r\n?|\n)/);for(let t=0,e=n.length;t<e;++t){const s=n[t];i.append(document.createTextNode(s));t<e-1&&i.append(document.createElement("br"))}return i}#$n(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#ss)&&this.#Zn()}updateEdited({rect:t,popupContent:e}){this.#Bn||={contentsObj:this.#Jn,richText:this.#os};t&&(this.#Ne=null);if(e){this.#os=this.#ps(e);this.#Jn=null}this.#as?.remove();this.#as=null}resetEdited(){if(this.#Bn){({contentsObj:this.#Jn,richText:this.#os}=this.#Bn);this.#Bn=null;this.#as?.remove();this.#as=null;this.#Ne=null}}#gs(){if(null!==this.#Ne)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:n,pageX:s,pageY:a}}}=this.#is;let r=!!this.#ns,o=r?this.#ns:this.#rs;for(const t of this.#es)if(!o||null!==i.Util.intersect(t.data.rect,o)){o=t.data.rect;r=!0;break}const l=i.Util.normalizeRect([o[0],t[3]-o[1]+t[1],o[2],t[3]-o[3]+t[1]]),h=r?o[2]-o[0]+5:0,d=l[0]+h,c=l[1];this.#Ne=[100*(d-s)/e,100*(c-a)/n];const{style:u}=this.#Ei;u.left=`${this.#Ne[0]}%`;u.top=`${this.#Ne[1]}%`}#Zn(){this.#ss=!this.#ss;if(this.#ss){this.#Kn();this.#Ei.addEventListener("click",this.#Yn);this.#Ei.addEventListener("keydown",this.#Wn)}else{this.#qn();this.#Ei.removeEventListener("click",this.#Yn);this.#Ei.removeEventListener("keydown",this.#Wn)}}#Kn(){this.#as||this.render();if(this.isVisible)this.#ss&&this.#Ei.classList.add("focused");else{this.#gs();this.#Ei.hidden=!1;this.#Ei.style.zIndex=parseInt(this.#Ei.style.zIndex)+1e3;const t=this.#Ei.closest(".page");t&&(t.style.overflow="visible")}}#qn(){this.#Ei.classList.remove("focused");if(this.#ss||!this.isVisible)return;this.#Ei.hidden=!0;this.#Ei.style.zIndex=parseInt(this.#Ei.style.zIndex)-1e3;const t=this.#Ei.closest(".page");t&&(t.style.overflow="")}forceHide(){this.#hs=this.isVisible;this.#hs&&(this.#Ei.hidden=!0)}maybeShow(){if(this.#hs){this.#as||this.#Kn();this.#hs=!1;this.#Ei.hidden=!1}}get isVisible(){return!1===this.#Ei.hidden}}class FreeTextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.textContent=t.data.textContent;this.textPosition=t.data.textPosition;this.annotationEditorType=i.AnnotationEditorType.FREETEXT}render(){this.container.classList.add("freeTextAnnotation");if(this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent");t.setAttribute("role","comment");for(const e of this.textContent){const i=document.createElement("span");i.textContent=e;t.append(i)}this.container.append(t)}!this.data.popupRef&&this.hasPopupData&&this._createPopup();this._editOnDoubleClick();return this.container}}class LineAnnotationElement extends AnnotationElement{#ms=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:i}=getRectDims(t.rect),n=this.svgFactory.create(e,i,!0),s=this.#ms=this.svgFactory.createElement("svg:line");s.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]);s.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]);s.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]);s.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]);s.setAttribute("stroke-width",t.borderStyle.width||1);s.setAttribute("stroke","transparent");s.setAttribute("fill","transparent");n.append(s);this.container.append(n);!t.popupRef&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#ms}addHighlightArea(){this.container.classList.add("highlightArea")}}class SquareAnnotationElement extends AnnotationElement{#fs=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:i}=getRectDims(t.rect),n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,a=this.#fs=this.svgFactory.createElement("svg:rect");a.setAttribute("x",s/2);a.setAttribute("y",s/2);a.setAttribute("width",e-s);a.setAttribute("height",i-s);a.setAttribute("stroke-width",s||1);a.setAttribute("stroke","transparent");a.setAttribute("fill","transparent");n.append(a);this.container.append(n);!t.popupRef&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#fs}addHighlightArea(){this.container.classList.add("highlightArea")}}class CircleAnnotationElement extends AnnotationElement{#bs=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:i}=getRectDims(t.rect),n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,a=this.#bs=this.svgFactory.createElement("svg:ellipse");a.setAttribute("cx",e/2);a.setAttribute("cy",i/2);a.setAttribute("rx",e/2-s/2);a.setAttribute("ry",i/2-s/2);a.setAttribute("stroke-width",s||1);a.setAttribute("stroke","transparent");a.setAttribute("fill","transparent");n.append(a);this.container.append(n);!t.popupRef&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#bs}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolylineAnnotationElement extends AnnotationElement{#ws=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="polylineAnnotation";this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:i,popupRef:n}}=this;if(!e)return this.container;const{width:s,height:a}=getRectDims(t),r=this.svgFactory.create(s,a,!0);let o=[];for(let i=0,n=e.length;i<n;i+=2){const n=e[i]-t[0],s=t[3]-e[i+1];o.push(`${n},${s}`)}o=o.join(" ");const l=this.#ws=this.svgFactory.createElement(this.svgElementName);l.setAttribute("points",o);l.setAttribute("stroke-width",i.width||1);l.setAttribute("stroke","transparent");l.setAttribute("fill","transparent");r.append(l);this.container.append(r);!n&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#ws}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolygonAnnotationElement extends PolylineAnnotationElement{constructor(t){super(t);this.containerClassName="polygonAnnotation";this.svgElementName="svg:polygon"}}class CaretAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("caretAnnotation");!this.data.popupRef&&this.hasPopupData&&this._createPopup();return this.container}}class InkAnnotationElement extends AnnotationElement{#vs=null;#ys=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="inkAnnotation";this.svgElementName="svg:polyline";this.annotationEditorType="InkHighlight"===this.data.it?i.AnnotationEditorType.HIGHLIGHT:i.AnnotationEditorType.INK}#As(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:i,borderStyle:n,popupRef:s}}=this,{transform:a,width:r,height:o}=this.#As(e,t),l=this.svgFactory.create(r,o,!0),h=this.#vs=this.svgFactory.createElement("svg:g");l.append(h);h.setAttribute("stroke-width",n.width||1);h.setAttribute("stroke-linecap","round");h.setAttribute("stroke-linejoin","round");h.setAttribute("stroke-miterlimit",10);h.setAttribute("stroke","transparent");h.setAttribute("fill","transparent");h.setAttribute("transform",a);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#ys.push(e);e.setAttribute("points",i[t].join(","));h.append(e)}!s&&this.hasPopupData&&this._createPopup();this.container.append(l);this._editOnDoubleClick();return this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:n}=t,s=this.#vs;e>=0&&s.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#ys.length;t<e;t++)this.#ys[t].setAttribute("points",i[t].join(","));if(n){const{transform:t,width:e,height:i}=this.#As(this.data.rotation,n);s.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`);s.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#ys}addHighlightArea(){this.container.classList.add("highlightArea")}}class HighlightAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0});this.annotationEditorType=i.AnnotationEditorType.HIGHLIGHT}render(){!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.classList.add("highlightAnnotation");this._editOnDoubleClick();return this.container}}class UnderlineAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.classList.add("underlineAnnotation");return this.container}}class SquigglyAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.classList.add("squigglyAnnotation");return this.container}}class StrikeOutAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.classList.add("strikeoutAnnotation");return this.container}}class StampAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.annotationEditorType=i.AnnotationEditorType.STAMP}render(){this.container.classList.add("stampAnnotation");this.container.setAttribute("role","img");!this.data.popupRef&&this.hasPopupData&&this._createPopup();this._editOnDoubleClick();return this.container}}class FileAttachmentAnnotationElement extends AnnotationElement{#xs=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename;this.content=e.content;this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let n;if(e.hasAppearance||0===e.fillAlpha)n=document.createElement("div");else{n=document.createElement("img");n.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`;e.fillAlpha&&e.fillAlpha<1&&(n.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)}n.addEventListener("dblclick",this.#Es.bind(this));this.#xs=n;const{isMac:s}=i.FeatureTest.platform;t.addEventListener("keydown",(t=>{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Es()}));!e.popupRef&&this.hasPopupData?this._createPopup():n.classList.add("popupTriggerArea");t.append(n);return t}getElementsToTriggerPopup(){return this.#xs}addHighlightArea(){this.container.classList.add("highlightArea")}#Es(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Ss=null;#Ps=null;#_s=new Map;#Cs=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:n,page:s,viewport:a,structTreeLayer:r}){this.div=t;this.#Ss=e;this.#Ps=i;this.#Cs=r||null;this.page=s;this.viewport=a;this.zIndex=0;this._annotationEditorUIManager=n}hasEditableAnnotations(){return this.#_s.size>0}async#Ts(t,e){const n=t.firstChild||t,s=n.id=`${i.AnnotationPrefix}${e}`,a=await(this.#Cs?.getAriaAttributes(s));if(a)for(const[t,e]of a)n.setAttribute(t,e);this.div.append(t);this.#Ss?.moveElementInDOM(this.div,t,n,!1)}async render(t){const{annotations:e}=t,n=this.div;(0,s.setLayerDimensions)(n,this.viewport);const a=new Map,r={data:null,layer:n,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:t.annotationStorage||new o.AnnotationStorage,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=t.annotationType===i.AnnotationType.POPUP;if(e){const e=a.get(t.id);if(!e)continue;r.elements=e}else{const{width:e,height:i}=getRectDims(t.rect);if(e<=0||i<=0)continue}r.data=t;const n=AnnotationElementFactory.create(r);if(!n.isRenderable)continue;if(!e&&t.popupRef){const e=a.get(t.popupRef);e?e.push(n):a.set(t.popupRef,[n])}const s=n.render();t.hidden&&(s.style.visibility="hidden");await this.#Ts(s,t.id);if(n._isEditable){this.#_s.set(n.data.id,n);this._annotationEditorUIManager?.renderAnnotationElement(n)}}this.#Ms()}update({viewport:t}){const e=this.div;this.viewport=t;(0,s.setLayerDimensions)(e,{rotation:t.rotation});this.#Ms();e.hidden=!1}#Ms(){if(!this.#Ps)return;const t=this.div;for(const[e,i]of this.#Ps){const n=t.querySelector(`[data-annotation-id="${e}"]`);if(!n)continue;i.className="annotationContent";const{firstChild:s}=n;s?"CANVAS"===s.nodeName?s.replaceWith(i):s.classList.contains("annotationContent")?s.after(i):s.before(i):n.append(i)}this.#Ps.clear()}getEditableAnnotations(){return Array.from(this.#_s.values())}getEditableAnnotation(t){return this.#_s.get(t)}}const c=/\r\n?|\n/g;class FreeTextEditor extends a.AnnotationEditor{#Qn;#Is="";#Ds=`${this.id}-editor`;#Ls=null;#cs;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=r.AnnotationEditorUIManager.TRANSLATE_SMALL,n=r.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new r.KeyboardManager([[["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:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-n,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[n,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-n],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,n],checker:arrowChecker}]]))}static _type="freetext";static _editorType=i.AnnotationEditorType.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.#Qn=t.color||FreeTextEditor._defaultColor||a.AnnotationEditor._defaultLineColor;this.#cs=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t,e){a.AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case i.AnnotationEditorParamsType.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case i.AnnotationEditorParamsType.FREETEXT_SIZE:this.#ks(e);break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:this.#Fs(e)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[i.AnnotationEditorParamsType.FREETEXT_COLOR,FreeTextEditor._defaultColor||a.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,this.#cs],[i.AnnotationEditorParamsType.FREETEXT_COLOR,this.#Qn]]}#ks(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`;this.translate(0,-(t-this.#cs)*this.parentScale);this.#cs=t;this.#Rs()},e=this.#cs;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0});this.eventBus?.dispatch("annotation-editor-event",{source:this,type:"fontSizeChanged",page:this.pageIndex+1,editorType:this.constructor.name,value:t,previousValue:this.#cs})}#Fs(t){const setColor=t=>{this.#Qn=this.editorDiv.style.color=t},e=this.#Qn;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this.eventBus?.dispatch("annotation-editor-event",{source:this,type:"colorChanged",page:this.pageIndex+1,editorType:this.constructor.name,value:t,previousValue:this.#Qn})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#cs)*t]}rebuild(){if(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(i.AnnotationEditorType.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#Ls=new AbortController;const t=this._uiManager.combinedSignal(this.#Ls);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(){if(this.isInEditMode()){this.parent.setEditingState(!0);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#Ds);this._isDraggable=!0;this.#Ls?.abort();this.#Ls=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing")}}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#Ns(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#Bs(i));e=i}return t.join("\n")}#Rs(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,n=e.style.display,s=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=n;e.classList.toggle("hidden",s)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Is,e=this.#Is=this.#Ns().trimEnd();if(t===e)return;const setText=t=>{this.#Is=t;if(t){this.#Os();this._uiManager.rebuild(this);this.#Rs()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#Rs();this.eventBus?.dispatch("annotation-editor-event",{source:this,type:"commit",page:this.pageIndex+1,value:e,previousValue:t})}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._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;if(this.width){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#Ds);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#cs}px * var(--scale-factor))`;i.color=this.#Qn;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);(0,r.bindEvents)(this,this.div,["dblclick","keydown"]);if(this.width){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:s}=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+(s[0]-h)/o;u=e+this.height-(s[1]-d)/l;break;case 90:c=t+(s[0]-h)/o;u=e-(s[1]-d)/l;[a,r]=[r,-a];break;case 180:c=t-this.width+(s[0]-h)/o;u=e-(s[1]-d)/l;[a,r]=[-a,-r];break;case 270:c=t+(s[0]-h-this.height*l)/o;u=e+(s[1]-d-this.width*o)/l;[a,r]=[-r,a]}this.setAt(c*i,u*n,a,r)}else this.setAt(t*i,e*n,this.width*i,this.height*n);this.#Os();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Bs(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(c,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const n=FreeTextEditor.#Vs(e.getData("text")||"").replaceAll(c,"\n");if(!n)return;const s=window.getSelection();if(!s.rangeCount)return;this.editorDiv.normalize();s.deleteFromDocument();const a=s.getRangeAt(0);if(!n.includes("\n")){a.insertNode(document.createTextNode(n));this.editorDiv.normalize();s.collapseToStart();return}const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;h.push(r.nodeValue.slice(o).replaceAll(c,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Bs(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(c,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Bs(i))}}this.#Is=`${l.join("\n")}${n}${h.join("\n")}`;this.#Os();const d=new Range;let u=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(u<=e){d.setStart(t,u);d.setEnd(t,u);break}u-=e}s.removeAllRanges();s.addRange(d)}#Os(){this.editorDiv.replaceChildren();if(this.#Is)for(const t of this.#Is.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Hs(){return this.#Is.replaceAll(" "," ")}static#Vs(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,n){let s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:n},rect:a,rotation:r,id:o,popupRef:l},textContent:h,textPosition:d,parent:{page:{pageNumber:c}}}=t;if(!h||0===h.length)return null;s=t={annotationType:i.AnnotationEditorType.FREETEXT,color:Array.from(n),fontSize:e,value:h.join("\n"),position:d,pageIndex:c-1,rect:a.slice(0),rotation:r,id:o,deleted:!1,popupRef:l}}const a=await super.deserialize(t,e,n);a.#cs=t.fontSize;a.#Qn=i.Util.makeHexColor(...t.color);a.#Is=FreeTextEditor.#Vs(t.value);a.annotationElementId=t.id||null;a._initialData=s;return a}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=FreeTextEditor._internalPadding*this.parentScale,n=this.getRect(e,e),s=a.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#Qn),r={annotationType:i.AnnotationEditorType.FREETEXT,color:s,fontSize:this.#cs,value:this.#Hs(),pageIndex:this.pageIndex,rect:n,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t)return r;if(this.annotationElementId&&!this.#zs(r))return null;r.id=this.annotationElementId;return r}#zs(t){const{value:e,fontSize:i,color:n,pageIndex:s}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==n[e]))||t.pageIndex!==s}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#cs}px * var(--scale-factor))`;i.color=this.#Qn;e.replaceChildren();for(const t of this.#Is.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}const n=FreeTextEditor._internalPadding*this.parentScale;t.updateEdited({rect:this.getRect(n,n),popupContent:this.#Is});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){(0,i.unreachable)("Abstract method `toSVGPath` must be implemented.")}get box(){(0,i.unreachable)("Abstract getter `box` must be implemented.")}serialize(t,e){(0,i.unreachable)("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,n,s,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2){a[r]=e+t[r]*n;a[r+1]=i+t[r+1]*s}return a}static _rescaleAndSwap(t,e,i,n,s,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2){a[r]=e+t[r+1]*n;a[r+1]=i+t[r]*s}return a}static _translate(t,e,i,n){n||=new Float32Array(t.length);for(let s=0,a=t.length;s<a;s+=2){n[s]=e+t[s];n[s+1]=i+t[s+1]}return n}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,n,s){switch(s){case 90:return[1-e/i,t/n];case 180:return[1-t/i,1-e/n];case 270:return[e/i,1-t/n];default:return[t/i,e/n]}}static _normalizePagePoint(t,e,i){switch(i){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,i,n,s,a){return[(t+5*i)/6,(e+5*n)/6,(5*i+s)/6,(5*n+a)/6,(i+s)/2,(n+a)/2]}}class FreeDrawOutliner{#Us;#js=[];#Ws;#$s;#Gs=[];#qs=new Float32Array(18);#Xs;#Ks;#Ys;#Zs;#Qs;#Js;#ta=[];static#ea=8;static#ia=2;static#na=FreeDrawOutliner.#ea+FreeDrawOutliner.#ia;constructor({x:t,y:e},i,n,s,a,r=0){this.#Us=i;this.#Js=s*n;this.#$s=a;this.#qs.set([NaN,NaN,NaN,NaN,t,e],6);this.#Ws=r;this.#Zs=FreeDrawOutliner.#ea*n;this.#Ys=FreeDrawOutliner.#na*n;this.#Qs=n;this.#ta.push(t,e)}isEmpty(){return isNaN(this.#qs[8])}#sa(){const t=this.#qs.subarray(4,6),e=this.#qs.subarray(16,18),[i,n,s,a]=this.#Us;return[(this.#Xs+(t[0]-e[0])/2-i)/s,(this.#Ks+(t[1]-e[1])/2-n)/a,(this.#Xs+(e[0]-t[0])/2-i)/s,(this.#Ks+(e[1]-t[1])/2-n)/a]}add({x:t,y:e}){this.#Xs=t;this.#Ks=e;const[i,n,s,a]=this.#Us;let[r,o,l,h]=this.#qs.subarray(8,12);const d=t-l,c=e-h,u=Math.hypot(d,c);if(u<this.#Ys)return!1;const p=u-this.#Zs,g=p/u,m=g*d,f=g*c;let b=r,w=o;r=l;o=h;l+=m;h+=f;this.#ta?.push(t,e);const v=m/p,y=-f/p*this.#Js,A=v*this.#Js;this.#qs.set(this.#qs.subarray(2,8),0);this.#qs.set([l+y,h+A],4);this.#qs.set(this.#qs.subarray(14,18),12);this.#qs.set([l-y,h-A],16);if(isNaN(this.#qs[6])){if(0===this.#Gs.length){this.#qs.set([r+y,o+A],2);this.#Gs.push(NaN,NaN,NaN,NaN,(r+y-i)/s,(o+A-n)/a);this.#qs.set([r-y,o-A],14);this.#js.push(NaN,NaN,NaN,NaN,(r-y-i)/s,(o-A-n)/a)}this.#qs.set([b,w,r,o,l,h],6);return!this.isEmpty()}this.#qs.set([b,w,r,o,l,h],6);if(Math.abs(Math.atan2(w-o,b-r)-Math.atan2(f,m))<Math.PI/2){[r,o,l,h]=this.#qs.subarray(2,6);this.#Gs.push(NaN,NaN,NaN,NaN,((r+l)/2-i)/s,((o+h)/2-n)/a);[r,o,b,w]=this.#qs.subarray(14,18);this.#js.push(NaN,NaN,NaN,NaN,((b+r)/2-i)/s,((w+o)/2-n)/a);return!0}[b,w,r,o,l,h]=this.#qs.subarray(0,6);this.#Gs.push(((b+5*r)/6-i)/s,((w+5*o)/6-n)/a,((5*r+l)/6-i)/s,((5*o+h)/6-n)/a,((r+l)/2-i)/s,((o+h)/2-n)/a);[l,h,r,o,b,w]=this.#qs.subarray(12,18);this.#js.push(((b+5*r)/6-i)/s,((w+5*o)/6-n)/a,((5*r+l)/6-i)/s,((5*o+h)/6-n)/a,((r+l)/2-i)/s,((o+h)/2-n)/a);return!0}toSVGPath(){if(this.isEmpty())return"";const t=this.#Gs,e=this.#js;if(isNaN(this.#qs[6])&&!this.isEmpty())return this.#aa();const i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#ra(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#oa(i);return i.join(" ")}#aa(){const[t,e,i,n]=this.#Us,[s,a,r,o]=this.#sa();return`M${(this.#qs[2]-t)/i} ${(this.#qs[3]-e)/n} L${(this.#qs[4]-t)/i} ${(this.#qs[5]-e)/n} L${s} ${a} L${r} ${o} L${(this.#qs[16]-t)/i} ${(this.#qs[17]-e)/n} L${(this.#qs[14]-t)/i} ${(this.#qs[15]-e)/n} Z`}#oa(t){const e=this.#js;t.push(`L${e[4]} ${e[5]} Z`)}#ra(t){const[e,i,n,s]=this.#Us,a=this.#qs.subarray(4,6),r=this.#qs.subarray(16,18),[o,l,h,d]=this.#sa();t.push(`L${(a[0]-e)/n} ${(a[1]-i)/s} L${o} ${l} L${h} ${d} L${(r[0]-e)/n} ${(r[1]-i)/s}`)}newFreeDrawOutline(t,e,i,n,s,a){return new FreeDrawOutline(t,e,i,n,s,a)}getOutlines(){const t=this.#Gs,e=this.#js,i=this.#qs,[n,s,a,r]=this.#Us,o=new Float32Array((this.#ta?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2){o[t]=(this.#ta[t]-n)/a;o[t+1]=(this.#ta[t+1]-s)/r}o[o.length-2]=(this.#Xs-n)/a;o[o.length-1]=(this.#Ks-s)/r;if(isNaN(i[6])&&!this.isEmpty())return this.#la(o);const l=new Float32Array(this.#Gs.length+24+this.#js.length);let h=t.length;for(let e=0;e<h;e+=2)if(isNaN(t[e]))l[e]=l[e+1]=NaN;else{l[e]=t[e];l[e+1]=t[e+1]}h=this.#ha(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#da(l,h);return this.newFreeDrawOutline(l,o,this.#Us,this.#Qs,this.#Ws,this.#$s)}#la(t){const e=this.#qs,[i,n,s,a]=this.#Us,[r,o,l,h]=this.#sa(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/s,(e[3]-n)/a,NaN,NaN,NaN,NaN,(e[4]-i)/s,(e[5]-n)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/s,(e[17]-n)/a,NaN,NaN,NaN,NaN,(e[14]-i)/s,(e[15]-n)/a],0);return this.newFreeDrawOutline(d,t,this.#Us,this.#Qs,this.#Ws,this.#$s)}#da(t,e){const i=this.#js;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#ha(t,e){const i=this.#qs.subarray(4,6),n=this.#qs.subarray(16,18),[s,a,r,o]=this.#Us,[l,h,d,c]=this.#sa();t.set([NaN,NaN,NaN,NaN,(i[0]-s)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(n[0]-s)/r,(n[1]-a)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Us;#ca=new Float32Array(4);#Ws;#$s;#ta;#Qs;#ua;constructor(t,e,i,n,s,a){super();this.#ua=t;this.#ta=e;this.#Us=i;this.#Qs=n;this.#Ws=s;this.#$s=a;this.lastPoint=[NaN,NaN];this.#pa(a);const[r,o,l,h]=this.#ca;for(let e=0,i=t.length;e<i;e+=2){t[e]=(t[e]-r)/l;t[e+1]=(t[e+1]-o)/h}for(let t=0,i=e.length;t<i;t+=2){e[t]=(e[t]-r)/l;e[t+1]=(e[t+1]-o)/h}}toSVGPath(){const t=[`M${this.#ua[4]} ${this.#ua[5]}`];for(let e=6,i=this.#ua.length;e<i;e+=6)isNaN(this.#ua[e])?t.push(`L${this.#ua[e+4]} ${this.#ua[e+5]}`):t.push(`C${this.#ua[e]} ${this.#ua[e+1]} ${this.#ua[e+2]} ${this.#ua[e+3]} ${this.#ua[e+4]} ${this.#ua[e+5]}`);t.push("Z");return t.join(" ")}serialize([t,e,i,n],s){const a=i-t,r=n-e;let o,l;switch(s){case 0:o=Outline._rescale(this.#ua,t,n,a,-r);l=Outline._rescale(this.#ta,t,n,a,-r);break;case 90:o=Outline._rescaleAndSwap(this.#ua,t,e,a,r);l=Outline._rescaleAndSwap(this.#ta,t,e,a,r);break;case 180:o=Outline._rescale(this.#ua,i,e,-a,r);l=Outline._rescale(this.#ta,i,e,-a,r);break;case 270:o=Outline._rescaleAndSwap(this.#ua,i,n,-a,-r);l=Outline._rescaleAndSwap(this.#ta,i,n,-a,-r)}return{outline:Array.from(o),points:[Array.from(l)]}}#pa(t){const e=this.#ua;let n=e[4],s=e[5],a=n,r=s,o=n,l=s,h=n,d=s;const c=t?Math.max:Math.min;for(let t=6,u=e.length;t<u;t+=6){if(isNaN(e[t])){a=Math.min(a,e[t+4]);r=Math.min(r,e[t+5]);o=Math.max(o,e[t+4]);l=Math.max(l,e[t+5]);if(d<e[t+5]){h=e[t+4];d=e[t+5]}else d===e[t+5]&&(h=c(h,e[t+4]))}else{const u=i.Util.bezierBoundingBox(n,s,...e.slice(t,t+6));a=Math.min(a,u[0]);r=Math.min(r,u[1]);o=Math.max(o,u[2]);l=Math.max(l,u[3]);if(d<u[3]){h=u[2];d=u[3]}else d===u[3]&&(h=c(h,u[2]))}n=e[t+4];s=e[t+5]}const u=this.#ca;u[0]=a-this.#Ws;u[1]=r-this.#Ws;u[2]=o-a+2*this.#Ws;u[3]=l-r+2*this.#Ws;this.lastPoint=[h,d]}get box(){return this.#ca}newOutliner(t,e,i,n,s,a=0){return new FreeDrawOutliner(t,e,i,n,s,a)}getNewOutline(t,e){const[i,n,s,a]=this.#ca,[r,o,l,h]=this.#Us,d=s*l,c=a*h,u=i*l+r,p=n*h+o,g=this.newOutliner({x:this.#ta[0]*d+u,y:this.#ta[1]*c+p},this.#Us,this.#Qs,t,this.#$s,e??this.#Ws);for(let t=2;t<this.#ta.length;t+=2)g.add({x:this.#ta[t]*d+u,y:this.#ta[t+1]*c+p});return g.getOutlines()}}class HighlightOutliner{#Us;#ga;#ma=[];#fa=[];constructor(t,e=0,i=0,n=!0){let s=1/0,a=-1/0,r=1/0,o=-1/0;const l=10**-4;for(const{x:i,y:n,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((n-e)/l)*l,p=Math.ceil((n+d+e)/l)*l,g=[t,u,p,!0],m=[c,u,p,!1];this.#ma.push(g,m);s=Math.min(s,t);a=Math.max(a,c);r=Math.min(r,u);o=Math.max(o,p)}const h=a-s+2*i,d=o-r+2*i,c=s-i,u=r-i,p=this.#ma.at(n?-1:-2),g=[p[0],p[2]];for(const t of this.#ma){const[e,i,n]=t;t[0]=(e-c)/h;t[1]=(i-u)/d;t[2]=(n-u)/d}this.#Us=new Float32Array([c,u,h,d]);this.#ga=g}getOutlines(){this.#ma.sort(((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#ma)if(e[3]){t.push(...this.#ba(e));this.#wa(e)}else{this.#va(e);t.push(...this.#ba(e))}return this.#ya(t)}#ya(t){const e=[],i=new Set;for(const i of t){const[t,n,s]=i;e.push([t,n,i],[t,s,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,n=e.length;t<n;t+=2){const n=e[t][2],s=e[t+1][2];n.push(s);s.push(n);i.add(n);i.add(s)}const n=[];let s;for(;i.size>0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;s=[e,r];n.push(s);for(;;){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;if(h!==e){s.push(h,d,e,d===a?a:r);h=e}d=d===a?r:a}s.push(h,d)}return new HighlightOutline(n,this.#Us,this.#ga)}#Aa(t){const e=this.#fa;let i=0,n=e.length-1;for(;i<=n;){const s=i+n>>1,a=e[s][0];if(a===t)return s;a<t?i=s+1:n=s-1}return n+1}#wa([,t,e]){const i=this.#Aa(t);this.#fa.splice(i,0,[t,e])}#va([,t,e]){const i=this.#Aa(t);for(let n=i;n<this.#fa.length;n++){const[i,s]=this.#fa[n];if(i!==t)break;if(i===t&&s===e){this.#fa.splice(n,1);return}}for(let n=i-1;n>=0;n--){const[i,s]=this.#fa[n];if(i!==t)break;if(i===t&&s===e){this.#fa.splice(n,1);return}}}#ba(t){const[e,i,n]=t,s=[[e,i,n]],a=this.#Aa(n);for(let t=0;t<a;t++){const[i,n]=this.#fa[t];for(let t=0,a=s.length;t<a;t++){const[,r,o]=s[t];if(!(n<=r||o<=i))if(r>=i)if(o>n)s[t][1]=n;else{if(1===a)return[];s.splice(t,1);t--;a--}else{s[t][2]=i;o>n&&s.push([e,n,o])}}}return s}}class HighlightOutline extends Outline{#Us;#xa;constructor(t,e,i){super();this.#xa=t;this.#Us=e;this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#xa){let[i,n]=e;t.push(`M${i} ${n}`);for(let s=2;s<e.length;s+=2){const a=e[s],r=e[s+1];if(a===i){t.push(`V${r}`);n=r}else if(r===n){t.push(`H${a}`);i=a}}t.push("Z")}return t.join(" ")}serialize([t,e,i,n],s){const a=[],r=i-t,o=n-e;for(const e of this.#xa){const i=new Array(e.length);for(let s=0;s<e.length;s+=2){i[s]=t+e[s]*r;i[s+1]=n-e[s+1]*o}a.push(i)}return a}get box(){return this.#Us}get classNamesForOutlining(){return["highlightOutline"]}}class FreeHighlightOutliner extends FreeDrawOutliner{newFreeDrawOutline(t,e,i,n,s,a){return new FreeHighlightOutline(t,e,i,n,s,a)}}class FreeHighlightOutline extends FreeDrawOutline{newOutliner(t,e,i,n,s,a=0){return new FreeHighlightOutliner(t,e,i,n,s,a)}}class ColorPicker{#Ea=null;#Sa=null;#Pa;#_a=null;#Ca=!1;#Ta=!1;#xt=null;#Ma;#Ia=null;#Ce=null;#Da;static#La=null;static get _keyboardManager(){return(0,i.shadow)(this,"_keyboardManager",new r.KeyboardManager([[["Escape","mac+Escape"],ColorPicker.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ColorPicker.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ColorPicker.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ColorPicker.prototype._moveToPrevious],[["Home","mac+Home"],ColorPicker.prototype._moveToBeginning],[["End","mac+End"],ColorPicker.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){if(t){this.#Ta=!1;this.#Da=i.AnnotationEditorParamsType.HIGHLIGHT_COLOR;this.#xt=t}else{this.#Ta=!0;this.#Da=i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR}this.#Ce=t?._uiManager||e;this.#Ma=this.#Ce._eventBus;this.#Pa=t?.color||this.#Ce?.highlightColors.values().next().value||"#FFFF98";ColorPicker.#La||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Ea=document.createElement("button");t.className="colorPicker";t.tabIndex="0";t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button");t.setAttribute("aria-haspopup",!0);const e=this.#Ce._signal;t.addEventListener("click",this.#ka.bind(this),{signal:e});t.addEventListener("keydown",this.#$n.bind(this),{signal:e});const i=this.#Sa=document.createElement("span");i.className="swatch";i.setAttribute("aria-hidden",!0);i.style.backgroundColor=this.#Pa;t.append(i);return t}renderMainDropdown(){const t=this.#_a=this.#Fa();t.setAttribute("aria-orientation","horizontal");t.setAttribute("aria-labelledby","highlightColorPickerLabel");return t}#Fa(){const t=document.createElement("div"),e=this.#Ce._signal;t.addEventListener("contextmenu",s.noContextMenu,{signal:e});t.className="dropdown";t.role="listbox";t.setAttribute("aria-multiselectable",!1);t.setAttribute("aria-orientation","vertical");t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[i,n]of this.#Ce.highlightColors){const s=document.createElement("button");s.tabIndex="0";s.role="option";s.setAttribute("data-color",n);s.title=i;s.setAttribute("data-l10n-id",ColorPicker.#La[i]);const a=document.createElement("span");s.append(a);a.className="swatch";a.style.backgroundColor=n;s.setAttribute("aria-selected",n===this.#Pa);s.addEventListener("click",this.#Ra.bind(this,n),{signal:e});t.append(s)}t.addEventListener("keydown",this.#$n.bind(this),{signal:e});return t}#Ra(t,e){e.stopPropagation();this.#Ma.dispatch("switchannotationeditorparams",{source:this,type:this.#Da,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#Ea){this.#ka(t);return}const e=t.target.getAttribute("data-color");e&&this.#Ra(e,t)}_moveToNext(t){this.#Na?t.target!==this.#Ea?t.target.nextSibling?.focus():this.#_a.firstChild?.focus():this.#ka(t)}_moveToPrevious(t){if(t.target!==this.#_a?.firstChild&&t.target!==this.#Ea){this.#Na||this.#ka(t);t.target.previousSibling?.focus()}else this.#Na&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Na?this.#_a.firstChild?.focus():this.#ka(t)}_moveToEnd(t){this.#Na?this.#_a.lastChild?.focus():this.#ka(t)}#$n(t){ColorPicker._keyboardManager.exec(this,t)}#ka(t){if(this.#Na){this.hideDropdown();return}this.#Ca=0===t.detail;if(!this.#Ia){this.#Ia=new AbortController;window.addEventListener("pointerdown",this.#Ae.bind(this),{signal:this.#Ce.combinedSignal(this.#Ia)})}if(this.#_a){this.#_a.classList.remove("hidden");return}const e=this.#_a=this.#Fa();this.#Ea.append(e)}#Ae(t){this.#_a?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#_a?.classList.add("hidden");this.#Ia?.abort();this.#Ia=null}get#Na(){return this.#_a&&!this.#_a.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#Ta)if(this.#Na){this.hideDropdown();this.#Ea.focus({preventScroll:!0,focusVisible:this.#Ca})}else this.#xt?.unselect()}updateColor(t){this.#Sa&&(this.#Sa.style.backgroundColor=t);if(!this.#_a)return;const e=this.#Ce.highlightColors.values();for(const i of this.#_a.children)i.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#Ea?.remove();this.#Ea=null;this.#Sa=null;this.#_a?.remove();this.#_a=null}}class HighlightEditor extends a.AnnotationEditor{#Ba=null;#Oa=0;#Va;#Ha=null;#we=null;#za=null;#Ua=null;#ja=0;#Wa=null;#$a=null;#L=null;#Ga=!1;#ga=null;#qa;#Xa=null;#Ka="";#Js;#Ya="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=i.AnnotationEditorType.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=HighlightEditor.prototype;return(0,i.shadow)(this,"_keyboardManager",new r.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"});this.color=t.color||HighlightEditor._defaultColor;this.#Js=t.thickness||HighlightEditor._defaultThickness;this.#qa=t.opacity||HighlightEditor._defaultOpacity;this.#Va=t.boxes||null;this.#Ya=t.methodOfCreation||"";this.#Ka=t.text||"";this._isDraggable=!1;if(t.highlightId>-1){this.#Ga=!0;this.#Za(t);this.#Qa()}else if(this.#Va){this.#Ba=t.anchorNode;this.#Oa=t.anchorOffset;this.#Ua=t.focusNode;this.#ja=t.focusOffset;this.#Ja();this.#Qa();this.rotate(this.rotation)}this.eventBus?.dispatch("annotation-editor-event",{source:this,type:"added",page:this.pageIndex+1,editorType:this.constructor.name,value:{color:this.color,thickness:this.#Js,isFreeHighlight:this.#Ga,text:this.#Ka}})}get telemetryInitialData(){return{action:"added",type:this.#Ga?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#Js,methodOfCreation:this.#Ya}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#Ja(){const t=new HighlightOutliner(this.#Va,.001);this.#$a=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#$a.box;const e=new HighlightOutliner(this.#Va,.0025,.001,"ltr"===this._uiManager.direction);this.#za=e.getOutlines();const{lastPoint:i}=this.#za;this.#ga=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#Za({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#$a=t;this.#za=t.getNewOutline(this.#Js/2+1.5,.0025);if(e>=0){this.#L=e;this.#Ha=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Xa=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#za.box,path:{d:this.#za.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#L,{bbox:HighlightEditor.#tr(this.#$a.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Xa,{bbox:HighlightEditor.#tr(this.#za.box,e),path:{d:this.#za.toSVGPath()}})}const[n,s,a,r]=t.box;switch(this.rotation){case 0:this.x=n;this.y=s;this.width=a;this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=s;this.y=1-n;this.width=a*e/t;this.height=r*t/e;break}case 180:this.x=1-n;this.y=1-s;this.width=a;this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-s;this.y=n;this.width=a*e/t;this.height=r*t/e;break}}const{lastPoint:o}=this.#za;this.#ga=[(o[0]-n)/a,(o[1]-s)/r]}static initialize(t,e){a.AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:HighlightEditor._defaultColor=e;break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#ga}updateParams(t,e){switch(t){case i.AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#Fs(e);break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#er(e)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR,HighlightEditor._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,this.#Js||HighlightEditor._defaultThickness],[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,this.#Ga]]}#Fs(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.#qa=e;this.parent?.drawLayer.updateProperties(this.#L,{root:{fill:t,"fill-opacity":e}});this.#we?.updateColor(t)},e=this.color,n=this.#qa;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0);this.eventBus?.dispatch("annotation-editor-event",{source:this,type:"colorChanged",page:this.pageIndex+1,editorType:this.constructor.name,value:t,previousValue:e})}#er(t){const e=this.#Js,setThickness=t=>{this.#Js=t;this.#ir(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0);this.eventBus?.dispatch("annotation-editor-event",{source:this,type:"thicknessChanged",page:this.pageIndex+1,editorType:this.constructor.name,value:t,previousValue:e})}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.highlightColors){this.#we=new ColorPicker({editor:this});t.addColorPicker(this.#we)}return t}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#nr())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#nr())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#sr();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Qa();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#sr();else if(t){this.#Qa(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#ir(t){if(!this.#Ga)return;this.#Za({highlightOutlines:this.#$a.getNewOutline(t/2)});this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#sr(){if(null!==this.#L&&this.parent){this.parent.drawLayer.remove(this.#L);this.#L=null;this.parent.drawLayer.remove(this.#Xa);this.#Xa=null}}#Qa(t=this.parent){if(null===this.#L){({id:this.#L,clipPathId:this.#Ha}=t.drawLayer.draw({bbox:this.#$a.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#qa},rootClass:{highlight:!0,free:this.#Ga},path:{d:this.#$a.toSVGPath()}},!1,!0));this.#Xa=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Ga},bbox:this.#za.box,path:{d:this.#za.toSVGPath()}},this.#Ga);this.#Wa&&(this.#Wa.style.clipPath=this.#Ha)}}static#tr([t,e,i,n],s){switch(s){case 90:return[1-e-n,t,n,i];case 180:return[1-t-i,1-e-n,i,n];case 270:return[e,1-t-i,n,i]}return[t,e,i,n]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Ga){t=(t-this.rotation+360)%360;i=HighlightEditor.#tr(this.#$a.box,t)}else i=HighlightEditor.#tr([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#L,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Xa,{bbox:HighlightEditor.#tr(this.#za.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#Ka){t.setAttribute("aria-label",this.#Ka);t.setAttribute("role","mark")}this.#Ga?t.classList.add("free"):this.div.addEventListener("keydown",this.#ar.bind(this),{signal:this._uiManager._signal});const e=this.#Wa=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#Ha;const[i,n]=this.parentDimensions;this.setDims(this.width*i,this.height*n);(0,r.bindEvents)(this,this.#Wa,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Xa,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Xa,{rootClass:{hovered:!1}})}#ar(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#rr(!0);break;case 1:case 3:this.#rr(!1)}}#rr(t){if(!this.#Ba)return;const e=window.getSelection();t?e.setPosition(this.#Ba,this.#Oa):e.setPosition(this.#Ua,this.#ja)}select(){super.select();this.#Xa&&this.parent?.drawLayer.updateProperties(this.#Xa,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Xa){this.parent?.drawLayer.updateProperties(this.#Xa,{rootClass:{selected:!1}});this.#Ga||this.#rr(!1)}}get _mustFixPosition(){return!this.#Ga}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#L,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Xa,{rootClass:{hidden:!t}})}}#nr(){return this.#Ga?this.rotation:0}#or(){if(this.#Ga)return null;const[t,e]=this.pageDimensions,[i,n]=this.pageTranslation,s=this.#Va,a=new Float32Array(8*s.length);let r=0;for(const{x:o,y:l,width:h,height:d}of s){const s=o*t+i,c=(1-l)*e+n;a[r]=a[r+4]=s;a[r+1]=a[r+3]=c;a[r+2]=a[r+6]=s+h*t;a[r+5]=a[r+7]=c-d*e;r+=8}return a}#lr(t){return this.#$a.serialize(t,this.#nr())}static startHighlighting(t,e,{target:i,x:n,y:a}){const{x:r,y:o,width:l,height:h}=i.getBoundingClientRect(),d=new AbortController,c=t.combinedSignal(d),pointerUpCallback=e=>{d.abort();this.#hr(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:c});window.addEventListener("pointerup",pointerUpCallback,{signal:c});window.addEventListener("pointerdown",s.stopEvent,{capture:!0,passive:!1,signal:c});window.addEventListener("contextmenu",s.noContextMenu,{signal:c});i.addEventListener("pointermove",this.#dr.bind(this,t),{signal:c});this._freeHighlight=new FreeHighlightOutliner({x:n,y:a},[r,o,l,h],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#dr(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#hr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(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,n){let s=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:n,rotation:a,id:r,color:o,opacity:l,popupRef:h},parent:{page:{pageNumber:d}}}=t;s=t={annotationType:i.AnnotationEditorType.HIGHLIGHT,color:Array.from(o),opacity:l,quadPoints:e,boxes:null,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:h}}else if(t.annotationType&&t.annotationType===i.AnnotationEditorType.HIGHLIGHT){let e,{quadPoints:n,outlines:a,rect:r,rotation:o,id:l,color:h,opacity:d,popupRef:c,pageIndex:u,thickness:p}=t;n&&(Array.isArray(n)||(n=Object.values(n)));if(!n&&a){if(Array.isArray(a))e=a.map((t=>t));else{if("object"!=typeof a||!a.points){console.error("Unexpected outlines format");return null}e=[a.points.flat()]}p=p||t.thickness||1}s=t={annotationType:i.AnnotationEditorType.HIGHLIGHT,color:Array.from(h),opacity:d,quadPoints:n,inkLists:e,thickness:p,boxes:null,pageIndex:u,rect:r.slice(0),rotation:o,id:l,deleted:!1,popupRef:c||null}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:n,rotation:a,id:r,color:o,borderStyle:{rawWidth:l},popupRef:h},parent:{page:{pageNumber:d}}}=t;s=t={annotationType:i.AnnotationEditorType.HIGHLIGHT,color:Array.from(o),thickness:l,inkLists:e,boxes:null,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:h}}const{color:a,quadPoints:r,inkLists:o,opacity:l}=t,h=await super.deserialize(t,e,n);h.color=i.Util.makeHexColor(...a);h.#qa=l||1;o&&(h.#Js=t.thickness);h.annotationElementId=t.id||null;h._initialData=s;const[d,c]=h.pageDimensions,[u,p]=h.pageTranslation;if(r){const t=h.#Va=[];for(let e=0;e<r.length;e+=8)t.push({x:(r[e]-u)/d,y:1-(r[e+1]-p)/c,width:(r[e+2]-r[e])/d,height:(r[e+1]-r[e+5])/c});h.#Ja();h.#Qa();h.rotate(h.rotation)}else if(o){h.#Ga=!0;const t=o[0],i={x:t[0]-u,y:c-(t[1]-p)},n=new FreeHighlightOutliner(i,[0,0,d,c],1,h.#Js/2,!0,.001);for(let e=0,s=t.length;e<s;e+=2){i.x=t[e]-u;i.y=c-(t[e+1]-p);n.add(i)}const{id:s,clipPathId:a}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:h.color,"fill-opacity":h._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:n.toSVGPath()}},!0,!0);h.#Za({highlightOutlines:n.getOutlines(),highlightId:s,clipPathId:a});h.#Qa()}return h}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),n=a.AnnotationEditor._colorManager.convert(this.color),s={annotationType:i.AnnotationEditorType.HIGHLIGHT,color:n,opacity:this.#qa,thickness:this.#Js,quadPoints:this.#or(),outlines:this.#lr(e),pageIndex:this.pageIndex,rect:e,rotation:this.#nr(),structTreeParentId:this._structTreeParentId};if(this.annotationElementId&&!this.#zs(s))return null;s.id=this.annotationElementId;return s}#zs(t){const{color:e}=this._initialData;return t.color.some(((t,i)=>t!==e[i]))}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#cr=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))this.updateProperty(e,i)}updateSVGProperty(t,e){this.#cr[t]=e}toSVGProperties(){const t=this.#cr;this.#cr=Object.create(null);return{root:t}}reset(){this.#cr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){(0,i.unreachable)("Not implemented")}}class DrawingEditor extends a.AnnotationEditor{#ur=null;#pr;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#gr=null;static#mr=null;static#fr=null;static#br=NaN;static#wr=null;static#vr=null;static#yr=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#pr=t.mustBeCommitted||!1;if(t.drawOutlines){this.#Ar(t);this.#Qa()}}#Ar({drawOutlines:t,drawId:e,drawingOptions:i}){this.#ur=t;this._drawingOptions||=i;if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#xr(t,this.parent);this.#Er(t.box)}#xr(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[n,s]of Object.entries(e))i.has(n)?Object.assign(t[n],s):t[n]=s;return t}static getDefaultDrawingOptions(t){(0,i.unreachable)("Not implemented")}static get typesMap(){(0,i.unreachable)("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#gr.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,n]of this.typesMap)t.push([i,e[n]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,n]of this.constructor.typesMap)t.push([i,e[n]]);return t}_updateProperty(t,e,i){const n=this._drawingOptions,s=n[e],setter=t=>{n.updateProperty(e,t);const i=this.#ur.updateProperty(e,t);i&&this.#Er(i);this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties())};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ur.getPathResizingSVGProperties(this.#Sr()),{bbox:this.#Pr()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ur.getPathResizedSVGProperties(this.#Sr()),{bbox:this.#Pr()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Pr(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ur.getPathTranslatedSVGProperties(this.#Sr(),this.parentDimensions),{bbox:this.#Pr()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#pr){this.#pr=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#sr();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Qa();this.#Er(this.#ur.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#sr()}else if(t){this._uiManager.addShouldRescale(this);this.#Qa(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#sr(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#Qa(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#xr(this.#ur,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#_r([t,e,i,n]){const{parentDimensions:[s,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/s),n*(s/a)];case 180:return[1-t,1-e,i,n];case 270:return[1-e,t,i*(a/s),n*(s/a)];default:return[t,e,i,n]}}#Sr(){const{x:t,y:e,width:i,height:n,parentDimensions:[s,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(s/a),n*(a/s)];case 180:return[1-t,1-e,i,n];case 270:return[e,1-t,i*(s/a),n*(a/s)];default:return[t,e,i,n]}}#Er(t){[this.x,this.y,this.width,this.height]=this.#_r(t);if(this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Pr(){const{x:t,y:e,width:i,height:n,rotation:s,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*s+a)/90){case 1:return[1-e-n,t,n,i];case 2:return[1-t-i,1-e-n,i,n];case 3:return[e,1-t-i,n,i];case 4:return[t,e-i*(r/o),n*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),n*(o/r)];case 6:return[1-t-n*(o/r),1-e,n*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-n*(o/r),i*(r/o),n*(o/r)];case 8:return[t-i,e-n,i,n];case 9:return[1-e,t-i,n,i];case 10:return[1-t,1-e,i,n];case 11:return[e-n,1-t,n,i];case 12:return[t-n*(o/r),e,n*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-n*(o/r),i*(r/o),n*(o/r)];case 14:return[1-t,1-e-i*(r/o),n*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),n*(o/r)];default:return[t,e,i,n]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Pr()},this.#ur.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Er(this.#ur.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";const[i,n]=this.parentDimensions;this.setDims(this.width*i,this.height*n);this._uiManager.addShouldRescale(this);this.disableEditing();return t}static createDrawerInstance(t,e,n,s,a){(0,i.unreachable)("Not implemented")}static startDrawing(t,e,i,n){const{target:a,offsetX:r,offsetY:o,pointerId:l,pointerType:h}=n;if(DrawingEditor.#wr&&DrawingEditor.#wr!==h)return;const{viewport:{rotation:d}}=t,{width:c,height:u}=a.getBoundingClientRect(),p=DrawingEditor.#mr=new AbortController,g=t.combinedSignal(p);DrawingEditor.#br||=l;DrawingEditor.#wr??=h;window.addEventListener("pointerup",(t=>{DrawingEditor.#br===t.pointerId?this._endDraw(t):DrawingEditor.#vr?.delete(t.pointerId)}),{signal:g});window.addEventListener("pointercancel",(t=>{DrawingEditor.#br===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#vr?.delete(t.pointerId)}),{signal:g});window.addEventListener("pointerdown",(t=>{if(DrawingEditor.#wr===t.pointerType){(DrawingEditor.#vr||=new Set).add(t.pointerId);if(DrawingEditor.#gr.isCancellable()){DrawingEditor.#gr.removeLastElement();DrawingEditor.#gr.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}}),{capture:!0,passive:!1,signal:g});window.addEventListener("contextmenu",s.noContextMenu,{signal:g});a.addEventListener("pointermove",this._drawMove.bind(this),{signal:g});a.addEventListener("touchmove",(t=>{t.timeStamp===DrawingEditor.#yr&&(0,s.stopEvent)(t)}),{signal:g});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#gr)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#gr.startNew(r,o,c,u,d));else{e.updateUIForDefaultProperties(this);DrawingEditor.#gr=this.createDrawerInstance(r,o,c,u,d);DrawingEditor.#fr=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#fr.toSVGProperties(),DrawingEditor.#gr.defaultSVGProperties),!0,!1))}}static _drawMove(t){DrawingEditor.#yr=-1;if(!DrawingEditor.#gr)return;const{offsetX:e,offsetY:i,pointerId:n}=t;if(DrawingEditor.#br===n)if(DrawingEditor.#vr?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#gr.add(e,i));DrawingEditor.#yr=t.timeStamp;(0,s.stopEvent)(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#gr=null;DrawingEditor.#fr=null;DrawingEditor.#wr=null;DrawingEditor.#yr=NaN}if(DrawingEditor.#mr){DrawingEditor.#mr.abort();DrawingEditor.#mr=null;DrawingEditor.#br=NaN;DrawingEditor.#vr=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#gr.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#gr,n=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(n,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(n,t.removeLastElement())},mustExec:!1,type:i.AnnotationEditorParamsType.DRAW_STEP})}else this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(i.AnnotationEditorParamsType.DRAW_STEP);if(!DrawingEditor.#gr.isEmpty()){const{pageDimensions:[i,n],scale:s}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#gr.getOutlines(i*s,n*s,s,this._INNER_MARGIN),drawingOptions:DrawingEditor.#fr,mustBeCommitted:!t});this._cleanup(!0);return a}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,n,s,a,r){(0,i.unreachable)("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:n,pageHeight:s,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,n,s,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#Ar({drawOutlines:o});l.#Qa();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[n,s]=this.pageDimensions;return this.#ur.serialize([e,i,n,s],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#qs=new Float64Array(6);#ms;#Cr;#in;#Js;#ta;#Tr="";#Mr=0;#xa=new InkDrawOutline;#Ir;#Dr;constructor(t,e,i,n,s,a){this.#Ir=i;this.#Dr=n;this.#in=s;this.#Js=a;[t,e]=this.#Lr(t,e);const r=this.#ms=[NaN,NaN,NaN,NaN,t,e];this.#ta=[t,e];this.#Cr=[{line:r,points:this.#ta}];this.#qs.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#Js=e)}#Lr(t,e){return Outline._normalizePoint(t,e,this.#Ir,this.#Dr,this.#in)}isEmpty(){return!this.#Cr||0===this.#Cr.length}isCancellable(){return this.#ta.length<=10}add(t,e){[t,e]=this.#Lr(t,e);const[i,n,s,a]=this.#qs.subarray(2,6),r=t-s,o=e-a;if(Math.hypot(this.#Ir*r,this.#Dr*o)<=2)return null;this.#ta.push(t,e);if(isNaN(i)){this.#qs.set([s,a,t,e],2);this.#ms.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#qs[0])&&this.#ms.splice(6,6);this.#qs.set([i,n,s,a,t,e],0);this.#ms.push(...Outline.createBezierPoints(i,n,s,a,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#ta.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,n,s){this.#Ir=i;this.#Dr=n;this.#in=s;[t,e]=this.#Lr(t,e);const a=this.#ms=[NaN,NaN,NaN,NaN,t,e];this.#ta=[t,e];const r=this.#Cr.at(-1);if(r){r.line=new Float32Array(r.line);r.points=new Float32Array(r.points)}this.#Cr.push({line:a,points:this.#ta});this.#qs.set(a,0);this.#Mr=0;this.toSVGPath();return null}getLastElement(){return this.#Cr.at(-1)}setLastElement(t){if(!this.#Cr)return this.#xa.setLastElement(t);this.#Cr.push(t);this.#ms=t.line;this.#ta=t.points;this.#Mr=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Cr)return this.#xa.removeLastElement();this.#Cr.pop();this.#Tr="";for(let t=0,e=this.#Cr.length;t<e;t++){const{line:e,points:i}=this.#Cr[t];this.#ms=e;this.#ta=i;this.#Mr=0;this.toSVGPath()}return{path:{d:this.#Tr}}}toSVGPath(){const t=Outline.svgRound(this.#ms[4]),e=Outline.svgRound(this.#ms[5]);if(2===this.#ta.length){this.#Tr=`${this.#Tr} M ${t} ${e} Z`;return this.#Tr}if(this.#ta.length<=6){const i=this.#Tr.lastIndexOf("M");this.#Tr=`${this.#Tr.slice(0,i)} M ${t} ${e}`;this.#Mr=6}if(4===this.#ta.length){const t=Outline.svgRound(this.#ms[10]),e=Outline.svgRound(this.#ms[11]);this.#Tr=`${this.#Tr} L ${t} ${e}`;this.#Mr=12;return this.#Tr}const i=[];if(0===this.#Mr){i.push(`M ${t} ${e}`);this.#Mr=6}for(let t=this.#Mr,e=this.#ms.length;t<e;t+=6){const[e,n,s,a,r,o]=this.#ms.slice(t,t+6).map(Outline.svgRound);i.push(`C${e} ${n} ${s} ${a} ${r} ${o}`)}this.#Tr+=i.join(" ");this.#Mr=this.#ms.length;return this.#Tr}getOutlines(t,e,i,n){const s=this.#Cr.at(-1);s.line=new Float32Array(s.line);s.points=new Float32Array(s.points);this.#xa.build(this.#Cr,t,e,i,this.#in,this.#Js,n);this.#qs=null;this.#ms=null;this.#Cr=null;this.#Tr=null;return this.#xa}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class InkDrawOutline extends Outline{#ca;#kr=0;#Ws;#Cr;#Ir;#Dr;#Fr;#in;#Js;build(t,e,i,n,s,a,r){this.#Ir=e;this.#Dr=i;this.#Fr=n;this.#in=s;this.#Js=a;this.#Ws=r??0;this.#Cr=t;this.#Rr()}setLastElement(t){this.#Cr.push(t);return{path:{d:this.toSVGPath()}}}removeLastElement(){this.#Cr.pop();return{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#Cr){t.push(`M${Outline.svgRound(e[4])} ${Outline.svgRound(e[5])}`);if(6!==e.length)if(12!==e.length)for(let i=6,n=e.length;i<n;i+=6){const[n,s,a,r,o,l]=e.subarray(i,i+6).map(Outline.svgRound);t.push(`C${n} ${s} ${a} ${r} ${o} ${l}`)}else t.push(`L${Outline.svgRound(e[10])} ${Outline.svgRound(e[11])}`);else t.push("Z")}return t.join("")}serialize([t,e,i,n],s){const a=[],r=[],[o,l,h,d]=this.#Nr();let c,u,p,g,m,f,b,w,v;switch(this.#in){case 0:v=Outline._rescale;c=t;u=e+n;p=i;g=-n;m=t+o*i;f=e+(1-l-d)*n;b=t+(o+h)*i;w=e+(1-l)*n;break;case 90:v=Outline._rescaleAndSwap;c=t;u=e;p=i;g=n;m=t+l*i;f=e+o*n;b=t+(l+d)*i;w=e+(o+h)*n;break;case 180:v=Outline._rescale;c=t+i;u=e;p=-i;g=n;m=t+(1-o-h)*i;f=e+l*n;b=t+(1-o)*i;w=e+(l+d)*n;break;case 270:v=Outline._rescaleAndSwap;c=t+i;u=e+n;p=-i;g=-n;m=t+(1-l-d)*i;f=e+(1-o-h)*n;b=t+(1-l)*i;w=e+(1-o)*n}for(const{line:t,points:e}of this.#Cr){a.push(v(t,c,u,p,g,s?new Array(t.length):null));r.push(v(e,c,u,p,g,s?new Array(e.length):null))}return{lines:a,points:r,rect:[m,f,b,w]}}static deserialize(t,e,i,n,s,{paths:{lines:a,points:r},rotation:o,thickness:l}){const h=[];let d,c,u,p,g;switch(o){case 0:g=Outline._rescale;d=-t/i;c=e/n+1;u=1/i;p=-1/n;break;case 90:g=Outline._rescaleAndSwap;d=-e/n;c=-t/i;u=1/n;p=1/i;break;case 180:g=Outline._rescale;d=t/i+1;c=-e/n;u=-1/i;p=1/n;break;case 270:g=Outline._rescaleAndSwap;d=e/n+1;c=t/i+1;u=-1/n;p=-1/i}if(!a){a=[];for(const t of r){const e=t.length;if(2===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const i=new Float32Array(3*(e-2));a.push(i);let[n,s,r,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,n,s],0);for(let a=4;a<e;a+=2){const e=t[a],l=t[a+1];i.set(Outline.createBezierPoints(n,s,r,o,e,l),3*(a-2));[n,s,r,o]=[r,o,e,l]}}}for(let t=0,e=a.length;t<e;t++)h.push({line:g(a[t].map((t=>t??NaN)),d,c,u,p),points:g(r[t].map((t=>t??NaN)),d,c,u,p)});const m=new InkDrawOutline;m.build(h,i,n,1,o,l,s);return m}#Br(t=this.#Js){const e=this.#Ws+t/2*this.#Fr;return this.#in%180==0?[e/this.#Ir,e/this.#Dr]:[e/this.#Dr,e/this.#Ir]}#Nr(){const[t,e,i,n]=this.#ca,[s,a]=this.#Br(0);return[t+s,e+a,i-2*s,n-2*a]}#Rr(){const t=this.#ca=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Cr){if(e.length<=12){for(let i=4,n=e.length;i<n;i+=6){const[n,s]=e.subarray(i,i+2);t[0]=Math.min(t[0],n);t[1]=Math.min(t[1],s);t[2]=Math.max(t[2],n);t[3]=Math.max(t[3],s)}continue}let n=e[4],s=e[5];for(let a=6,r=e.length;a<r;a+=6){const[r,o,l,h,d,c]=e.subarray(a,a+6);i.Util.bezierBoundingBox(n,s,r,o,l,h,d,c,t);n=d;s=c}}const[e,n]=this.#Br();t[0]=Math.min(1,Math.max(0,t[0]-e));t[1]=Math.min(1,Math.max(0,t[1]-n));t[2]=Math.min(1,Math.max(0,t[2]+e));t[3]=Math.min(1,Math.max(0,t[3]+n));t[2]-=t[0];t[3]-=t[1]}get box(){return this.#ca}updateProperty(t,e){return"stroke-width"===t?this.#er(e):null}#er(t){const[e,i]=this.#Br();this.#Js=t;const[n,s]=this.#Br(),[a,r]=[n-e,s-i],o=this.#ca;o[0]-=a;o[1]-=r;o[2]+=2*a;o[3]+=2*r;return o}updateParentDimensions([t,e],i){const[n,s]=this.#Br();this.#Ir=t;this.#Dr=e;this.#Fr=i;const[a,r]=this.#Br(),o=a-n,l=r-s,h=this.#ca;h[0]-=o;h[1]-=l;h[2]+=2*o;h[3]+=2*l;return h}updateRotation(t){this.#kr=t;return{path:{transform:this.rotationTransform}}}get viewBox(){return this.#ca.map(Outline.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#ca;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#ca;let i=0,n=0,s=0,a=0,r=0,o=0;switch(this.#kr){case 90:n=e/t;s=-t/e;r=t;break;case 180:i=-1;a=-1;r=t;o=e;break;case 270:n=-e/t;s=t/e;o=e;break;default:return""}return`matrix(${i} ${n} ${s} ${a} ${Outline.svgRound(r)} ${Outline.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,n]){const[s,a]=this.#Br(),[r,o,l,h]=this.#ca;if(Math.abs(l-s)<=Outline.PRECISION||Math.abs(h-a)<=Outline.PRECISION){const s=t+i/2-(r+l/2),a=e+n/2-(o+h/2);return{path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:`${this.rotationTransform} translate(${s} ${a})`}}}const d=(i-2*s)/(l-2*s),c=(n-2*a)/(h-2*a),u=l/i,p=h/n;return{path:{"transform-origin":`${Outline.svgRound(r)} ${Outline.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Outline.svgRound(s)} ${Outline.svgRound(a)}) scale(${d} ${c}) translate(${Outline.svgRound(-s)} ${Outline.svgRound(-a)})`}}}getPathResizedSVGProperties([t,e,i,n]){const[s,a]=this.#Br(),r=this.#ca,[o,l,h,d]=r;r[0]=t;r[1]=e;r[2]=i;r[3]=n;if(Math.abs(h-s)<=Outline.PRECISION||Math.abs(d-a)<=Outline.PRECISION){const s=t+i/2-(o+h/2),a=e+n/2-(l+d/2);for(const{line:t,points:e}of this.#Cr){Outline._translate(t,s,a,t);Outline._translate(e,s,a,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const c=(i-2*s)/(h-2*s),u=(n-2*a)/(d-2*a),p=-c*(o+s)+t+s,g=-u*(l+a)+e+a;if(1!==c||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#Cr){Outline._rescale(t,p,g,c,u,t);Outline._rescale(e,p,g,c,u,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[n,s]=i,a=this.#ca,r=t-a[0],o=e-a[1];if(this.#Ir===n&&this.#Dr===s)for(const{line:t,points:e}of this.#Cr){Outline._translate(t,r,o,t);Outline._translate(e,r,o,e)}else{const t=this.#Ir/n,e=this.#Dr/s;this.#Ir=n;this.#Dr=s;for(const{line:i,points:n}of this.#Cr){Outline._rescale(i,r,o,t,e,i);Outline._rescale(n,r,o,t,e,n)}a[2]*=t;a[3]*=e}a[0]=t;a[1]=e;return{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#ca;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t[0])} ${Outline.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class InkDrawingOptions extends DrawingOptions{#Or;constructor(t){super();this.#Or=t;super.updateProperties({fill:"none",stroke:a.AnnotationEditor._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){if("stroke-width"===t){e??=this["stroke-width"];e*=this.#Or.realScale}super.updateSVGProperty(t,e)}clone(){const t=new InkDrawingOptions(this.#Or);t.updateAll(this);return t}}class InkEditor extends DrawingEditor{static _type="ink";static _editorType=i.AnnotationEditorType.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"});this._willKeepAspectRatio=!0}static initialize(t,e){a.AnnotationEditor.initialize(t,e);this._defaultDrawingOptions=new InkDrawingOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();e.updateProperties(t);return e}static get supportMultipleDrawings(){return!0}static get typesMap(){return(0,i.shadow)(this,"typesMap",new Map([[i.AnnotationEditorParamsType.INK_THICKNESS,"stroke-width"],[i.AnnotationEditorParamsType.INK_COLOR,"stroke"],[i.AnnotationEditorParamsType.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,n,s){return new InkDrawOutliner(t,e,i,n,s,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,n,s,a){return InkDrawOutline.deserialize(t,e,i,n,s,a)}static async deserialize(t,e,n){let s=null;if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:n,rotation:a,id:r,color:o,opacity:l,borderStyle:{rawWidth:h},popupRef:d},parent:{page:{pageNumber:c}}}=t;s=t={annotationType:i.AnnotationEditorType.INK,color:Array.from(o),thickness:h,opacity:l,paths:{points:e},boxes:null,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:d}}const a=await super.deserialize(t,e,n);a.annotationElementId=t.id||null;a._initialData=s;return a}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width");i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;if(t){super.onScaleChangingWhenDrawing();this._defaultDrawingOptions.updateSVGProperty("stroke-width");t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}createDrawingOptions({color:t,thickness:e,opacity:n}){this._drawingOptions=InkEditor.getDefaultDrawingOptions({stroke:i.Util.makeHexColor(...t),"stroke-width":e,"stroke-opacity":n})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:n,rect:s}=this.serializeDraw(t),{_drawingOptions:{stroke:r,"stroke-opacity":o,"stroke-width":l}}=this,h={annotationType:i.AnnotationEditorType.INK,color:a.AnnotationEditor._colorManager.convert(r),opacity:o,thickness:l,paths:{lines:e,points:n},pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t)return h;if(this.annotationElementId&&!this.#zs(h))return null;h.id=this.annotationElementId;return h}#zs(t){const{color:e,thickness:i,opacity:n,pageIndex:s}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some(((t,i)=>t!==e[i]))||t.thickness!==i||t.opacity!==n||t.pageIndex!==s}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e});return null}}class StampEditor extends a.AnnotationEditor{#Vr=null;#Hr=null;#zr=null;#Ur=null;#jr=null;#Wr="";#$r=null;#Gr=null;#qr=!1;#Xr=!1;static _type="stamp";static _editorType=i.AnnotationEditorType.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Ur=t.bitmapUrl;this.#jr=t.bitmapFile}static initialize(t,e){a.AnnotationEditor.initialize(t,e)}static get supportedTypes(){return(0,i.shadow)(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return(0,i.shadow)(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(i.AnnotationEditorType.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){if(t){this.#Vr=t.bitmap;if(!e){this.#Hr=t.id;this.#qr=t.isSvg}t.file&&(this.#Wr=t.file.name);this.#Yr()}else this.remove()}#Zr(){this.#zr=null;this._uiManager.enableWaiting(!1);if(this.#$r)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Vr){this._editToolbar.hide();this._uiManager.editAltText(this,!0)}else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Vr){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:n,width:s,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:n,width:s,height:a,channels:n.length/(s*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;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#Qr(){if(this.#Hr){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#Hr).then((t=>this.#Kr(t,!0))).finally((()=>this.#Zr()));return}if(this.#Ur){const t=this.#Ur;this.#Ur=null;this._uiManager.enableWaiting(!0);this.#zr=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#Kr(t))).finally((()=>this.#Zr()));return}if(this.#jr){const t=this.#jr;this.#jr=null;this._uiManager.enableWaiting(!0);this.#zr=this._uiManager.imageManager.getFromFile(t).then((t=>this.#Kr(t))).finally((()=>this.#Zr()));return}const t=document.createElement("input");t.type="file";t.accept=StampEditor.supportedTypesStr;const e=this._uiManager._signal;this.#zr=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.#Zr()));t.click()}remove(){if(this.#Hr){this.#Vr=null;this._uiManager.imageManager.deleteId(this.#Hr);this.#$r?.remove();this.#$r=null;if(this.#Gr){clearTimeout(this.#Gr);this.#Gr=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Hr&&null===this.#$r&&this.#Qr();this.isAttachedToDOM||this.parent.add(this)}}else this.#Hr&&this.#Qr()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#zr||this.#Vr||this.#Ur||this.#jr||this.#Hr)}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.#Vr?this.#Yr():this.#Qr();if(this.width&&!this.annotationElementId){const[i,n]=this.parentDimensions;this.setAt(t*i,e*n,this.width*i,this.height*n)}this._uiManager.addShouldRescale(this);return this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#Gr&&clearTimeout(this.#Gr);this.#Gr=setTimeout((()=>{this.#Gr=null;this.#Jr()}),200)}#Yr(){const{div:t}=this;let{width:e,height:i}=this.#Vr;const[n,s]=this.pageDimensions,a=.75;if(this.width){e=this.width*n;i=this.height*s}else if(e>a*n||i>a*s){const t=Math.min(a*n/e,a*s/i);e*=t;i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/n,i*o/s);this._uiManager.enableWaiting(!1);const l=this.#$r=document.createElement("canvas");l.setAttribute("role","img");this.addContainer(l);this.width=e/n;this.height=i/s;this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#Jr();if(!this.#Xr){this.parent.addUndoableEditor(this);this.#Xr=!0}this._reportTelemetry({action:"inserted_image"});this.#Wr&&l.setAttribute("aria-label",this.#Wr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:n,height:a}=this.#Vr,r=new s.OutputScale;let o=this.#Vr,l=n,h=a,d=null;if(e){if(n>e||a>e){const t=Math.min(e/n,e/a);l=Math.floor(n*t);h=Math.floor(a*t)}d=document.createElement("canvas");const t=d.width=Math.ceil(l*r.sx),i=d.height=Math.ceil(h*r.sy);this.#qr||(o=this.#to(t,i));const s=d.getContext("2d");s.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(window.matchMedia?.("(prefers-color-scheme: dark)").matches){c="#8f8f9d";u="#42414d"}const p=15,g=p*r.sx,m=p*r.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);s.fillStyle=s.createPattern(f,"repeat");s.fillRect(0,0,t,i);s.drawImage(o,0,0,o.width,o.height,0,0,t,i)}let c=null;if(i){let e,i;if(r.symmetric&&o.width<t&&o.height<t){e=o.width;i=o.height}else{o=this.#Vr;if(n>t||a>t){const s=Math.min(t/n,t/a);e=Math.floor(n*s);i=Math.floor(a*s);this.#qr||(o=this.#to(e,i))}}const s=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});s.drawImage(o,0,0,o.width,o.height,0,0,e,i);c={width:e,height:i,data:s.getImageData(0,0,e,i).data}}return{canvas:d,width:l,height:h,imageData:c}}#to(t,e){const{width:i,height:n}=this.#Vr;let s=i,a=n,r=this.#Vr;for(;s>2*t||a>2*e;){const i=s,n=a;s>2*t&&(s=s>=16384?Math.floor(s/2)-1:Math.ceil(s/2));a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(s,a);o.getContext("2d").drawImage(r,0,0,i,n,0,0,s,a);r=o.transferToImageBitmap()}return r}#Jr(){const[t,e]=this.parentDimensions,{width:i,height:n}=this,a=new s.OutputScale,r=Math.ceil(i*t*a.sx),o=Math.ceil(n*e*a.sy),l=this.#$r;if(!l||l.width===r&&l.height===o)return;l.width=r;l.height=o;const h=this.#qr?this.#Vr:this.#to(r,o),d=l.getContext("2d");d.filter=this._uiManager.hcmFilter;d.drawImage(h,0,0,h.width,h.height,0,0,r,o)}getImageForAltText(){return this.#$r}#eo(t){if(t){if(this.#qr){const t=this._uiManager.imageManager.getSvgUrl(this.#Hr);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Vr);t.getContext("2d").drawImage(this.#Vr,0,0);return t.toDataURL()}if(this.#qr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*s.PixelsPerInch.PDF_TO_CSS_UNITS),n=Math.round(this.height*e*s.PixelsPerInch.PDF_TO_CSS_UNITS),a=new OffscreenCanvas(i,n);a.getContext("2d").drawImage(this.#Vr,0,0,this.#Vr.width,this.#Vr.height,0,0,i,n);return a.transferToImageBitmap()}return structuredClone(this.#Vr)}static async deserialize(t,e,n){let s=null;if(t instanceof StampAnnotationElement){const{data:{rect:a,rotation:r,id:o,structParent:l,popupRef:h},container:d,parent:{page:{pageNumber:c}}}=t,u=d.querySelector("canvas"),p=n.imageManager.getFromCanvas(d.id,u);u.remove();const g=(await e._structTree.getAriaAttributes(`${i.AnnotationPrefix}${o}`))?.get("aria-label")||"";s=t={annotationType:i.AnnotationEditorType.STAMP,bitmapId:p.id,bitmap:p.bitmap,pageIndex:c-1,rect:a.slice(0),rotation:r,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:g},isSvg:!1,structParent:l,popupRef:h}}const a=await super.deserialize(t,e,n),{rect:r,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:d,accessibilityData:c}=t;if(h&&n.imageManager.isValidId(h)){a.#Hr=h;o&&(a.#Vr=o)}else a.#Ur=l;a.#qr=d;const[u,p]=a.pageDimensions;a.width=(r[2]-r[0])/u;a.height=(r[3]-r[1])/p;a.annotationElementId=t.id||null;c&&(a.altTextData=c);a._initialData=s;a.#Xr=!!s;return a}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const n={annotationType:i.AnnotationEditorType.STAMP,bitmapId:this.#Hr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#qr,structTreeParentId:this._structTreeParentId};if(t){n.bitmapUrl=this.#eo(!0);n.accessibilityData=this.serializeAltText(!0);return n}const{decorative:s,altText:a}=this.serializeAltText(!1);!s&&a&&(n.accessibilityData={type:"Figure",alt:a});if(this.annotationElementId){const t=this.#zs(n);if(t.isSame)return null;t.isSameAltText?delete n.accessibilityData:n.accessibilityData.structParent=this._initialData.structParent??-1}n.id=this.annotationElementId;if(null===e)return n;e.stamps||=new Map;const r=this.#qr?(n.rect[2]-n.rect[0])*(n.rect[3]-n.rect[1]):null;if(e.stamps.has(this.#Hr)){if(this.#qr){const t=e.stamps.get(this.#Hr);if(r>t.area){t.area=r;t.serialized.bitmap.close();t.serialized.bitmap=this.#eo(!1)}}}else{e.stamps.set(this.#Hr,{area:r,serialized:n});n.bitmap=this.#eo(!1)}return n}#zs(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,n=t.pageIndex===e,s=(t.accessibilityData?.alt||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&n&&s,isSameAltText:s}}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}}class PointerType{static current=null;static editor=null;constructor(t){if(null===PointerType.current){PointerType.current="";window.addEventListener("pointerdown",this.windowPointerDown,!0)}}destroy(){if(null!==PointerType.current){window.removeEventListener("pointerdown",this.windowPointerDown,!0);PointerType.current=null}}windowPointerDown(t){PointerType.current=t.pointerType;return!0}static initializeEditor(){setTimeout((()=>PointerType.editor=PointerType.current))}static sameAsEditor(t=void 0){return t?PointerType.editor==t:PointerType.editor==PointerType.current}}new PointerType;class AnnotationEditorLayer{#Ss;#io=!1;#no=null;#so=null;#ao=null;#ro=new Map;#oo=!1;#lo=!1;#ho=!1;#do=null;#co=null;#uo=null;#po=null;#Ce;static _initialized=!1;static#Ze=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:n,accessibilityManager:s,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h,eventBus:d}){const c=[...AnnotationEditorLayer.#Ze.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of c)e.initialize(h,t)}t.registerEditorTypes(c);this.#Ce=t;this.pageIndex=e;this.div=i;this.#Ss=s;this.#no=a;this.viewport=l;this.#uo=o;this.drawLayer=r;this._structTree=n;this.#Ce.addLayer(this);this.eventBus=d}get isEmpty(){return 0===this.#ro.size}get isInvisible(){return this.isEmpty&&this.#Ce.getMode()===i.AnnotationEditorType.NONE}updateToolbar(t){this.#Ce.updateToolbar(t)}updateMode(t=this.#Ce.getMode()){this.#go();switch(t){case i.AnnotationEditorType.NONE:this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case i.AnnotationEditorType.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case i.AnnotationEditorType.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}PointerType.initializeEditor();this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of AnnotationEditorLayer.#Ze.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#uo?.div}setEditingState(t){this.#Ce.setEditingState(t)}addCommands(t){this.#Ce.addCommands(t)}cleanUndoStack(t){this.#Ce.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#no?.div.classList.toggle("disabled",!t)}async enable(){this.#ho=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);const t=new Set;for(const e of this.#ro.values()){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#Ce.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}if(!this.#no){this.#ho=!1;return}const e=this.#no.getEditableAnnotations();for(const i of e){i.hide();if(this.#Ce.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#ho=!1}disable(){this.#lo=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#ro.values()){i.disableEditing();if(i.annotationElementId)if(null===i.serialize()){e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show();i.remove()}else t.set(i.annotationElementId,i)}if(this.#no){const i=this.#no.getEditableAnnotations();for(const n of i){const{id:i}=n.data;if(this.#Ce.isDeletedAnnotationElement(i))continue;let s=e.get(i);if(s){s.resetAnnotationElement(n);s.show(!1);n.show()}else{s=t.get(i);if(s){this.#Ce.addChangedExistingAnnotation(s);s.renderAnnotationElement(n)&&s.show(!1)}n.show()}}}this.#go();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#Ze.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);this.#lo=!1}getEditableAnnotation(t){return this.#no?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#Ce.getActive()!==t&&this.#Ce.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#uo?.div&&!this.#po){this.#po=new AbortController;const t=this.#Ce.combinedSignal(this.#po);this.#uo.div.addEventListener("pointerdown",this.#mo.bind(this),{signal:t});this.#uo.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#uo?.div&&this.#po){this.#po.abort();this.#po=null;this.#uo.div.classList.remove("highlighting")}}#mo(t){this.#Ce.unselectAll();const{target:e}=t;if(e===this.#uo.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#uo.div.contains(e)){const{isMac:e}=i.FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#Ce.showAllEditors("highlight",!0,!0);this.#uo.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#Ce.direction,{target:this.#uo.div,x:t.x,y:t.y});this.#uo.div.addEventListener("pointerup",(()=>{this.#uo.div.classList.remove("free");this.toggleDrawing(!0)}),{once:!0,signal:this.#Ce._signal});t.preventDefault()}}enableClick(){if(this.#so)return;this.#so=new AbortController;const t=this.#Ce.combinedSignal(this.#so);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#so?.abort();this.#so=null}attach(t){this.#ro.set(t.id,t);const{annotationElementId:e}=t;e&&this.#Ce.isDeletedAnnotationElement(e)&&this.#Ce.removeDeletedAnnotationElement(t)}detach(t){this.#ro.delete(t.id);this.#Ss?.removePointerInTextLayer(t.contentDiv);!this.#lo&&t.annotationElementId&&this.#Ce.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#Ce.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#Ce.addDeletedAnnotationElement(t.annotationElementId);a.AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#Ce.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#ho);this.#Ce.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#ao){t._focusEventsAllowed=!1;this.#ao=setTimeout((()=>{this.#ao=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#Ce._signal});e.focus()}}),0)}t._structTreeParentId=this.#Ss?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#Ce.getId()}get#fo(){return AnnotationEditorLayer.#Ze.get(this.#Ce.getMode())}combinedSignal(t){return this.#Ce.combinedSignal(t)}#bo(t){const e=this.#fo;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#fo?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#Ce.updateToolbar(t);this.#Ce.updateMode(t);const{offsetX:i,offsetY:n}=this.#wo(),s=this.getNextId(),a=this.#bo({parent:this,id:s,x:i,y:n,uiManager:this.#Ce,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#Ze.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#Ce))||null}createAndAddNewEditor(t,e,i={}){const n=this.getNextId(),s=this.#bo({parent:this,id:n,x:t.offsetX,y:t.offsetY,uiManager:this.#Ce,isCentered:e,eventBus:this.eventBus,...i});s&&this.add(s);return s}#wo(){const{x:t,y:e,width:i,height:n}=this.div.getBoundingClientRect(),s=Math.max(0,t),a=Math.max(0,e),r=(s+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+n))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#wo(),!0)}setSelected(t){this.#Ce.setSelected(t)}toggleSelected(t){this.#Ce.toggleSelected(t)}unselect(t){this.#Ce.unselect(t)}pointerup(t){const{isMac:e}=i.FeatureTest.platform;if(!(0!==t.button||t.ctrlKey&&e)&&t.target===this.div&&this.#oo){this.#oo=!1;this.#fo?.isDrawer&&this.#fo.supportMultipleDrawings||(this.#io?this.#Ce.getMode()!==i.AnnotationEditorType.STAMP?this.createAndAddNewEditor(t,!1):this.#Ce.unselectAll():this.#io=!0)}}pointerdown(t){if(this.#Ce.getMode()===i.AnnotationEditorType.HIGHLIGHT){if(!PointerType.sameAsEditor(t.pointerType))return;this.enableTextSelection()}else if(this.#Ce.getMode()===i.AnnotationEditorType.INK&&!PointerType.sameAsEditor(t.pointerType))return;if(this.#oo){this.#oo=!1;return}const{isMac:e}=i.FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#oo=!0;if(this.#fo?.isDrawer){this.startDrawingSession(t);return}const n=this.#Ce.getActive();this.#io=!n||n.isEmpty()}startDrawingSession(t){this.div.focus();if(this.#do){this.#fo.startDrawing(this,this.#Ce,!1,t);return}this.#Ce.setCurrentDrawingSession(this);this.#do=new AbortController;const e=this.#Ce.combinedSignal(this.#do);this.div.addEventListener("blur",(({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#co=null;this.commitOrRemove()}}),{signal:e});this.#fo.startDrawing(this,this.#Ce,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#co=t)}else this.#co&&setTimeout((()=>{this.#co?.focus();this.#co=null}),0)}endDrawingSession(t=!1){if(!this.#do)return null;this.#Ce.setCurrentDrawingSession(null);this.#do.abort();this.#do=null;this.#co=null;return this.#fo.endDrawing(t)}findNewParent(t,e,i){const n=this.#Ce.findParent(e,i);if(null===n||n===this)return!1;n.changeParent(t);return!0}commitOrRemove(){if(this.#do){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#do&&this.#fo.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#Ce.getActive()?.parent===this){this.#Ce.commitOrRemove();this.#Ce.setActiveEditor(null)}if(this.#ao){clearTimeout(this.#ao);this.#ao=null}for(const t of this.#ro.values()){this.#Ss?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#ro.clear();this.#Ce.removeLayer(this)}#go(){for(const t of this.#ro.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;(0,s.setLayerDimensions)(this.div,t);for(const t of this.#Ce.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#Ce.commitOrRemove();this.#go();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;(0,s.setLayerDimensions)(this.div,{rotation:i});if(e!==i)for(const t of this.#ro.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#Ce.viewParameters.realScale}}class DrawLayer{#is=null;#L=0;#vo=new Map;#yo=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#is){if(this.#is!==t){if(this.#vo.size>0)for(const e of this.#vo.values()){e.remove();t.append(e)}this.#is=t}}else this.#is=t}static get _svgFactory(){return(0,i.shadow)(this,"_svgFactory",new DOMSVGFactory)}static#Ao(t,[e,i,n,s]){const{style:a}=t;a.top=100*i+"%";a.left=100*e+"%";a.width=100*n+"%";a.height=100*s+"%"}#xo(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#is.append(t);t.setAttribute("aria-hidden",!0);return t}#Eo(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const n=`clip_${e}`;i.setAttribute("id",n);i.setAttribute("clipPathUnits","objectBoundingBox");const s=DrawLayer._svgFactory.createElement("use");i.append(s);s.setAttribute("href",`#${e}`);s.classList.add("clip");return n}#So(t,e){for(const[i,n]of Object.entries(e))null===n?t.removeAttribute(i):t.setAttribute(i,n)}draw(t,e=!1,i=!1){const n=this.#L++,s=this.#xo(),a=DrawLayer._svgFactory.createElement("defs");s.append(a);const r=DrawLayer._svgFactory.createElement("path");a.append(r);const o=`path_p${this.pageIndex}_${n}`;r.setAttribute("id",o);r.setAttribute("vector-effect","non-scaling-stroke");e&&this.#yo.set(n,r);const l=i?this.#Eo(a,o):null,h=DrawLayer._svgFactory.createElement("use");s.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(s,t);this.#vo.set(n,s);return{id:n,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=this.#L++,n=this.#xo(),s=DrawLayer._svgFactory.createElement("defs");n.append(s);const a=DrawLayer._svgFactory.createElement("path");s.append(a);const r=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",r);a.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");s.append(t);o=`mask_p${this.pageIndex}_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const n=DrawLayer._svgFactory.createElement("use");t.append(n);n.setAttribute("href",`#${r}`);n.setAttribute("stroke","none");n.setAttribute("fill","black");n.setAttribute("fill-rule","nonzero");n.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");n.append(l);l.setAttribute("href",`#${r}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();n.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(n,t);this.#vo.set(i,n);return i}finalizeDraw(t,e){this.#yo.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:n,rootClass:s,path:a}=e,r="number"==typeof t?this.#vo.get(t):t;if(r){i&&this.#So(r,i);n&&DrawLayer.#Ao(r,n);if(s){const{classList:t}=r;for(const[e,i]of Object.entries(s))t.toggle(e,i)}if(a){const t=r.firstChild.firstChild;this.#So(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#vo.get(t);if(i){e.#is.append(i);this.#vo.delete(t);e.#vo.set(t,i)}}remove(t){this.#yo.delete(t);if(null!==this.#is){this.#vo.get(t).remove();this.#vo.delete(t)}}destroy(){this.#is=null;for(const t of this.#vo.values())t.remove();this.#vo.clear();this.#yo.clear()}}var u=e(164),p=e(814),g=e(900);globalThis.pdfjsTestingUtils={HighlightOutliner}},651:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{MurmurHash3_64:()=>MurmurHash3_64});const i=3285377520,n=4294901760,s=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:i;this.h2=t?4294967295&t:i}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let n=0,s=t.length;n<s;n++){const s=t.charCodeAt(n);if(s<=255)e[i++]=s;else{e[i++]=s>>>8;e[i++]=255&s}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const a=i>>2,r=i-4*a,o=new Uint32Array(e.buffer,0,a);let l=0,h=0,d=this.h1,c=this.h2;const u=3432918353,p=461845907,g=11601,m=13715;for(let t=0;t<a;t++)if(1&t){l=o[t];l=l*u&n|l*g&s;l=l<<15|l>>>17;l=l*p&n|l*m&s;d^=l;d=d<<13|d>>>19;d=5*d+3864292196}else{h=o[t];h=h*u&n|h*g&s;h=h<<15|h>>>17;h=h*p&n|h*m&s;c^=h;c=c<<13|c>>>19;c=5*c+3864292196}l=0;switch(r){case 3:l^=e[4*a+2]<<16;case 2:l^=e[4*a+1]<<8;case 1:l^=e[4*a];l=l*u&n|l*g&s;l=l<<15|l>>>17;l=l*p&n|l*m&s;1&a?d^=l:c^=l}this.h1=d;this.h2=c}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&n|36045*t&s;e=4283543511*e&n|(2950163797*(e<<16|t>>>16)&n)>>>16;t^=e>>>1;t=444984403*t&n|60499*t&s;e=3301882366*e&n|(3120437893*(e<<16|t>>>16)&n)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}},292:(t,__webpack_exports__,e)=>{e.d(__webpack_exports__,{AbortException:()=>AbortException,AnnotationBorderStyleType:()=>b,AnnotationEditorParamsType:()=>u,AnnotationEditorPrefix:()=>d,AnnotationEditorType:()=>c,AnnotationMode:()=>h,AnnotationPrefix:()=>_,AnnotationType:()=>f,BaseException:()=>x,FONT_IDENTITY_MATRIX:()=>a,FeatureTest:()=>FeatureTest,FormatError:()=>FormatError,IDENTITY_MATRIX:()=>s,ImageKind:()=>m,InvalidPDFException:()=>InvalidPDFException,LINE_FACTOR:()=>o,MAX_IMAGE_SIZE_TO_CACHE:()=>r,MissingPDFException:()=>MissingPDFException,OPS:()=>v,PasswordException:()=>PasswordException,PasswordResponses:()=>y,PermissionFlag:()=>p,RenderingIntentFlag:()=>l,TextRenderingMode:()=>g,UnexpectedResponseException:()=>UnexpectedResponseException,UnknownErrorException:()=>UnknownErrorException,Util:()=>Util,VerbosityLevel:()=>w,assert:()=>assert,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,getUuid:()=>getUuid,getVerbosityLevel:()=>getVerbosityLevel,info:()=>info,isNodeJS:()=>n,normalizeUnicode:()=>normalizeUnicode,objectFromMap:()=>objectFromMap,setVerbosityLevel:()=>setVerbosityLevel,shadow:()=>shadow,string32:()=>string32,stringToBytes:()=>stringToBytes,toBase64Util:()=>toBase64Util,unreachable:()=>unreachable,warn:()=>warn});var i=e(641);const n=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),s=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],r=1e7,o=1.35,l={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},h={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},d="pdfjs_internal_editor_",c={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},u={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,DRAW_STEP:41},p={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},g={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},m={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},f={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},b={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},w={ERRORS:0,WARNINGS:1,INFOS:5},v={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},y={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let A=w.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(A=t)}function getVerbosityLevel(){return A}function info(t){A>=w.INFOS&&("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?console.log(`Info: ${t}`):Window&&i.NgxConsole?i.NgxConsole.log(`Info: ${t}`):console.log(`Info: ${t}`))}function warn(t){A>=w.WARNINGS&&("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope||Window&&i.NgxConsole?i.NgxConsole.log(`Warning: ${t}`):console.log(`Warning: ${t}`))}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(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=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const n=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":case"capacitor":return!0;default:return!1}}(n))return n}catch{}return null}function shadow(t,e,i,n=!1){Object.defineProperty(t,e,{value:i,enumerable:!n,configurable:!0,writable:!1});return i}const x=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends x{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends x{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends x{constructor(t){super(t,"InvalidPDFException")}}class MissingPDFException extends x{constructor(t){super(t,"MissingPDFException")}}class UnexpectedResponseException extends x{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}}class FormatError extends x{constructor(t){super(t,"FormatError")}}class AbortException extends x{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const n=[];for(let s=0;s<e;s+=i){const a=Math.min(s+i,e),r=t.subarray(s,a);n.push(String.fromCharCode.apply(null,r))}return n.join("")}function stringToBytes(t){"string"!=typeof t&&unreachable("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let n=0;n<e;++n)i[n]=255&t.charCodeAt(n);return i}function string32(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}function objectFromMap(t){const e=Object.create(null);for(const[i,n]of t)e[i]=n;return e}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const t=new Uint8Array(4);t[0]=1;return 1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):shadow(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const E=Array.from(Array(256).keys(),(t=>t.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,i){return`#${E[t]}${E[e]}${E[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(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),n=this.applyTransform(t.slice(2,4),e),s=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],n[0],s[0],a[0]),Math.min(i[1],n[1],s[1],a[1]),Math.max(i[0],n[0],s[0],a[0]),Math.max(i[1],n[1],s[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],n=t[0]*e[1]+t[1]*e[3],s=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-s*n))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),n=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>n)return null;const s=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 s>a?null:[i,s,n,a]}static#Po(t,e,i,n,s,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*n,g=d*(d*(d*s+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#_o(t,e,i,n,s,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#Po(t,e,i,n,s,a,r,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#Po(t,e,i,n,s,a,r,o,(-h+p)/g,c);this.#Po(t,e,i,n,s,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,n,s,a,r,o,l){if(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)}else l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)];this.#_o(t,i,s,r,e,n,a,o,3*(3*(i-s)-t+r),6*(t-2*i+s),3*(i-t),l);this.#_o(t,i,s,r,e,n,a,o,3*(3*(n-a)-e+o),6*(e-2*n+a),3*(n-e),l);return l}}let S=null,P=null;function normalizeUnicode(t){if(!S){S=/([\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;P=new Map([["ſt","ſt"]])}return t.replaceAll(S,((t,e,i)=>e?e.normalize("NFKC"):P.get(i)))}function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}const _="pdfjs_internal_id_";function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise((i=>{i(t(...e))}))})},276:(t,e,i)=>{var n=i(641);const s="auto",a=.1,r={INITIAL:0,RUNNING:1,PAUSED:2,FINISHED:3},o=0,l=1,h=2,d=3,c=-1,u=0,p=1,g=2,m=3,f=4,b=0,w=1,v=2,y={UNKNOWN:-1,VERTICAL:0,HORIZONTAL:1,WRAPPED:2,PAGE:3},A={UNKNOWN:-1,NONE:0,ODD:1,EVEN:2},x=0,E=1,S=/\bprint\s*\(/;function scrollIntoView(t,e,i=!1,s=!1){if(t.classList.contains("stf__item")||t.parentElement?.classList.contains("stf__item")||t.parentElement?.parentElement?.classList.contains("stf__item"))return;let a=t.offsetParent;if(!a){n.NgxConsole.error("offsetParent is not set -- cannot scroll");return}let r=t.offsetTop+t.clientTop,o=t.offsetLeft+t.clientLeft;for(;a.clientHeight===a.scrollHeight&&a.clientWidth===a.scrollWidth||i&&(a.classList.contains("markedContent")||"hidden"===getComputedStyle(a).overflow);){r+=a.offsetTop;o+=a.offsetLeft;a=a.offsetParent;if(!a){if(s&&document.body.clientHeight>r){r-=32;window.scrollTo(window.scrollX,r)}return}}if(e){void 0!==e.top&&(r+=e.top);if(void 0!==e.left){o+=e.left;a.scrollLeft=o}}else if(function isDivInViewport(t){const e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}(t))return;a.scrollTop=r}function watchScroll(t,e,i=void 0){const debounceScroll=function(i){s||(s=window.requestAnimationFrame((function viewAreaElementScrolled(){s=null;const i=t.scrollLeft,a=n.lastX;i!==a&&(n.right=i>a);n.lastX=i;const r=t.scrollTop,o=n.lastY;r!==o&&(n.down=r>o);n.lastY=r;e(n)})))},n={right:!0,down:!0,lastX:t.scrollLeft,lastY:t.scrollTop,_eventHandler:debounceScroll};let s=null;t.addEventListener("scroll",debounceScroll,{useCapture:!0,signal:i});i?.addEventListener("abort",(()=>window.cancelAnimationFrame(s)),{once:!0});return n}function parseQueryString(t){const e=new Map;for(const[i,n]of new URLSearchParams(t))e.set(i.toLowerCase(),n);return e}const P=/[\x00-\x1F]/g;function removeNullCharacters(t,e=!1){return P.test(t)?e?t.replaceAll(P,(t=>"\0"===t?"":" ")):t.replaceAll("\0",""):t}function binarySearchFirstItem(t,e,i=0){let n=i,s=t.length-1;if(s<0||!e(t[s]))return t.length;if(e(t[n]))return n;for(;n<s;){const i=n+s>>1;e(t[i])?s=i:n=i+1}return n}function approximateFraction(t){if(Math.floor(t)===t)return[t,1];const e=1/t;if(e>8)return[1,8];if(Math.floor(e)===e)return[1,e];const i=t>1?e:t;let n,s=0,a=1,r=1,o=1;for(;;){const t=s+r,e=a+o;if(e>8)break;if(i<=t/e){r=t;o=e}else{s=t;a=e}}n=i-s/a<r/o-i?i===t?[s,a]:[a,s]:i===t?[r,o]:[o,r];return n}function floorToDivide(t,e){return t-t%e}function getPageSizeInches({view:t,userUnit:e,rotate:i}){const[n,s,a,r]=t,o=i%180!=0,l=(a-n)/72*e,h=(r-s)/72*e;return{width:o?h:l,height:o?l:h}}function getVisibleElements({scrollEl:t,views:e,sortByVisibility:i=!1,horizontal:n=!1,rtl:s=!1}){const a=t.scrollTop,r=a+t.clientHeight,o=t.scrollLeft,l=o+t.clientWidth;const h=[],d=new Set,c=e.length;let u=binarySearchFirstItem(e,n?function isElementNextAfterViewHorizontally(t){const e=t.div,i=e.offsetLeft+e.clientLeft,n=i+e.clientWidth;return s?i<l:n>o}:function isElementBottomAfterViewTop(t){const e=t.div;return e.offsetTop+e.clientTop+e.clientHeight>a});u>0&&u<c&&!n&&(u=function backtrackBeforeAllVisibleElements(t,e,i){if(t<2)return t;let n=e[t].div,s=n.offsetTop+n.clientTop;if(s>=i){n=e[t-1].div;s=n.offsetTop+n.clientTop}for(let i=t-2;i>=0;--i){n=e[i].div;if(n.offsetTop+n.clientTop+n.clientHeight<=s)break;t=i}return t}(u,e,a));let p=n?l:-1;for(let t=u;t<c;t++){const i=e[t],s=i.div,c=s.offsetLeft+s.clientLeft,u=s.offsetTop+s.clientTop,g=s.clientWidth,m=s.clientHeight,f=c+g,b=u+m;if(-1===p)b>=r&&(p=b);else if((n?c:u)>p)break;if(b<=a||u>=r||f<=o||c>=l)continue;const w=Math.max(0,a-u)+Math.max(0,b-r),v=(g-(Math.max(0,o-c)+Math.max(0,f-l)))/g,y=(m-w)/m*v*100|0;h.push({id:i.id,x:c,y:u,view:i,percent:y,widthPercent:100*v|0});d.add(i.id)}const g=h[0],m=h.at(-1);i&&h.sort((function(t,e){const i=t.percent-e.percent;return Math.abs(i)>.001?-i:t.id-e.id}));return{first:g,last:m,views:h,ids:d}}function normalizeWheelEventDirection(t){let e=Math.hypot(t.deltaX,t.deltaY);const i=Math.atan2(t.deltaY,t.deltaX);-.25*Math.PI<i&&i<.75*Math.PI&&(e=-e);return e}function isValidRotation(t){return Number.isInteger(t)&&t%90==0}function isValidScrollMode(t){return Number.isInteger(t)&&Object.values(y).includes(t)&&t!==y.UNKNOWN}function isValidSpreadMode(t){return Number.isInteger(t)&&Object.values(A).includes(t)&&t!==A.UNKNOWN}function isPortraitOrientation(t){return t.width<=t.height}const _=new Promise((function(t){window.requestAnimationFrame(t)})),C=document.documentElement.style;class ProgressBar{#Co=null;#To=null;#Mo=0;#Io=null;#y=!0;constructor(t){this.#Co=t.classList;this.#Io=t.style}get percent(){return this.#Mo}set percent(t){this.#Mo=function clamp(t,e,i){return Math.min(Math.max(t,e),i)}(t,0,100);if(isNaN(t))this.#Co.add("indeterminate");else{this.#Co.remove("indeterminate");this.#Io.setProperty("--progressBar-percent",`${this.#Mo}%`)}}setWidth(t){if(!t)return;const e=t.parentNode.offsetWidth-t.offsetWidth;e>0&&this.#Io.setProperty("--progressBar-end-offset",`${e}px`)}setDisableAutoFetch(t=5e3){if(100!==this.#Mo&&!isNaN(this.#Mo)){this.#To&&clearTimeout(this.#To);this.show();this.#To=setTimeout((()=>{this.#To=null;this.hide()}),t)}}hide(){if(this.#y){this.#y=!1;this.#Co.add("hidden")}}show(){if(!this.#y){this.#y=!0;this.#Co.remove("hidden")}}}function getActiveOrFocusedElement(){let t=document,e=t.activeElement||t.querySelector(":focus");for(;e?.shadowRoot;){t=e.shadowRoot;e=t.activeElement||t.querySelector(":focus")}return e}function apiPageLayoutToViewerModes(t){let e=y.VERTICAL,i=A.NONE;switch(t){case"SinglePage":e=y.PAGE;break;case"OneColumn":break;case"TwoPageLeft":e=y.PAGE;case"TwoColumnLeft":i=A.ODD;break;case"TwoPageRight":e=y.PAGE;case"TwoColumnRight":i=A.EVEN}return{scrollMode:e,spreadMode:i}}function toggleCheckedBtn(t,e,i=null){t.classList.toggle("toggled",e);t.setAttribute("aria-checked",e);i?.classList.toggle("hidden",!e)}function toggleExpandedBtn(t,e,i=null){t.classList.toggle("toggled",e);t.setAttribute("aria-expanded",e);i?.classList.toggle("hidden",!e);if(i&&!i.classList.contains("hidden")){const e=t.getBoundingClientRect(),n=t.closest("#toolbarViewer");if(n){const t=n.getBoundingClientRect().right-e.right;i.style.removeProperty("inset-inline-end");i.style.setProperty("inset-inline-end",t+"px")}}}const T=function(){const t=document.createElement("div");t.style.width="round(down, calc(1.6666666666666665 * 792px), 1px)";return"calc(1320px)"===t.style.width?Math.fround:t=>t}();function isInsideNgxExtendedPdfViewer(t){let e=t;for(;e;){if("ngx-extended-pdf-viewer"===e.tagName.toLowerCase())return!0;e=e.parentElement}return!1}{var M=new Map;const t=navigator.userAgent||"",e=navigator.platform||"",i=navigator.maxTouchPoints||1,n=/Android/.test(t);(/\b(iPad|iPhone|iPod)(?=;)/.test(t)||"MacIntel"===e&&i>1||n)&&M.set("maxCanvasPixels",5242880);n&&M.set("useSystemFonts",!1)}const I=1,D=2,L=4,k=8,F=16,R=128,N={BOOLEAN:1,NUMBER:2,OBJECT:4,STRING:8,UNDEFINED:16},B={defaultCacheSize:{value:50,kind:D},passwordPrompt:{value:null,kind:D},enableDragAndDrop:{value:!0,kind:D},pageViewMode:{value:"multiple",kind:D},findController:{value:null,kind:D},secondaryFindController:{value:null,kind:D},allowedGlobalEvents:{value:null,kind:I},canvasMaxAreaInBytes:{value:-1,kind:I+L},isInAutomation:{value:!1,kind:I},localeProperties:{value:{lang:navigator.language||"en-US"},kind:I},nimbusDataStr:{value:"",kind:I},supportsCaretBrowsingMode:{value:!1,kind:I},supportsDocumentFonts:{value:!0,kind:I},supportsIntegratedFind:{value:!1,kind:I},supportsMouseWheelZoomCtrlKey:{value:!0,kind:I},supportsMouseWheelZoomMetaKey:{value:!0,kind:I},supportsPinchToZoom:{value:!0,kind:I},toolbarDensity:{value:0,kind:I+F},altTextLearnMoreUrl:{value:"",kind:D+R},annotationEditorMode:{value:0,kind:D+R},annotationMode:{value:2,kind:D+R},cursorToolOnLoad:{value:0,kind:D+R},debuggerSrc:{value:"./debugger.mjs",kind:D},defaultZoomDelay:{value:400,kind:D+R},defaultZoomValue:{value:"auto",kind:D+R},disableHistory:{value:!1,kind:D},disablePageLabels:{value:!1,kind:D+R},enableAltText:{value:!1,kind:D+R},enableAltTextModelDownload:{value:!0,kind:D+R+F},enableGuessAltText:{value:!0,kind:D+R+F},enableHighlightFloatingButton:{value:!1,kind:D+R},enableNewAltTextWhenAddingImage:{value:!0,kind:D+R},enablePermissions:{value:!1,kind:D+R},enablePrintAutoRotate:{value:!0,kind:D+R},enableScripting:{value:!0,kind:D+R},enableUpdatedAddImage:{value:!1,kind:D+R},externalLinkRel:{value:"noopener noreferrer nofollow",kind:D},externalLinkTarget:{value:0,kind:D+R},highlightEditorColors:{value:"yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F",kind:D+R},historyUpdateUrl:{value:!1,kind:D+R},ignoreDestinationZoom:{value:!1,kind:D+R},imageResourcesPath:{value:"./images/",kind:D},maxCanvasPixels:{value:2**25,kind:D},forcePageColors:{value:!1,kind:D+R},pageColorsBackground:{value:"Canvas",kind:D+R},pageColorsForeground:{value:"CanvasText",kind:D+R},pdfBugEnabled:{value:!1,kind:D+R},printResolution:{value:150,kind:D},removePageBorders:{value:!1,kind:D+R},sidebarViewOnLoad:{value:-1,kind:D+R},scrollModeOnLoad:{value:-1,kind:D+R},spreadModeOnLoad:{value:-1,kind:D+R},textLayerMode:{value:1,kind:D+R},viewOnLoad:{value:0,kind:D+R},cMapPacked:{value:!0,kind:L},cMapUrl:{value:"../web/cmaps/",kind:L},disableAutoFetch:{value:!1,kind:L+R},disableFontFace:{value:!1,kind:L+R},disableRange:{value:!1,kind:L+R},disableStream:{value:!1,kind:L+R},docBaseUrl:{value:"",kind:L},enableHWA:{value:!0,kind:L+D+R},enableXfa:{value:!0,kind:L+R},fontExtraProperties:{value:!1,kind:L},isEvalSupported:{value:!0,kind:L},isOffscreenCanvasSupported:{value:!0,kind:L},maxZoom:{value:10,kind:D},minZoom:{value:.1,kind:D},maxImageSize:{value:-1,kind:L},pdfBug:{value:!1,kind:L},standardFontDataUrl:{value:"../web/standard_fonts/",kind:L},useSystemFonts:{value:void 0,kind:L,type:N.BOOLEAN+N.UNDEFINED},verbosity:{value:1,kind:L},workerPort:{value:null,kind:k},workerSrc:{value:"./assets/pdf.worker.mjs",kind:k}};B.defaultUrl={value:"compressed.tracemonkey-pldi-09.pdf",kind:D};B.sandboxBundleSrc={value:"../build/pdf.sandbox.mjs",kind:D};B.viewerCssTheme={value:0,kind:D+R};B.enableFakeMLManager={value:!0,kind:D};B.disablePreferences={value:!1,kind:D};class AppOptions{static eventBus;static#Do=new Map;static{for(const t in B)this.#Do.set(t,B[t].value);for(const[t,e]of M)this.#Do.set(t,e);this._hasInvokedSet=!1;this._checkDisablePreferences=()=>{if(this.get("disablePreferences"))return!0;this._hasInvokedSet&&console.warn('The Preferences may override manually set AppOptions; please use the "disablePreferences"-option to prevent that.');return!1}}static get(t){return this.#Do.get(t)}static getAll(t=null,e=!1){const i=Object.create(null);for(const n in B){const s=B[n];(!t||t&s.kind)&&(i[n]=e?s.value:this.#Do.get(n))}return i}static set(t,e){this.setAll({[t]:e})}static setAll(t,e=!1){this._hasInvokedSet||=!0;let i;for(const n in t){const s=B[n];let a=t[n];if(!s||!(typeof a==typeof s.value||N[(typeof a).toUpperCase()]&s.type)){"number"==typeof s.value&&"string"==typeof a&&(Number.isNaN(Number(a))||(a=Number(a)));if(!(typeof a==typeof s.value||N[(typeof a).toUpperCase()]&s.type||["maxZoom","minZoom","passwordPrompt","defaultZoomValue","findController"].includes(n))){console.error("Invalid AppOptions value: "+n+" = "+a);continue}}const{kind:r}=s;if(!e||r&I||r&R){this.eventBus&&r&F&&(i||=new Map).set(n,a);this.#Do.set(n,a)}else console.error("Invalid AppOptions parameter: "+n+" = "+a)}if(i)for(const[t,e]of i)this.eventBus.dispatch(t.toLowerCase(),{source:this,value:e})}}const O={NONE:0,SELF:1,BLANK:2,PARENT:3,TOP:4};class PDFLinkService{externalLinkEnabled=!0;constructor({eventBus:t,externalLinkTarget:e=null,externalLinkRel:i=null,ignoreDestinationZoom:n=!1}={}){this.eventBus=t;this.externalLinkTarget=e;this.externalLinkRel=i;this._ignoreDestinationZoom=n;this.baseUrl=null;this.pdfDocument=null;this.pdfViewer=null;this.pdfHistory=null}setDocument(t,e=null){this.baseUrl=e;this.pdfDocument=t}setViewer(t){this.pdfViewer=t}setHistory(t){this.pdfHistory=t}get pagesCount(){return this.pdfDocument?this.pdfDocument.numPages:0}get page(){return this.pdfDocument?this.pdfViewer.currentPageNumber:1}set page(t){this.pdfDocument&&(this.pdfViewer.currentPageNumber=t)}get rotation(){return this.pdfDocument?this.pdfViewer.pagesRotation:0}set rotation(t){this.pdfDocument&&(this.pdfViewer.pagesRotation=t)}get isInPresentationMode(){return!!this.pdfDocument&&this.pdfViewer.isInPresentationMode}async goToDestination(t){if(!this.pdfDocument)return;let e,i,s;if("string"==typeof t){e=t;i=await this.pdfDocument.getDestination(t)}else{e=null;i=await t}if(!Array.isArray(i)){console.error(`goToDestination: "${i}" is not a valid destination array, for dest="${t}".`);return}const[a]=i;if(a&&"object"==typeof a){s=this.pdfDocument.cachedPageNumber(a);if(!s)try{s=await this.pdfDocument.getPageIndex(a)+1}catch{n.NgxConsole.error(`goToDestination: "${a}" is not a valid page reference, for dest="${t}".`);return}}else Number.isInteger(a)&&(s=a+1);if(!s||s<1||s>this.pagesCount)n.NgxConsole.error(`goToDestination: "${s}" is not a valid page number, for dest="${t}".`);else{if(this.pdfHistory){this.pdfHistory.pushCurrentPosition();this.pdfHistory.push({namedDest:e,explicitDest:i,pageNumber:s})}this.pdfViewer.scrollPageIntoView({pageNumber:s,destArray:i,ignoreDestinationZoom:this._ignoreDestinationZoom})}}goToPage(t){if(!this.pdfDocument)return;const e="string"==typeof t&&this.pdfViewer.pageLabelToPageNumber(t)||0|t;if(Number.isInteger(e)&&e>0&&e<=this.pagesCount){if(this.pdfHistory){this.pdfHistory.pushCurrentPosition();this.pdfHistory.pushPage(e)}if("book"===this.pdfViewer.pageViewMode){if(this.pdfViewer.pageFlip){this.pdfViewer.ensureAdjacentPagesAreLoaded();const t=this.pdfViewer.currentPageNumber-this.pdfViewer.currentPageNumber%2,i=e-e%2;t===i-2?this.pdfViewer.pageFlip.flipNext():t===i+2?this.pdfViewer.pageFlip.flipPrev():this.pdfViewer.pageFlip.turnToPage(e-1)}}else this.pdfViewer.scrollPageIntoView({pageNumber:e})}else n.NgxConsole.error(`PDFLinkService.goToPage: "${t}" is not a valid page.`)}addLinkAttributes(t,e,i=!1){if(!e||"string"!=typeof e)throw new Error('A valid "url" parameter must provided.');const n=i?O.BLANK:this.externalLinkTarget,s=this.externalLinkRel;if(this.externalLinkEnabled)t.href=t.title=e;else{t.href="";t.title=`Disabled: ${e}`;t.onclick=()=>!1}let a="";switch(n){case O.NONE:break;case O.SELF:a="_self";break;case O.BLANK:a="_blank";break;case O.PARENT:a="_parent";break;case O.TOP:a="_top"}t.target=a;t.rel="string"==typeof s?s:"noopener noreferrer nofollow"}getDestinationHash(t){if("string"==typeof t){if(t.length>0)return this.getAnchorUrl("#"+escape(t))}else if(Array.isArray(t)){const e=JSON.stringify(t);if(e.length>0)return this.getAnchorUrl("#"+escape(e))}return this.getAnchorUrl("")}getAnchorUrl(t){return this.baseUrl?this.baseUrl+t:t}setHash(t){if(!this.pdfDocument)return;let e,i;if(t.includes("=")){const s=parseQueryString(t);if(s.has("search")){const t=s.get("search").replaceAll('"',""),e="true"===s.get("phrase");this.eventBus.dispatch("findfromurlhash",{source:this,query:e?t:t.match(/\S+/g)})}s.has("page")&&(e=0|s.get("page")||1);if(s.has("zoom")){const t=s.get("zoom").split(","),e=t[0],a=parseFloat(e);e.includes("Fit")?"Fit"===e||"FitB"===e?i=[null,{name:e}]:"FitH"===e||"FitBH"===e||"FitV"===e||"FitBV"===e?i=[null,{name:e},t.length>1?0|t[1]:null]:"FitR"===e?5!==t.length?n.NgxConsole.error('PDFLinkService.setHash: Not enough parameters for "FitR".'):i=[null,{name:e},0|t[1],0|t[2],0|t[3],0|t[4]]:n.NgxConsole.error(`PDFLinkService.setHash: "${e}" is not a valid zoom value.`):i=[null,{name:"XYZ"},t.length>1?0|t[1]:null,t.length>2?0|t[2]:null,a?a/100:e]}i?this.pdfViewer.scrollPageIntoView({pageNumber:e||this.page,destArray:i,allowNegativeOffset:!0}):e&&(this.page=e);s.has("pagemode")&&this.eventBus.dispatch("pagemode",{source:this,mode:s.get("pagemode")});s.has("nameddest")&&this.goToDestination(s.get("nameddest"))}else{i=unescape(t);try{i=JSON.parse(i);Array.isArray(i)||(i=i.toString())}catch{}"string"==typeof i||PDFLinkService.#Lo(i)?this.goToDestination(i):console.error(`PDFLinkService.setHash: "${unescape(t)}" is not a valid destination.`)}}executeNamedAction(t){if(this.pdfDocument){switch(t){case"GoBack":this.pdfHistory?.back();break;case"GoForward":this.pdfHistory?.forward();break;case"NextPage":this.pdfViewer.nextPage();break;case"PrevPage":this.pdfViewer.previousPage();break;case"LastPage":this.page=this.pagesCount;break;case"FirstPage":this.page=1}this.eventBus.dispatch("namedaction",{source:this,action:t})}}async executeSetOCGState(t){if(!this.pdfDocument)return;const e=this.pdfDocument,i=await this.pdfViewer.optionalContentConfigPromise;if(e===this.pdfDocument){i.setOCGState(t);this.pdfViewer.optionalContentConfigPromise=Promise.resolve(i)}}static#Lo(t){if(!Array.isArray(t)||t.length<2)return!1;const[e,i,...n]=t;if(!("object"==typeof e&&Number.isInteger(e?.num)&&Number.isInteger(e?.gen)||Number.isInteger(e)))return!1;if("object"!=typeof i||"string"!=typeof i?.name)return!1;const s=n.length;let a=!0;switch(i.name){case"XYZ":if(s<2||s>3)return!1;break;case"Fit":case"FitB":return 0===s;case"FitH":case"FitBH":case"FitV":case"FitBV":if(s>1)return!1;break;case"FitR":if(4!==s)return!1;a=!1;break;default:return!1}for(const t of n)if(!("number"==typeof t||a&&null===t))return!1;return!0}}class SimpleLinkService extends PDFLinkService{setDocument(t,e=null){}}var V=i(292),H=i(900),z=i(925),U=i(419),j=i(909);const W="event",$="timeout";async function waitOnEventOrTimeout({target:t,name:e,delay:i=0}){if("object"!=typeof t||!e||"string"!=typeof e||!(Number.isInteger(i)&&i>=0))throw new Error("waitOnEventOrTimeout - invalid parameters.");const{promise:n,resolve:s}=Promise.withResolvers(),a=new AbortController;function handler(t){a.abort();clearTimeout(r);s(t)}t[t instanceof EventBus?"_on":"addEventListener"](e,handler.bind(null,W),{signal:a.signal});const r=setTimeout(handler.bind(null,$),i);return n}class EventBus{#K=Object.create(null);on(t,e,i=null){this._on(t,e,{external:!0,once:i?.once,signal:i?.signal})}off(t,e,i=null){this._off(t,e)}dispatch(t,e){const i=this.#K[t];if(!i||0===i.length)return;let n;for(const{listener:s,external:a,once:r}of i.slice(0)){r&&this._off(t,s);a?(n||=[]).push(s):s(e)}if(n){for(const t of n)t(e);n=null}}_on(t,e,i=null){let n=null;if(i?.signal instanceof AbortSignal){const{signal:s}=i;if(s.aborted){console.error("Cannot use an `aborted` signal.");return}const onAbort=()=>this._off(t,e);n=()=>s.removeEventListener("abort",onAbort);s.addEventListener("abort",onAbort)}(this.#K[t]||=[]).push({listener:e,external:!0===i?.external,once:!0===i?.once,rmAbort:n})}_off(t,e,i=null){const n=this.#K[t];if(n)for(let t=0,i=n.length;t<i;t++){const i=n[t];if(i.listener===e){i.rmAbort?.();n.splice(t,1);return}}}destroy(){let t;for(t in this.#K)this.#K[t].length=0}}class BaseExternalServices{updateFindControlState(t){}updateFindMatchesCount(t){}initPassiveLoading(){}reportTelemetry(t){}async createL10n(){throw new Error("Not implemented: createL10n")}createScripting(){throw new Error("Not implemented: createScripting")}updateEditorStates(t){throw new Error("Not implemented: updateEditorStates")}dispatchGlobalEvent(t){}}class BasePreferences{#ko=Object.freeze({altTextLearnMoreUrl:"",annotationEditorMode:0,annotationMode:2,cursorToolOnLoad:0,defaultZoomDelay:400,defaultZoomValue:"auto",disablePageLabels:!1,enableAltText:!1,enableAltTextModelDownload:!0,enableGuessAltText:!0,enableHighlightFloatingButton:!1,enableNewAltTextWhenAddingImage:!0,enablePermissions:!1,enablePrintAutoRotate:!0,enableScripting:!0,enableUpdatedAddImage:!1,externalLinkTarget:0,highlightEditorColors:"yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F",historyUpdateUrl:!1,ignoreDestinationZoom:!1,forcePageColors:!1,pageColorsBackground:"Canvas",pageColorsForeground:"CanvasText",pdfBugEnabled:!1,removePageBorders:!1,sidebarViewOnLoad:-1,scrollModeOnLoad:-1,spreadModeOnLoad:-1,textLayerMode:1,viewOnLoad:0,disableAutoFetch:!1,disableFontFace:!1,disableRange:!1,disableStream:!1,enableHWA:!0,enableXfa:!0,viewerCssTheme:0});#Fo=null;constructor(){this.#Fo=this._readFromStorage(this.#ko).then((({browserPrefs:t,prefs:e})=>{AppOptions._checkDisablePreferences()||AppOptions.setAll({...t,...e},!0)}))}async _writeToStorage(t){throw new Error("Not implemented: _writeToStorage")}async _readFromStorage(t){throw new Error("Not implemented: _readFromStorage")}async reset(){await this.#Fo;AppOptions.setAll(this.#ko,!0);await this._writeToStorage(this.#ko)}async set(t,e){await this.#Fo;AppOptions.setAll({[t]:e},!0);await this._writeToStorage(AppOptions.getAll(R))}async get(t){await this.#Fo;return AppOptions.get(t)}get initializedPromise(){return this.#Fo}}class FluentType{constructor(t){this.value=t}valueOf(){return this.value}}class FluentNone extends FluentType{constructor(t="???"){super(t)}toString(t){return`{${this.value}}`}}class FluentNumber extends FluentType{constructor(t,e={}){super(t);this.opts=e}toString(t){try{return t.memoizeIntlObject(Intl.NumberFormat,this.opts).format(this.value)}catch(e){t.reportError(e);return this.value.toString(10)}}}class FluentDateTime extends FluentType{constructor(t,e={}){super(t);this.opts=e}toString(t){try{return t.memoizeIntlObject(Intl.DateTimeFormat,this.opts).format(this.value)}catch(e){t.reportError(e);return new Date(this.value).toISOString()}}}function match(t,e,i){if(i===e)return!0;if(i instanceof FluentNumber&&e instanceof FluentNumber&&i.value===e.value)return!0;if(e instanceof FluentNumber&&"string"==typeof i){if(i===t.memoizeIntlObject(Intl.PluralRules,e.opts).select(e.value))return!0}return!1}function getDefault(t,e,i){if(e[i])return resolvePattern(t,e[i].value);t.reportError(new RangeError("No default"));return new FluentNone}function getArguments(t,e){const i=[],n=Object.create(null);for(const s of e)"narg"===s.type?n[s.name]=resolveExpression(t,s.value):i.push(resolveExpression(t,s));return{positional:i,named:n}}function resolveExpression(t,e){switch(e.type){case"str":return e.value;case"num":return new FluentNumber(e.value,{minimumFractionDigits:e.precision});case"var":return function resolveVariableReference(t,{name:e}){let i;if(t.params){if(!Object.prototype.hasOwnProperty.call(t.params,e))return new FluentNone(`$${e}`);i=t.params[e]}else{if(!t.args||!Object.prototype.hasOwnProperty.call(t.args,e)){t.reportError(new ReferenceError(`Unknown variable: $${e}`));return new FluentNone(`$${e}`)}i=t.args[e]}if(i instanceof FluentType)return i;switch(typeof i){case"string":return i;case"number":return new FluentNumber(i);case"object":if(i instanceof Date)return new FluentDateTime(i.getTime());default:t.reportError(new TypeError(`Variable type not supported: $${e}, ${typeof i}`));return new FluentNone(`$${e}`)}}(t,e);case"mesg":return function resolveMessageReference(t,{name:e,attr:i}){const n=t.bundle._messages.get(e);if(!n){t.reportError(new ReferenceError(`Unknown message: ${e}`));return new FluentNone(e)}if(i){const s=n.attributes[i];if(s)return resolvePattern(t,s);t.reportError(new ReferenceError(`Unknown attribute: ${i}`));return new FluentNone(`${e}.${i}`)}if(n.value)return resolvePattern(t,n.value);t.reportError(new ReferenceError(`No value: ${e}`));return new FluentNone(e)}(t,e);case"term":return function resolveTermReference(t,{name:e,attr:i,args:n}){const s=`-${e}`,a=t.bundle._terms.get(s);if(!a){t.reportError(new ReferenceError(`Unknown term: ${s}`));return new FluentNone(s)}if(i){const e=a.attributes[i];if(e){t.params=getArguments(t,n).named;const i=resolvePattern(t,e);t.params=null;return i}t.reportError(new ReferenceError(`Unknown attribute: ${i}`));return new FluentNone(`${s}.${i}`)}t.params=getArguments(t,n).named;const r=resolvePattern(t,a.value);t.params=null;return r}(t,e);case"func":return function resolveFunctionReference(t,{name:e,args:i}){let n=t.bundle._functions[e];if(!n){t.reportError(new ReferenceError(`Unknown function: ${e}()`));return new FluentNone(`${e}()`)}if("function"!=typeof n){t.reportError(new TypeError(`Function ${e}() is not callable`));return new FluentNone(`${e}()`)}try{let e=getArguments(t,i);return n(e.positional,e.named)}catch(i){t.reportError(i);return new FluentNone(`${e}()`)}}(t,e);case"select":return function resolveSelectExpression(t,{selector:e,variants:i,star:n}){let s=resolveExpression(t,e);if(s instanceof FluentNone)return getDefault(t,i,n);for(const e of i){if(match(t,s,resolveExpression(t,e.key)))return resolvePattern(t,e.value)}return getDefault(t,i,n)}(t,e);default:return new FluentNone}}function resolveComplexPattern(t,e){if(t.dirty.has(e)){t.reportError(new RangeError("Cyclic reference"));return new FluentNone}t.dirty.add(e);const i=[],n=t.bundle._useIsolating&&e.length>1;for(const s of e)if("string"!=typeof s){t.placeables++;if(t.placeables>100){t.dirty.delete(e);throw new RangeError(`Too many placeables expanded: ${t.placeables}, max allowed is 100`)}n&&i.push("");i.push(resolveExpression(t,s).toString(t));n&&i.push("")}else i.push(t.bundle._transform(s));t.dirty.delete(e);return i.join("")}function resolvePattern(t,e){return"string"==typeof e?t.bundle._transform(e):resolveComplexPattern(t,e)}class Scope{constructor(t,e,i){this.dirty=new WeakSet;this.params=null;this.placeables=0;this.bundle=t;this.errors=e;this.args=i}reportError(t){if(!(this.errors&&t instanceof Error))throw t;this.errors.push(t)}memoizeIntlObject(t,e){let i=this.bundle._intls.get(t);if(!i){i={};this.bundle._intls.set(t,i)}let n=JSON.stringify(e);i[n]||(i[n]=new t(this.bundle.locales,e));return i[n]}}function values(t,e){const i=Object.create(null);for(const[n,s]of Object.entries(t))e.includes(n)&&(i[n]=s.valueOf());return i}const G=["unitDisplay","currencyDisplay","useGrouping","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits"];function NUMBER(t,e){let i=t[0];if(i instanceof FluentNone)return new FluentNone(`NUMBER(${i.valueOf()})`);if(i instanceof FluentNumber)return new FluentNumber(i.valueOf(),{...i.opts,...values(e,G)});if(i instanceof FluentDateTime)return new FluentNumber(i.valueOf(),{...values(e,G)});throw new TypeError("Invalid argument to NUMBER")}const q=["dateStyle","timeStyle","fractionalSecondDigits","dayPeriod","hour12","weekday","era","year","month","day","hour","minute","second","timeZoneName"];function DATETIME(t,e){let i=t[0];if(i instanceof FluentNone)return new FluentNone(`DATETIME(${i.valueOf()})`);if(i instanceof FluentDateTime)return new FluentDateTime(i.valueOf(),{...i.opts,...values(e,q)});if(i instanceof FluentNumber)return new FluentDateTime(i.valueOf(),{...values(e,q)});throw new TypeError("Invalid argument to DATETIME")}const X=new Map;class FluentBundle{constructor(t,{functions:e,useIsolating:i=!0,transform:n=t=>t}={}){this._terms=new Map;this._messages=new Map;this.locales=Array.isArray(t)?t:[t];this._functions={NUMBER,DATETIME,...e};this._useIsolating=i;this._transform=n;this._intls=function getMemoizerForLocale(t){const e=Array.isArray(t)?t.join(" "):t;let i=X.get(e);if(void 0===i){i=new Map;X.set(e,i)}return i}(t)}hasMessage(t){return this._messages.has(t)}getMessage(t){return this._messages.get(t)}addResource(t,{allowOverrides:e=!1}={}){const i=[];for(let n=0;n<t.body.length;n++){let s=t.body[n];if(s.id.startsWith("-")){if(!1===e&&this._terms.has(s.id)){i.push(new Error(`Attempt to override an existing term: "${s.id}"`));continue}this._terms.set(s.id,s)}else{if(!1===e&&this._messages.has(s.id)){i.push(new Error(`Attempt to override an existing message: "${s.id}"`));continue}this._messages.set(s.id,s)}}return i}formatPattern(t,e=null,i=null){if("string"==typeof t)return this._transform(t);let n=new Scope(this,i,e);try{return resolveComplexPattern(n,t).toString(n)}catch(t){if(n.errors&&t instanceof Error){n.errors.push(t);return(new FluentNone).toString(n)}throw t}}}const K=/^(-?[a-zA-Z][\w-]*) *= */gm,Y=/\.([a-zA-Z][\w-]*) *= */y,Z=/\*?\[/y,Q=/(-?[0-9]+(?:\.([0-9]+))?)/y,J=/([a-zA-Z][\w-]*)/y,tt=/([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y,et=/^[A-Z][A-Z0-9_-]*$/,it=/([^{}\n\r]+)/y,nt=/([^\\"\n\r]*)/y,st=/\\([\\"])/y,at=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y,rt=/^\n+/,ot=/ +$/,lt=/ *\r?\n/g,ht=/( *)$/,dt=/{\s*/y,ct=/\s*}/y,ut=/\[\s*/y,pt=/\s*] */y,gt=/\s*\(\s*/y,mt=/\s*->\s*/y,ft=/\s*:\s*/y,bt=/\s*,?\s*/y,wt=/\s+/y;class FluentResource{constructor(t){this.body=[];K.lastIndex=0;let e=0;for(;;){let i=K.exec(t);if(null===i)break;e=K.lastIndex;try{this.body.push(parseMessage(i[1]))}catch(t){if(t instanceof SyntaxError)continue;throw t}}function test(i){i.lastIndex=e;return i.test(t)}function consumeChar(i,n){if(t[e]===i){e++;return!0}if(n)throw new n(`Expected ${i}`);return!1}function consumeToken(t,i){if(test(t)){e=t.lastIndex;return!0}if(i)throw new i(`Expected ${t.toString()}`);return!1}function match(i){i.lastIndex=e;let n=i.exec(t);if(null===n)throw new SyntaxError(`Expected ${i.toString()}`);e=i.lastIndex;return n}function match1(t){return match(t)[1]}function parseMessage(t){let e=parsePattern(),i=function parseAttributes(){let t=Object.create(null);for(;test(Y);){let e=match1(Y),i=parsePattern();if(null===i)throw new SyntaxError("Expected attribute value");t[e]=i}return t}();if(null===e&&0===Object.keys(i).length)throw new SyntaxError("Expected message value or attributes");return{id:t,value:e,attributes:i}}function parsePattern(){let i;test(it)&&(i=match1(it));if("{"===t[e]||"}"===t[e])return parsePatternElements(i?[i]:[],1/0);let n=parseIndent();if(n){if(i)return parsePatternElements([i,n],n.length);n.value=trim(n.value,rt);return parsePatternElements([n],n.length)}return i?trim(i,ot):null}function parsePatternElements(i=[],n){for(;;){if(test(it)){i.push(match1(it));continue}if("{"===t[e]){i.push(parsePlaceable());continue}if("}"===t[e])throw new SyntaxError("Unbalanced closing brace");let s=parseIndent();if(!s)break;i.push(s);n=Math.min(n,s.length)}let s=i.length-1,a=i[s];"string"==typeof a&&(i[s]=trim(a,ot));let r=[];for(let t of i){t instanceof Indent&&(t=t.value.slice(0,t.value.length-n));t&&r.push(t)}return r}function parsePlaceable(){consumeToken(dt,SyntaxError);let t=parseInlineExpression();if(consumeToken(ct))return t;if(consumeToken(mt)){let e=function parseVariants(){let t,e=[],i=0;for(;test(Z);){consumeChar("*")&&(t=i);let n=parseVariantKey(),s=parsePattern();if(null===s)throw new SyntaxError("Expected variant value");e[i++]={key:n,value:s}}if(0===i)return null;if(void 0===t)throw new SyntaxError("Expected default variant");return{variants:e,star:t}}();consumeToken(ct,SyntaxError);return{type:"select",selector:t,...e}}throw new SyntaxError("Unclosed placeable")}function parseInlineExpression(){if("{"===t[e])return parsePlaceable();if(test(tt)){let[,i,n,s=null]=match(tt);if("$"===i)return{type:"var",name:n};if(consumeToken(gt)){let a=function parseArguments(){let i=[];for(;;){switch(t[e]){case")":e++;return i;case void 0:throw new SyntaxError("Unclosed argument list")}i.push(parseArgument());consumeToken(bt)}}();if("-"===i)return{type:"term",name:n,attr:s,args:a};if(et.test(n))return{type:"func",name:n,args:a};throw new SyntaxError("Function names must be all upper-case")}return"-"===i?{type:"term",name:n,attr:s,args:[]}:{type:"mesg",name:n,attr:s}}return parseLiteral()}function parseArgument(){let t=parseInlineExpression();return"mesg"!==t.type?t:consumeToken(ft)?{type:"narg",name:t.name,value:parseLiteral()}:t}function parseVariantKey(){consumeToken(ut,SyntaxError);let t;t=test(Q)?parseNumberLiteral():{type:"str",value:match1(J)};consumeToken(pt,SyntaxError);return t}function parseLiteral(){if(test(Q))return parseNumberLiteral();if('"'===t[e])return function parseStringLiteral(){consumeChar('"',SyntaxError);let i="";for(;;){i+=match1(nt);if("\\"!==t[e]){if(consumeChar('"'))return{type:"str",value:i};throw new SyntaxError("Unclosed string literal")}i+=parseEscapeSequence()}}();throw new SyntaxError("Invalid expression")}function parseNumberLiteral(){let[,t,e=""]=match(Q),i=e.length;return{type:"num",value:parseFloat(t),precision:i}}function parseEscapeSequence(){if(test(st))return match1(st);if(test(at)){let[,t,e]=match(at),i=parseInt(t||e,16);return i<=55295||57344<=i?String.fromCodePoint(i):"�"}throw new SyntaxError("Unknown escape sequence")}function parseIndent(){let i=e;consumeToken(wt);switch(t[e]){case".":case"[":case"*":case"}":case void 0:return!1;case"{":return makeIndent(t.slice(i,e))}return" "===t[e-1]&&makeIndent(t.slice(i,e))}function trim(t,e){return t.replace(e,"")}function makeIndent(t){let e=t.replace(lt,"\n"),i=ht.exec(t)[1].length;return new Indent(e,i)}}}class Indent{constructor(t,e){this.value=t;this.length=e}}const vt=/<|&#?\w+;/,yt={"http://www.w3.org/1999/xhtml":["em","strong","small","s","cite","q","dfn","abbr","data","time","code","var","samp","kbd","sub","sup","i","b","u","mark","bdi","bdo","span","br","wbr"]},At={"http://www.w3.org/1999/xhtml":{global:["title","aria-label","aria-valuetext"],a:["download"],area:["download","alt"],input:["alt","placeholder"],menuitem:["label"],menu:["label"],optgroup:["label"],option:["label"],track:["label"],img:["alt"],textarea:["placeholder"],th:["abbr"]},"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul":{global:["accesskey","aria-label","aria-valuetext","label","title","tooltiptext"],description:["value"],key:["key","keycode"],label:["value"],textbox:["placeholder","value"]}};function translateElement(t,e){const{value:i}=e;if("string"==typeof i)if("title"===t.localName&&"http://www.w3.org/1999/xhtml"===t.namespaceURI)t.textContent=i;else if(vt.test(i)){const e=t.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","template");e.innerHTML=i;!function overlayChildNodes(t,e){for(const i of t.childNodes)if(i.nodeType!==i.TEXT_NODE)if(i.hasAttribute("data-l10n-name")){const n=getNodeForNamedElement(e,i);t.replaceChild(n,i)}else if(isElementAllowed(i)){const e=createSanitizedElement(i);t.replaceChild(e,i)}else{console.warn(`An element of forbidden type "${i.localName}" was found in the translation. Only safe text-level elements and elements with data-l10n-name are allowed.`);t.replaceChild(createTextNodeFromTextContent(i),i)}e.textContent="";e.appendChild(t)}(e.content,t)}else t.textContent=i;overlayAttributes(e,t)}function hasAttribute(t,e){if(!t)return!1;for(let i of t)if(i.name===e)return!0;return!1}function overlayAttributes(t,e){const i=e.hasAttribute("data-l10n-attrs")?e.getAttribute("data-l10n-attrs").split(",").map((t=>t.trim())):null;for(const n of Array.from(e.attributes))isAttrNameLocalizable(n.name,e,i)&&!hasAttribute(t.attributes,n.name)&&e.removeAttribute(n.name);if(t.attributes)for(const n of Array.from(t.attributes))isAttrNameLocalizable(n.name,e,i)&&e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function getNodeForNamedElement(t,e){const i=e.getAttribute("data-l10n-name"),n=t.querySelector(`[data-l10n-name="${i}"]`);if(!n){console.warn(`An element named "${i}" wasn't found in the source.`);return createTextNodeFromTextContent(e)}if(n.localName!==e.localName){console.warn(`An element named "${i}" was found in the translation but its type ${e.localName} didn't match the element found in the source (${n.localName}).`);return createTextNodeFromTextContent(e)}t.removeChild(n);return shallowPopulateUsing(e,n.cloneNode(!1))}function createSanitizedElement(t){const e=t.ownerDocument.createElement(t.localName);return shallowPopulateUsing(t,e)}function createTextNodeFromTextContent(t){return t.ownerDocument.createTextNode(t.textContent)}function isElementAllowed(t){const e=yt[t.namespaceURI];return e&&e.includes(t.localName)}function isAttrNameLocalizable(t,e,i=null){if(i&&i.includes(t))return!0;const n=At[e.namespaceURI];if(!n)return!1;const s=t.toLowerCase(),a=e.localName;if(n.global.includes(s))return!0;if(!n[a])return!1;if(n[a].includes(s))return!0;if("http://www.w3.org/1999/xhtml"===e.namespaceURI&&"input"===a&&"value"===s){const t=e.type.toLowerCase();if("submit"===t||"button"===t||"reset"===t)return!0}return!1}function shallowPopulateUsing(t,e){e.textContent=t.textContent;overlayAttributes(t,e);return e}class CachedIterable extends Array{static from(t){return t instanceof this?t:new this(t)}}Symbol.iterator;class CachedAsyncIterable extends CachedIterable{constructor(t){super();if(Symbol.asyncIterator in Object(t))this.iterator=t[Symbol.asyncIterator]();else{if(!(Symbol.iterator in Object(t)))throw new TypeError("Argument must implement the iteration protocol.");this.iterator=t[Symbol.iterator]()}}[Symbol.asyncIterator](){const t=this;let e=0;return{async next(){t.length<=e&&t.push(t.iterator.next());return t[e++]}}}async touchNext(t=1){let e=0;for(;e++<t;){const t=this[this.length-1];if(t&&(await t).done)break;this.push(this.iterator.next())}return this[this.length-1]}}class Localization{constructor(t=[],e){this.resourceIds=t;this.generateBundles=e;this.onChange(!0)}addResourceIds(t,e=!1){this.resourceIds.push(...t);this.onChange(e);return this.resourceIds.length}removeResourceIds(t){this.resourceIds=this.resourceIds.filter((e=>!t.includes(e)));this.onChange();return this.resourceIds.length}async formatWithFallback(t,e){const i=[];let n=!1;for await(const s of this.bundles){n=!0;const a=keysFromBundle(e,s,t,i);if(0===a.size)break;if("undefined"!=typeof console){const t=s.locales[0],e=Array.from(a).join(", ");console.warn(`[fluent] Missing translations in ${t}: ${e}`)}}n||"undefined"==typeof console||console.warn(`[fluent] Request for keys failed because no resource bundles got generated.\n keys: ${JSON.stringify(t)}.\n resourceIds: ${JSON.stringify(this.resourceIds)}.`);return i}formatMessages(t){return this.formatWithFallback(t,messageFromBundle)}formatValues(t){return this.formatWithFallback(t,valueFromBundle)}async formatValue(t,e){const[i]=await this.formatValues([{id:t,args:e}]);return i}handleEvent(){this.onChange()}onChange(t=!1){this.bundles=CachedAsyncIterable.from(this.generateBundles(this.resourceIds));t&&this.bundles.touchNext(2)}}function valueFromBundle(t,e,i,n){return i.value?t.formatPattern(i.value,n,e):null}function messageFromBundle(t,e,i,n){const s={value:null,attributes:null};i.value&&(s.value=t.formatPattern(i.value,n,e));let a=Object.keys(i.attributes);if(a.length>0){s.attributes=new Array(a.length);for(let[r,o]of a.entries()){let a=t.formatPattern(i.attributes[o],n,e);s.attributes[r]={name:o,value:a}}}return s}function keysFromBundle(t,e,i,n){const s=[],a=new Set;i.forEach((({id:i,args:r},o)=>{if(void 0!==n[o])return;let l=e.getMessage(i);if(l){s.length=0;n[o]=t(e,s,l,r);if(s.length>0&&"undefined"!=typeof console){const t=e.locales[0],n=s.join(", ");console.warn(`[fluent][resolver] errors in ${t}/${i}: ${n}.`)}}else a.add(i)}));return a}const xt="data-l10n-id",Et="data-l10n-args",St=`[${xt}]`;class DOMLocalization extends Localization{constructor(t,e){super(t,e);this.roots=new Set;this.pendingrAF=null;this.pendingElements=new Set;this.windowElement=null;this.mutationObserver=null;this.observerConfig={attributes:!0,characterData:!1,childList:!0,subtree:!0,attributeFilter:[xt,Et]}}onChange(t=!1){super.onChange(t);this.roots&&this.translateRoots()}setAttributes(t,e,i){t.setAttribute(xt,e);i?t.setAttribute(Et,JSON.stringify(i)):t.removeAttribute(Et);return t}getAttributes(t){return{id:t.getAttribute(xt),args:JSON.parse(t.getAttribute(Et)||null)}}connectRoot(t){for(const e of this.roots)if(e===t||e.contains(t)||t.contains(e))throw new Error("Cannot add a root that overlaps with existing root.");if(this.windowElement){if(this.windowElement!==t.ownerDocument.defaultView)throw new Error("Cannot connect a root:\n DOMLocalization already has a root from a different window.")}else{this.windowElement=t.ownerDocument.defaultView;this.mutationObserver=new this.windowElement.MutationObserver((t=>this.translateMutations(t)))}this.roots.add(t);this.mutationObserver.observe(t,this.observerConfig)}disconnectRoot(t){this.roots.delete(t);this.pauseObserving();if(0===this.roots.size){this.mutationObserver=null;this.windowElement&&this.pendingrAF&&this.windowElement.cancelAnimationFrame(this.pendingrAF);this.windowElement=null;this.pendingrAF=null;this.pendingElements.clear();return!0}this.resumeObserving();return!1}translateRoots(){const t=Array.from(this.roots);return Promise.all(t.map((t=>this.translateFragment(t))))}pauseObserving(){if(this.mutationObserver){this.translateMutations(this.mutationObserver.takeRecords());this.mutationObserver.disconnect()}}resumeObserving(){if(this.mutationObserver)for(const t of this.roots)this.mutationObserver.observe(t,this.observerConfig)}translateMutations(t){for(const e of t)switch(e.type){case"attributes":e.target.hasAttribute("data-l10n-id")&&this.pendingElements.add(e.target);break;case"childList":for(const t of e.addedNodes)if(t.nodeType===t.ELEMENT_NODE)if(t.childElementCount)for(const e of this.getTranslatables(t))this.pendingElements.add(e);else t.hasAttribute(xt)&&this.pendingElements.add(t)}this.pendingElements.size>0&&null===this.pendingrAF&&(this.pendingrAF=this.windowElement.requestAnimationFrame((()=>{this.translateElements(Array.from(this.pendingElements));this.pendingElements.clear();this.pendingrAF=null})))}translateFragment(t){return this.translateElements(this.getTranslatables(t))}async translateElements(t){if(!t.length)return;const e=t.map(this.getKeysForElement),i=await this.formatMessages(e);return this.applyTranslations(t,i)}applyTranslations(t,e){this.pauseObserving();for(let i=0;i<t.length;i++)void 0!==e[i]&&translateElement(t[i],e[i]);this.resumeObserving()}getTranslatables(t){const e=Array.from(t.querySelectorAll(St));"function"==typeof t.hasAttribute&&t.hasAttribute(xt)&&e.push(t);return e}getKeysForElement(t){return{id:t.getAttribute(xt),args:JSON.parse(t.getAttribute(Et)||null)}}}class L10n{#Ro;#es;#Yi;#No;constructor({lang:t,isRTL:e},i=null){this.#Yi=L10n.#Bo(t);this.#No=i;this.#Ro=e??L10n.#Oo(this.#Yi)?"rtl":"ltr"}_setL10n(t){this.#No=t}getLanguage(){return this.#Yi}getDirection(){return this.#Ro}async get(t,e=null,i){if(Array.isArray(t)){t=t.map((t=>({id:t})));return(await this.#No.formatMessages(t)).map((t=>t.value))}const n=await this.#No.formatMessages([{id:t,args:e}]);return n[0]?.value||i}async translate(t){(this.#es||=new Set).add(t);try{this.#No.connectRoot(t)}catch{}await this.#No.translateRoots()}async translateOnce(t){try{await this.#No.translateElements([t])}catch(t){console.error("translateOnce:",t)}}async destroy(){if(this.#es){for(const t of this.#es)this.#No.disconnectRoot(t);this.#es.clear();this.#es=null}this.#No.pauseObserving()}pause(){this.#No.pauseObserving()}resume(){this.#No.resumeObserving()}static#Bo(t){return{en:"en-us",es:"es-es",fy:"fy-nl",ga:"ga-ie",gu:"gu-in",hi:"hi-in",hy:"hy-am",nb:"nb-no",ne:"ne-np",nn:"nn-no",pa:"pa-in",pt:"pt-pt",sv:"sv-se",zh:"zh-cn"}[t=t?.toLowerCase()||"en-us"]||t}static#Oo(t){const e=t.split("-",1)[0];return["ar","he","fa","ps","ur"].includes(e)}}function createBundle(t,e){const i=new FluentResource(e),n=new FluentBundle(t),s=n.addResource(i);s.length&&console.error("L10n errors",s);return n}class genericl10n_GenericL10n extends L10n{constructor(t){super({lang:t});const e=t?genericl10n_GenericL10n.#Vo.bind(genericl10n_GenericL10n,"en-us",this.getLanguage()):genericl10n_GenericL10n.#Ho.bind(genericl10n_GenericL10n,this.getLanguage());this._setL10n(new DOMLocalization([],e))}static async*#Vo(t,e){const{baseURL:i,paths:n}=await this.#zo(),s=[e];if(t!==e){const i=e.split("-",1)[0];i!==e&&s.push(i);s.push(t)}for(const t of s){const e=await this.#Uo(t,i,n);e?yield e:"en-us"===t&&(yield this.#jo(t))}}static async#Uo(t,e,i){const n=i[t];if(!n)return null;const s=new URL(n,e);return createBundle(t,await(0,j.fetchData)(s,"text"))}static async#zo(){try{const{href:t}=document.querySelector('link[type="application/l10n"]'),e=await(0,j.fetchData)(t,"json");return{baseURL:t.replace(/[^/]*$/,"")||"./",paths:e}}catch{}return{baseURL:"./",paths:Object.create(null)}}static async*#Ho(t){yield this.#jo(t)}static async#jo(t){return createBundle(t,'pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties…\npdfjs-document-properties-button-label = Document Properties…\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: "short", timeStyle: "medium") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } × { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } × { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing…\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document…\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: "short", timeStyle: "medium") }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing…\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can’t see the image or when it doesn’t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, “A young man sits down at a table to eat a meal”\npdfjs-editor-resizer-top-left =\n .aria-label = Top left corner — resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle — resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner — resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right — resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner — resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle — resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner — resize\npdfjs-editor-resizer-middle-left =\n .aria-label = Middle left — resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here…\npdfjs-editor-new-alt-text-description = Short description for people who can’t see the image or when the image doesn’t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn’t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can’t see the image or when the image doesn’t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading…\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close')}}class GenericScripting{constructor(t){"Function"===t?.constructor?.name&&(t=t());this._ready=new Promise(((e,i)=>{import(t).then((t=>{e(t.QuickJSSandbox())})).catch(i)}))}async createSandbox(t){(await this._ready).create(t)}async dispatchEventInSandbox(t){const e=await this._ready;setTimeout((()=>e.dispatchEvent(t)),0)}async destroySandbox(){(await this._ready).nukeSandbox()}}class ExternalServices extends BaseExternalServices{async createL10n(){return new genericl10n_GenericL10n(AppOptions.get("localeProperties")?.lang)}createScripting(){return new GenericScripting(AppOptions.get("sandboxBundleSrc"))}}class NewAltTextManager{#Wo=this.#$o.bind(this);#Go;#qo=null;#Xo;#Ko;#Yo;#Zo;#Qo;#Jo;#Ma;#tl=!1;#el;#il=null;#Ut=null;#nl;#sl;#al=!1;#rl=!1;#ol;#ll;#hl;#dl;#cl;#Ce;#ul=null;constructor({descriptionContainer:t,dialog:e,imagePreview:i,cancelButton:n,disclaimer:s,notNowButton:a,saveButton:r,textarea:o,learnMore:l,errorCloseButton:h,createAutomaticallyButton:d,downloadModel:c,downloadModelDescription:u,title:p},g,m){this.#Xo=n;this.#Go=d;this.#Ko=t;this.#Yo=e;this.#Zo=s;this.#ll=a;this.#nl=i;this.#dl=o;this.#ol=l;this.#cl=p;this.#Qo=c;this.#Jo=u;this.#hl=g;this.#Ma=m;e.addEventListener("close",this.#pl.bind(this));e.addEventListener("contextmenu",(t=>{t.target!==this.#dl&&t.preventDefault()}));n.addEventListener("click",this.#Wo);a.addEventListener("click",this.#Wo);r.addEventListener("click",this.#gl.bind(this));h.addEventListener("click",(()=>{this.#ml(!1)}));d.addEventListener("click",(async()=>{const t="true"!==d.getAttribute("aria-pressed");this.#qo._reportTelemetry({action:"pdfjs.image.alt_text.ai_generation_check",data:{status:t}});if(this.#Ce){this.#Ce.setPreference("enableGuessAltText",t);await this.#Ce.mlManager.toggleService("altText",t)}this.#fl(t,!1)}));o.addEventListener("focus",(()=>{this.#rl=this.#al;this.#bl(!1);this.#wl()}));o.addEventListener("blur",(()=>{o.value||this.#bl(this.#rl);this.#wl()}));o.addEventListener("input",(()=>{this.#wl()}));m._on("enableguessalttext",(({value:t})=>{this.#fl(t,!1)}));this.#hl.register(e);this.#ol.addEventListener("click",(()=>{this.#qo._reportTelemetry({action:"pdfjs.image.alt_text.info",data:{topic:"alt_text"}})}))}#bl(t){if(this.#Ce&&this.#al!==t){this.#al=t;this.#Ko.classList.toggle("loading",t)}}#ml(t){this.#Ce&&this.#Yo.classList.toggle("error",t)}async#fl(t,e=!1){if(this.#Ce){this.#Yo.classList.toggle("aiDisabled",!t);this.#Go.setAttribute("aria-pressed",t);if(t){const{altTextLearnMoreUrl:t}=this.#Ce.mlManager;t&&(this.#ol.href=t);this.#vl(e)}else{this.#bl(!1);this.#al=!1;this.#wl()}}}#yl(){this.#ll.classList.toggle("hidden",!this.#tl);this.#Xo.classList.toggle("hidden",this.#tl)}#Al(t){if(this.#Ce&&this.#il!==t){this.#il=t;this.#Yo.classList.toggle("noAi",!t);this.#wl()}}#wl(){const t=this.#al||this.#el&&this.#el===this.#dl.value;this.#Zo.hidden=!t;const e=this.#al||!!this.#dl.value;if(this.#Ut!==e){this.#Ut=e;this.#cl.setAttribute("data-l10n-id",e?"pdfjs-editor-new-alt-text-dialog-edit-label":"pdfjs-editor-new-alt-text-dialog-add-label")}}async#vl(t){if(this.#al)return;if(this.#dl.value)return;if(t&&null!==this.#ul)return;this.#el=this.#qo.guessedAltText;if(null===this.#ul&&this.#el){this.#xl(this.#el);return}this.#bl(!0);this.#wl();let e=!1;try{const t=await this.#qo.mlGuessAltText(this.#sl,!1);if(t){this.#el=t;this.#rl=this.#al;this.#al&&this.#xl(t)}}catch(t){console.error(t);e=!0}this.#bl(!1);this.#wl();e&&this.#Ce&&this.#ml(!0)}#xl(t){if(this.#Ce&&!this.#dl.value){this.#dl.value=t;this.#wl()}}#El(){this.#Qo.classList.toggle("hidden",!1);const callback=async({detail:{finished:t,total:e,totalLoaded:i}})=>{const n=1e6;i=Math.min(.99*e,i);const s=this.#Jo.ariaValueMax=Math.round(e/n),a=this.#Jo.ariaValueNow=Math.round(i/n);this.#Jo.setAttribute("data-l10n-args",JSON.stringify({totalSize:s,downloadedSize:a}));if(!t)return;this.#Ma._off("loadaiengineprogress",callback);this.#Qo.classList.toggle("hidden",!0);this.#Al(!0);if(!this.#Ce)return;const{mlManager:r}=this.#Ce;r.toggleService("altText",!0);this.#fl(await r.isEnabledFor("altText"),!0)};this.#Ma._on("loadaiengineprogress",callback)}async editAltText(t,e,i){if(this.#qo||!e)return;if(i&&e.hasAltTextData()){e.altTextFinish();return}this.#tl=i;let{mlManager:n}=t,s=!!n;this.#wl();if(n&&!n.isReady("altText")){s=!1;n.hasProgress?this.#El():n=null}else this.#Qo.classList.toggle("hidden",!0);const a=n?.isEnabledFor("altText");this.#qo=e;this.#Ce=t;this.#Ce.removeEditListeners();({altText:this.#ul}=e.altTextData);this.#dl.value=this.#ul??"";let r,o,l;if(n){({canvas:r,width:o,height:l,imageData:this.#sl}=e.copyCanvas(224,180,!0));s&&this.#fl(await a,!0)}else({canvas:r,width:o,height:l}=e.copyCanvas(224,180,!1));r.setAttribute("role","presentation");const{style:h}=r;h.width=`${o}px`;h.height=`${l}px`;this.#nl.append(r);this.#yl();this.#Al(s);this.#ml(!1);try{await this.#hl.open(this.#Yo)}catch(t){this.#pl();throw t}}#$o(){this.#qo.altTextData={cancel:!0};const t=this.#dl.value.trim();this.#qo._reportTelemetry({action:"pdfjs.image.alt_text.dismiss",data:{alt_text_type:t?"present":"empty",flow:this.#tl?"image_add":"alt_text_edit"}});this.#qo._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!0,alt_text_type:"skipped"}});this.#Sl()}#Sl(){this.#hl.active===this.#Yo&&this.#hl.close(this.#Yo)}#pl(){const t=this.#nl.firstChild;t.remove();t.width=t.height=0;this.#sl=null;this.#bl(!1);this.#Ce?.addEditListeners();this.#qo.altTextFinish();this.#Ce?.setSelected(this.#qo);this.#qo=null;this.#Ce=null}#Pl(t){return new Set(t.toLowerCase().split(/[^\p{L}\p{N}]+/gu).filter((t=>!!t)))}#gl(){const t=this.#dl.value.trim();this.#qo.altTextData={altText:t,decorative:!1};this.#qo.altTextData.guessedAltText=this.#el;if(this.#el&&this.#el!==t){const e=this.#Pl(this.#el),i=this.#Pl(t);this.#qo._reportTelemetry({action:"pdfjs.image.alt_text.user_edit",data:{total_words:e.size,words_removed:e.difference(i).size,words_added:i.difference(e).size}})}this.#qo._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!0,alt_text_type:t?"present":"empty"}});this.#qo._reportTelemetry({action:"pdfjs.image.alt_text.save",data:{alt_text_type:t?"present":"empty",flow:this.#tl?"image_add":"alt_text_edit"}});this.#Sl()}destroy(){this.#Ce=null;this.#Sl()}}class ImageAltTextSettings{#_l;#Cl;#Tl;#Yo;#Ma;#gi;#hl;#Ml;constructor({dialog:t,createModelButton:e,aiModelSettings:i,learnMore:n,closeButton:s,deleteModelButton:a,downloadModelButton:r,showAltTextDialogButton:o},l,h,d){this.#Yo=t;this.#_l=i;this.#Cl=e;this.#Tl=r;this.#Ml=o;this.#hl=l;this.#Ma=h;this.#gi=d;const{altTextLearnMoreUrl:c}=d;c&&(n.href=c);t.addEventListener("contextmenu",U.noContextMenu);e.addEventListener("click",(async t=>{const e=this.#Il("enableGuessAltText",t);await d.toggleService("altText",e);this.#Dl({type:"stamp",action:"pdfjs.image.alt_text.settings_ai_generation_check",data:{status:e}})}));o.addEventListener("click",(t=>{const e=this.#Il("enableNewAltTextWhenAddingImage",t);this.#Dl({type:"stamp",action:"pdfjs.image.alt_text.settings_edit_alt_text_check",data:{status:e}})}));a.addEventListener("click",this.#Ll.bind(this,!0));r.addEventListener("click",this.#Es.bind(this,!0));s.addEventListener("click",this.#Sl.bind(this));n.addEventListener("click",(()=>{this.#Dl({type:"stamp",action:"pdfjs.image.alt_text.info",data:{topic:"ai_generation"}})}));h._on("enablealttextmodeldownload",(({value:t})=>{t?this.#Es(!1):this.#Ll(!1)}));this.#hl.register(t)}#Dl(t){this.#Ma.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}async#Es(t=!1){if(t){this.#Tl.disabled=!0;const t=this.#Tl.firstChild;t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-settings-downloading-model-button");await this.#gi.downloadModel("altText");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-settings-download-model-button");this.#Cl.disabled=!1;this.#kl("enableGuessAltText",!0);this.#gi.toggleService("altText",!0);this.#kl("enableAltTextModelDownload",!0);this.#Tl.disabled=!1}this.#_l.classList.toggle("download",!1);this.#Cl.setAttribute("aria-pressed",!0)}async#Ll(t=!1){if(t){await this.#gi.deleteModel("altText");this.#kl("enableGuessAltText",!1);this.#kl("enableAltTextModelDownload",!1)}this.#_l.classList.toggle("download",!0);this.#Cl.disabled=!0;this.#Cl.setAttribute("aria-pressed",!1)}async open({enableGuessAltText:t,enableNewAltTextWhenAddingImage:e}){const{enableAltTextModelDownload:i}=this.#gi;this.#Cl.disabled=!i;this.#Cl.setAttribute("aria-pressed",i&&t);this.#Ml.setAttribute("aria-pressed",e);this.#_l.classList.toggle("download",!i);await this.#hl.open(this.#Yo);this.#Dl({type:"stamp",action:"pdfjs.image.alt_text.settings_displayed"})}#Il(t,{target:e}){const i="true"!==e.getAttribute("aria-pressed");this.#kl(t,i);e.setAttribute("aria-pressed",i);return i}#kl(t,e){this.#Ma.dispatch("setpreference",{source:this,name:t,value:e})}#Sl(){this.#hl.active===this.#Yo&&this.#hl.close(this.#Yo)}}class AltTextManager{#so=null;#qo=null;#Xo;#Yo;#Ma;#Fl=!1;#Rl;#Nl;#hl;#Bl;#dl;#Ce;#ul=null;#Ol=null;#Vl=null;#Hl=null;#Ei;#zl=null;constructor({dialog:t,optionDescription:e,optionDecorative:i,textarea:n,cancelButton:s,saveButton:a},r,o,l){this.#Yo=t;this.#Rl=e;this.#Nl=i;this.#dl=n;this.#Xo=s;this.#Bl=a;this.#hl=o;this.#Ma=l;this.#Ei=r;const h=this.#Ul.bind(this);t.addEventListener("close",this.#pl.bind(this));t.addEventListener("contextmenu",(t=>{t.target!==this.#dl&&t.preventDefault()}));s.addEventListener("click",this.#Sl.bind(this));a.addEventListener("click",this.#gl.bind(this));e.addEventListener("change",h);i.addEventListener("change",h);this.#hl.register(t)}#jl(){if(this.#Vl)return;const t=new j.DOMSVGFactory,e=this.#Vl=t.createElement("svg");e.setAttribute("width","0");e.setAttribute("height","0");const i=t.createElement("defs");e.append(i);const n=t.createElement("mask");i.append(n);n.setAttribute("id","alttext-manager-mask");n.setAttribute("maskContentUnits","objectBoundingBox");let s=t.createElement("rect");n.append(s);s.setAttribute("fill","white");s.setAttribute("width","1");s.setAttribute("height","1");s.setAttribute("x","0");s.setAttribute("y","0");s=this.#Hl=t.createElement("rect");n.append(s);s.setAttribute("fill","black");this.#Yo.append(e)}async editAltText(t,e){if(this.#qo||!e)return;this.#jl();this.#Fl=!1;this.#so=new AbortController;const i={signal:this.#so.signal},n=this.#Wl.bind(this);for(const t of[this.#Rl,this.#Nl,this.#dl,this.#Bl,this.#Xo])t.addEventListener("click",n,i);const{altText:s,decorative:a}=e.altTextData;if(!0===a){this.#Nl.checked=!0;this.#Rl.checked=!1}else{this.#Nl.checked=!1;this.#Rl.checked=!0}this.#ul=this.#dl.value=s?.trim()||"";this.#Ul();this.#qo=e;this.#Ce=t;this.#Ce.removeEditListeners();this.#Ol=new AbortController;this.#Ma._on("resize",this.#gs.bind(this),{signal:this.#Ol.signal});try{await this.#hl.open(this.#Yo);this.#gs()}catch(t){this.#pl();throw t}}#gs(){if(!this.#qo)return;const t=this.#Yo,{style:e}=t,{x:i,y:n,width:s,height:a}=this.#Ei.getBoundingClientRect(),{innerWidth:r,innerHeight:o}=window,{width:l,height:h}=t.getBoundingClientRect(),{x:d,y:c,width:u,height:p}=this.#qo.getClientDimensions(),g=10,m="ltr"===this.#Ce.direction,f=Math.max(d,i),b=Math.min(d+u,i+s),w=Math.max(c,n),v=Math.min(c+p,n+a);this.#Hl.setAttribute("width",""+(b-f)/r);this.#Hl.setAttribute("height",""+(v-w)/o);this.#Hl.setAttribute("x",""+f/r);this.#Hl.setAttribute("y",""+w/o);let y=null,A=Math.max(c,0);A+=Math.min(o-(A+h),0);m?d+u+g+l<r?y=d+u+g:d>l+g&&(y=d-l-g):d>l+g?y=d-l-g:d+u+g+l<r&&(y=d+u+g);if(null===y){A=null;y=Math.max(d,0);y+=Math.min(r-(y+l),0);c>h+g?A=c-h-g:c+p+g+h<o&&(A=c+p+g)}if(null!==A){t.classList.add("positioned");m?e.left=`${y}px`:e.right=r-y-l+"px";e.top=`${A}px`}else{t.classList.remove("positioned");e.left="";e.top=""}}#Sl(){this.#hl.active===this.#Yo&&this.#hl.close(this.#Yo)}#pl(){this.#qo._reportTelemetry(this.#zl||{action:"alt_text_cancel",alt_text_keyboard:!this.#Fl});this.#zl=null;this.#$l();this.#Ce?.addEditListeners();this.#Ol?.abort();this.#Ol=null;this.#qo.altTextFinish();this.#qo=null;this.#Ce=null}#Ul(){this.#dl.disabled=this.#Nl.checked}#gl(){const t=this.#dl.value.trim(),e=this.#Nl.checked;this.#qo.altTextData={altText:t,decorative:e};this.#zl={action:"alt_text_save",alt_text_description:!!t,alt_text_edit:!!this.#ul&&this.#ul!==t,alt_text_decorative:e,alt_text_keyboard:!this.#Fl};this.#Sl()}#Wl(t){if(0!==t.detail){this.#Fl=!0;this.#$l()}}#$l(){this.#so?.abort();this.#so=null}destroy(){this.#Ce=null;this.#Sl();this.#Vl?.remove();this.#Vl=this.#Hl=null}}class AnnotationEditorParams{constructor(t,e){this.eventBus=e;this.#Gl(t)}#Gl({editorFreeTextFontSize:t,editorFreeTextColor:e,editorInkColor:i,editorInkThickness:n,editorInkOpacity:s,editorStampAddImage:a,editorFreeHighlightThickness:r,editorHighlightShowAll:o}){const dispatchEvent=(t,e)=>{this.eventBus.dispatch("switchannotationeditorparams",{source:this,type:V.AnnotationEditorParamsType[t],value:e})};t.addEventListener("input",(function(){dispatchEvent("FREETEXT_SIZE",this.valueAsNumber)}));e.addEventListener("input",(function(){dispatchEvent("FREETEXT_COLOR",this.value)}));i.addEventListener("input",(function(){dispatchEvent("INK_COLOR",this.value)}));n.addEventListener("input",(function(){dispatchEvent("INK_THICKNESS",this.valueAsNumber)}));s.addEventListener("input",(function(){dispatchEvent("INK_OPACITY",this.valueAsNumber)}));a.addEventListener("click",(()=>{this.eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{action:"pdfjs.image.add_image_click"}}});dispatchEvent("CREATE")}));r.addEventListener("input",(function(){dispatchEvent("HIGHLIGHT_THICKNESS",this.valueAsNumber)}));o.addEventListener("click",(function(){const t="true"===this.getAttribute("aria-pressed");this.setAttribute("aria-pressed",!t);dispatchEvent("HIGHLIGHT_SHOW_ALL",!t)}));this.eventBus._on("annotationeditorparamschanged",(a=>{for(const[l,h]of a.details)switch(l){case V.AnnotationEditorParamsType.FREETEXT_SIZE:t.value=h;break;case V.AnnotationEditorParamsType.FREETEXT_COLOR:e.value=h;break;case V.AnnotationEditorParamsType.INK_COLOR:i.value=h;break;case V.AnnotationEditorParamsType.INK_THICKNESS:n.value=h;break;case V.AnnotationEditorParamsType.INK_OPACITY:s.value=h;break;case V.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:r.value=h;break;case V.AnnotationEditorParamsType.HIGHLIGHT_FREE:r.disabled=!h;break;case V.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:o.setAttribute("aria-pressed",h)}}))}}const Pt=.1;class CaretBrowsingMode{#ql;#Xl=0;#Kl;constructor(t,e,i,n){this.#ql=e;this.#Kl=i;if(!n)return;this.#Xl=n.getBoundingClientRect().height;const s=new ResizeObserver((t=>{for(const e of t)if(e.target===n){this.#Xl=Math.floor(e.borderBoxSize[0].blockSize);break}}));s.observe(n);t.addEventListener("abort",(()=>s.disconnect()),{once:!0})}#Yl(t,e){const i=t.y,n=t.bottom,s=t.y+t.height/2,a=e.y,r=e.bottom,o=e.y+e.height/2;return i<=o&&o<=n||a<=s&&s<=r}#Zl(t,e,i,n){const s=t.y+t.height/2;return(n?i>=s:i<=s)&&t.x-Pt<=e&&e<=t.right+Pt}#Ql(t){return t.top>=this.#Xl&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}#Jl(t,e){const{focusNode:i,focusOffset:n}=t,s=document.createRange();s.setStart(i,n);s.setEnd(i,n);const a=s.getBoundingClientRect();return[a.x,e?a.top:a.bottom]}static#th(t,e){if(!document.caretPositionFromPoint){const{startContainer:i,startOffset:n}=document.caretRangeFromPoint(t,e);return{offsetNode:i,offset:n}}return document.caretPositionFromPoint(t,e)}#eh(t,e,i,n,s){s||=n.getBoundingClientRect();if(e<=s.x+Pt){i?t.extend(n.firstChild,0):t.setPosition(n.firstChild,0);return}if(s.right-Pt<=e){const{lastChild:e}=n;i?t.extend(e,e.length):t.setPosition(e,e.length);return}const a=s.y+s.height/2;let r=CaretBrowsingMode.#th(e,a),o=r.offsetNode?.parentElement;if(o&&o!==n){const t=document.elementsFromPoint(e,a),i=[];for(const e of t){if(e===n)break;const{style:t}=e;i.push([e,t.visibility]);t.visibility="hidden"}r=CaretBrowsingMode.#th(e,a);o=r.offsetNode?.parentElement;for(const[t,e]of i)t.style.visibility=e}o===n?i?t.extend(r.offsetNode,r.offset):t.setPosition(r.offsetNode,r.offset):i?t.extend(n.firstChild,0):t.setPosition(n.firstChild,0)}#ih(t,e,i,n,s){if(this.#Ql(n))this.#eh(e,s,t,i,n);else{this.#ql.addEventListener("scrollend",this.#eh.bind(this,e,s,t,i,null),{once:!0});i.scrollIntoView()}}#nh(t,e){for(;;){const i=t.closest(".page"),n=parseInt(i.getAttribute("data-page-number")),s=e?n-1:n+1;if(!(t=this.#Kl.querySelector(`.page[data-page-number="${s}"] .textLayer`)))return null;const a=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),r=e?a.lastChild():a.firstChild();if(r)return r}}moveCaret(t,e){const i=document.getSelection();if(0===i.rangeCount)return;const{focusNode:n}=i,s=n.nodeType!==Node.ELEMENT_NODE?n.parentElement:n,a=s.closest(".textLayer");if(!a)return;const r=document.createTreeWalker(a,NodeFilter.SHOW_TEXT);r.currentNode=n;const o=s.getBoundingClientRect();let l=null;const h=(t?r.previousSibling:r.nextSibling).bind(r);for(;h();){const t=r.currentNode.parentElement;if(!this.#Yl(o,t.getBoundingClientRect())){l=t;break}}if(!l){const s=this.#nh(a,t);if(!s)return;if(e){const e=(t?r.firstChild():r.lastChild())||n;i.extend(e,t?0:e.length);const a=document.createRange();a.setStart(s,t?s.length:0);a.setEnd(s,t?s.length:0);i.addRange(a);return}const[o]=this.#Jl(i,t),{parentElement:l}=s;this.#ih(e,i,l,l.getBoundingClientRect(),o);return}const[d,c]=this.#Jl(i,t),u=l.getBoundingClientRect();if(this.#Zl(u,d,c,t))this.#ih(e,i,l,u,d);else{for(;h();){const n=r.currentNode.parentElement,s=n.getBoundingClientRect();if(!this.#Yl(u,s))break;if(this.#Zl(s,d,c,t)){this.#ih(e,i,n,s,d);return}}this.#ih(e,i,l,u,d)}}}function download(t,e){const i=document.createElement("a");if(!i.click)throw new Error('DownloadManager: "a.click()" is not supported.');i.href=t;i.target="_parent";"download"in i&&(i.download=e);(document.body||document.documentElement).append(i);i.click();i.remove()}class DownloadManager{#sh=new WeakMap;downloadData(t,e,i){download(URL.createObjectURL(new Blob([t],{type:i})),e)}openOrDownloadData(t,e,i=null){const s=(0,U.isPdfFile)(e),a=s?"application/pdf":"";if(s){let e=this.#sh.get(t);if(!e){e=URL.createObjectURL(new Blob([t],{type:a}));this.#sh.set(t,e)}try{window.open(e);return!0}catch(i){n.NgxConsole.error("openOrDownloadData:",i);URL.revokeObjectURL(e);this.#sh.delete(t)}}this.downloadData(t,e,a);return!1}download(t,e,i){let n;if(t)n=URL.createObjectURL(new Blob([t],{type:"application/pdf"}));else{if(!(0,V.createValidAbsoluteUrl)(e,"http://example.com")){console.error(`download - not a valid URL: ${e}`);return}n=e+"#pdfjs.action=download"}download(n,i)}}class EditorUndoBar{#ah=null;#Ei;#Ma=null;#rh=null;#oh=null;isOpen=!1;#lh;#hh=null;#dh;static#ch=Object.freeze({highlight:"pdfjs-editor-undo-bar-message-highlight",freetext:"pdfjs-editor-undo-bar-message-freetext",stamp:"pdfjs-editor-undo-bar-message-stamp",ink:"pdfjs-editor-undo-bar-message-ink",_multiple:"pdfjs-editor-undo-bar-message-multiple"});constructor({container:t,message:e,undoButton:i,closeButton:n},s){this.#Ei=t;this.#lh=e;this.#dh=i;this.#ah=n;this.#Ma=s}destroy(){this.#oh?.abort();this.#oh=null;this.hide()}show(t,e){if(!this.#oh){this.#oh=new AbortController;const t={signal:this.#oh.signal},e=this.hide.bind(this);this.#Ei.addEventListener("contextmenu",U.noContextMenu,t);this.#ah.addEventListener("click",e,t);this.#Ma._on("beforeprint",e,t);this.#Ma._on("download",e,t)}this.hide();if("string"==typeof e)this.#lh.setAttribute("data-l10n-id",EditorUndoBar.#ch[e]);else{this.#lh.setAttribute("data-l10n-id",EditorUndoBar.#ch._multiple);this.#lh.setAttribute("data-l10n-args",JSON.stringify({count:e}))}this.isOpen=!0;this.#Ei.hidden=!1;this.#hh=new AbortController;this.#dh.addEventListener("click",(()=>{t();this.hide()}),{signal:this.#hh.signal});this.#rh=setTimeout((()=>{this.#Ei.focus();this.#rh=null}),100)}hide(){if(this.isOpen){this.isOpen=!1;this.#Ei.hidden=!0;this.#hh?.abort();this.#hh=null;if(this.#rh){clearTimeout(this.#rh);this.#rh=null}}}}class OverlayManager{#uh=new WeakMap;#ph=null;get active(){return this.#ph}async register(t,e=!1){if("object"!=typeof t)throw new Error("Not enough parameters.");if(this.#uh.has(t))throw new Error("The overlay is already registered.");this.#uh.set(t,{canForceClose:e});t.addEventListener("cancel",(t=>{this.#ph=null}))}unregister(t){if(!this.#uh.has(t))throw new Error("The overlay does not exist.");this.#uh.delete(t)}async open(t){if(!this.#uh.has(t))throw new Error("The overlay does not exist.");if(this.#ph){if(this.#ph===t)throw new Error("The overlay is already active.");if(!this.#uh.get(t).canForceClose)throw new Error("Another overlay is currently active.");await this.close()}this.#ph=t;t.showModal();t.classList.remove("hidden")}async close(t=this.#ph,e=!1){if(!this.#uh.has(t)){if(e)return;throw new Error("The overlay does not exist.")}if(!this.#ph){if(e)return;throw new Error("The overlay is currently not active.")}if(this.#ph!==t){if(e)return;throw new Error("Another overlay is currently active.")}t.close();this.#ph=null}}class PasswordPrompt{#gh=null;#mh=null;#fh=null;constructor(t,e,i=!1){this.dialog=t.dialog;this.label=t.label;this.input=t.input;this.submitButton=t.submitButton;this.cancelButton=t.cancelButton;this.overlayManager=e;this._isViewerEmbedded=i;this.submitButton.addEventListener("click",this.#bh.bind(this));this.cancelButton.addEventListener("click",this.close.bind(this));this.input.addEventListener("keydown",(t=>{13===t.keyCode&&this.#bh()}));this.overlayManager.register(this.dialog,!0);this.dialog.addEventListener("close",this.#$o.bind(this))}async open(){await(this.#gh?.promise);this.#gh=Promise.withResolvers();try{await this.overlayManager.open(this.dialog);this.input.type="password";this.input.focus()}catch(t){this.#gh.resolve();throw t}const t=this.#fh===V.PasswordResponses.INCORRECT_PASSWORD;this._isViewerEmbedded&&!t||this.input.focus();this.label.setAttribute("data-l10n-id",t?"pdfjs-password-invalid":"pdfjs-password-label")}async close(){if(this.overlayManager.active===this.dialog){this.overlayManager.close(this.dialog);this.input.value="";this.input.type="text"}}#bh(){const t=this.input.value;t?.length>0&&this.#wh(t)}#$o(){this.#wh(new Error("PasswordPrompt cancelled."));this.#gh.resolve()}#wh(t){if(this.#mh){this.close();this.input.value="";this.#mh(t);this.#mh=null}}async setUpdateCallback(t,e){this.#gh&&await this.#gh.promise;this.#mh=t;this.#fh=e}}const _t="selected";class BaseTreeViewer{constructor(t){this.container=t.container;this.eventBus=t.eventBus;this._l10n=t.l10n;this.reset()}reset(){this._pdfDocument=null;this._lastToggleIsShow=!0;this._currentTreeItem=null;this.container.textContent="";this.container.classList.remove("treeWithDeepNesting")}_dispatchEvent(t){throw new Error("Not implemented: _dispatchEvent")}_bindLink(t,e){throw new Error("Not implemented: _bindLink")}_normalizeTextContent(t){return removeNullCharacters(t,!0)||"–"}_addToggleButton(t,e=!1){const i=document.createElement("div");i.className="treeItemToggler";e&&i.classList.add("treeItemsHidden");i.onclick=e=>{e.stopPropagation();i.classList.toggle("treeItemsHidden");if(e.shiftKey){const e=!i.classList.contains("treeItemsHidden");this._toggleTreeItem(t,e)}};t.prepend(i)}_toggleTreeItem(t,e=!1){this._l10n.pause();this._lastToggleIsShow=e;for(const i of t.querySelectorAll(".treeItemToggler"))i.classList.toggle("treeItemsHidden",!e);this._l10n.resume()}_toggleAllTreeItems(){this._toggleTreeItem(this.container,!this._lastToggleIsShow)}_finishRendering(t,e,i=!1){if(i){this.container.classList.add("treeWithDeepNesting");this._lastToggleIsShow=!t.querySelector(".treeItemsHidden")}this._l10n.pause();this.container.append(t);this._l10n.resume();this._dispatchEvent(e)}render(t){throw new Error("Not implemented: render")}_updateCurrentTreeItem(t=null){if(this._currentTreeItem){this._currentTreeItem.classList.remove(_t);this._currentTreeItem=null}if(t){t.classList.add(_t);this._currentTreeItem=t}}_scrollToCurrentTreeItem(t){if(!t)return;this._l10n.pause();let e=t.parentNode;for(;e&&e!==this.container;){if(e.classList.contains("treeItem")){const t=e.firstElementChild;t?.classList.remove("treeItemsHidden")}e=e.parentNode}this._l10n.resume();this._updateCurrentTreeItem(t);this.container.scrollTo(t.offsetLeft,t.offsetTop+-100)}}class PDFAttachmentViewer extends BaseTreeViewer{constructor(t){super(t);this.downloadManager=t.downloadManager;this.eventBus._on("fileattachmentannotation",this.#vh.bind(this))}reset(t=!1){super.reset();this._attachments=null;t||(this._renderedCapability=Promise.withResolvers());this._pendingDispatchEvent=!1}async _dispatchEvent(t){this._renderedCapability.resolve();if(0===t&&!this._pendingDispatchEvent){this._pendingDispatchEvent=!0;await waitOnEventOrTimeout({target:this.eventBus,name:"annotationlayerrendered",delay:1e3});if(!this._pendingDispatchEvent)return}this._pendingDispatchEvent=!1;this.eventBus.dispatch("attachmentsloaded",{source:this,attachmentsCount:t})}_bindLink(t,{content:e,description:i,filename:n}){i&&(t.title=i);t.onclick=()=>{this.downloadManager.openOrDownloadData(e,n);return!1}}render({attachments:t,keepRenderedCapability:e=!1}){this._attachments&&this.reset(e);this._attachments=t||null;if(!t){this._dispatchEvent(0);return}const i=document.createDocumentFragment();let n=0;for(const e in t){const s=t[e],a=document.createElement("div");a.className="treeItem";const r=document.createElement("a");this._bindLink(r,s);r.textContent=this._normalizeTextContent(s.filename);a.append(r);i.append(a);n++}this._finishRendering(i,n)}#vh(t){const e=this._renderedCapability.promise;e.then((()=>{if(e!==this._renderedCapability.promise)return;const i=this._attachments||Object.create(null);for(const e in i)if(t.filename===e)return;i[t.filename]=t;this.render({attachments:i,keepRenderedCapability:!0})}))}}const Ct="grab-to-pan-grab";class GrabToPan{#yh=null;#Ah=null;#xh=null;constructor({element:t}){this.element=t;this.document=t.ownerDocument;(this.overlay=document.createElement("div")).className="grab-to-pan-grabbing"}activate(){if(!this.#yh){this.#yh=new AbortController;this.element.addEventListener("mousedown",this.#Eh.bind(this),{capture:!0,signal:this.#yh.signal});this.element.classList.add(Ct)}}deactivate(){if(this.#yh){this.#yh.abort();this.#yh=null;this.#Sh();this.element.classList.remove(Ct)}}toggle(){this.#yh?this.deactivate():this.activate()}ignoreTarget(t){return!!document.querySelector(".stf__item")||t.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}#Eh(t){if(0!==t.button||this.ignoreTarget(t.target))return;if(t.originalTarget)try{t.originalTarget.tagName}catch{return}this.scrollLeftStart=this.element.scrollLeft;this.scrollTopStart=this.element.scrollTop;this.clientXStart=t.clientX;this.clientYStart=t.clientY;if(isOverPerfectScrollbar(this.clientXStart,this.clientYStart,"ps__rail-x"))return;if(isOverPerfectScrollbar(this.clientXStart,this.clientYStart,"ps__rail-y"))return;this.#Ah=new AbortController;const e=this.#Sh.bind(this),i={capture:!0,signal:this.#Ah.signal};this.document.addEventListener("mousemove",this.#Ph.bind(this),i);this.document.addEventListener("mouseup",e,i);this.#xh=new AbortController;this.element.addEventListener("scroll",e,{capture:!0,signal:this.#xh.signal});(0,U.stopEvent)(t);const n=document.activeElement;n&&!n.contains(t.target)&&n.blur()}#Ph(t){this.#xh?.abort();this.#xh=null;if(!(1&t.buttons)){this.#Sh();return}const e=t.clientX-this.clientXStart,i=t.clientY-this.clientYStart;this.element.scrollTo({top:this.scrollTopStart-i,left:this.scrollLeftStart-e,behavior:"instant"});this.overlay.parentNode||document.body.append(this.overlay)}#Sh(){this.#Ah?.abort();this.#Ah=null;this.#xh?.abort();this.#xh=null;this.overlay.remove()}}function isOverPerfectScrollbar(t,e,i){const n=document.getElementsByClassName(i);if(n&&1===n.length){var{top:s,right:a,bottom:r,left:o}=n[0].getBoundingClientRect();if(e>=s&&e<=r&&t<=a&&t>=o)return!0}return!1}class PDFCursorTools{#ph=x;#_h=null;constructor({container:t,eventBus:e,cursorToolOnLoad:i=x}){this.container=t;this.eventBus=e;this.#Ch();Promise.resolve().then((()=>{this.switchTool(i)}))}get activeTool(){return this.#ph}switchTool(t){null===this.#_h&&this.#Th(t)}#Th(t,e=!1){if(t===this.#ph){null!==this.#_h&&this.eventBus.dispatch("cursortoolchanged",{source:this,tool:t,disabled:e});return}const disableActiveTool=()=>{switch(this.#ph){case x:break;case E:this._handTool.deactivate()}};switch(t){case x:disableActiveTool();break;case E:disableActiveTool();this._handTool.activate();break;default:n.NgxConsole.error(`switchTool: "${t}" is an unsupported value.`);return}this.#ph=t;this.eventBus.dispatch("cursortoolchanged",{source:this,tool:t,disabled:e})}#Ch(){this.eventBus._on("switchcursortool",(i=>{if(i.reset){if(null!==this.#_h){t=V.AnnotationEditorType.NONE;e=l;enableActive()}}else this.switchTool(i.tool)}));let t=V.AnnotationEditorType.NONE,e=l;const disableActive=()=>{this.#_h??=this.#ph;this.#Th(x,!0)},enableActive=()=>{if(null!==this.#_h&&t===V.AnnotationEditorType.NONE&&e===l){this.#Th(this.#_h);this.#_h=null}};this.eventBus._on("annotationeditormodechanged",(({mode:e})=>{t=e;e===V.AnnotationEditorType.NONE?enableActive():disableActive()}));this.eventBus._on("presentationmodechanged",(({state:t})=>{e=t;t===l?enableActive():t===d&&disableActive()}))}get _handTool(){return(0,V.shadow)(this,"_handTool",new GrabToPan({element:this.container}))}}const Tt=["en-us","en-lr","my"],Mt={"8.5x11":"pdfjs-document-properties-page-size-name-letter","8.5x14":"pdfjs-document-properties-page-size-name-legal"},It={"297x420":"pdfjs-document-properties-page-size-name-a-three","210x297":"pdfjs-document-properties-page-size-name-a-four"};function getPageName(t,e,i){return i[`${e?t.width:t.height}x${e?t.height:t.width}`]}class PDFDocumentProperties{#Mh=null;constructor({dialog:t,fields:e,closeButton:i},n,s,a,r){this.dialog=t;this.fields=e;this.overlayManager=n;this.l10n=a;this._fileNameLookup=r;this.eventBus=s;this.#Ih();i.addEventListener("click",this.close.bind(this));this.overlayManager.register(this.dialog);s._on("pagechanging",(t=>{this._currentPageNumber=t.pageNumber}));s._on("rotationchanging",(t=>{this._pagesRotation=t.pagesRotation}))}async open(){await Promise.all([this.overlayManager.open(this.dialog),this._dataAvailableCapability.promise]);this.eventBus.dispatch("propertiesdialogopen",this);const t=this._currentPageNumber,e=this._pagesRotation;if(this.#Mh&&t===this.#Mh._currentPageNumber&&e===this.#Mh._pagesRotation){this.#Dh();return}const[{info:i,contentLength:n},s]=await Promise.all([this.pdfDocument.getMetadata(),this.pdfDocument.getPage(t)]),[a,r,o,l,h,d]=await Promise.all([this._fileNameLookup(),this.#Lh(n),this.#kh(i.CreationDate),this.#kh(i.ModDate),this.#Fh(getPageSizeInches(s),e),this.#Rh(i.IsLinearized)]);this.#Mh=Object.freeze({fileName:a,fileSize:r,title:i.Title,author:i.Author,subject:i.Subject,keywords:i.Keywords,creationDate:o,modificationDate:l,creator:i.Creator,producer:i.Producer,version:i.PDFFormatVersion,pageCount:this.pdfDocument.numPages,pageSize:h,linearized:d,_currentPageNumber:t,_pagesRotation:e});this.#Dh();const{length:c}=await this.pdfDocument.getDownloadInfo();if(n===c)return;const u=Object.assign(Object.create(null),this.#Mh);u.fileSize=await this.#Lh(c);this.#Mh=Object.freeze(u);this.#Dh()}async close(){this.overlayManager.close(this.dialog,!0);this.eventBus.dispatch("propertiesdialogclose",this)}setDocument(t){if(this.pdfDocument){this.#Ih();this.#Dh()}if(t){this.pdfDocument=t;this._dataAvailableCapability.resolve()}}#Ih(){this.pdfDocument=null;this.#Mh=null;this._dataAvailableCapability=Promise.withResolvers();this._currentPageNumber=1;this._pagesRotation=0}#Dh(){if(!this.#Mh||this.overlayManager.active===this.dialog)for(const t in this.fields){const e=this.#Mh?.[t];this.fields[t].textContent=e||0===e?e:"-"}}async#Lh(t=0){const e=t/1024,i=e/1024;return e?this.l10n.get(i>=1?"pdfjs-document-properties-size-mb":"pdfjs-document-properties-size-kb",{mb:i,kb:e,b:t}):void 0}async#Fh(t,e){if(!t)return;e%180!=0&&(t={width:t.height,height:t.width});const i=isPortraitOrientation(t),n=Tt.includes(this.l10n.getLanguage());let s={width:Math.round(100*t.width)/100,height:Math.round(100*t.height)/100},a={width:Math.round(25.4*t.width*10)/10,height:Math.round(25.4*t.height*10)/10},r=getPageName(s,i,Mt)||getPageName(a,i,It);if(!(r||Number.isInteger(a.width)&&Number.isInteger(a.height))){const e={width:25.4*t.width,height:25.4*t.height},n={width:Math.round(a.width),height:Math.round(a.height)};if(Math.abs(e.width-n.width)<.1&&Math.abs(e.height-n.height)<.1){r=getPageName(n,i,It);if(r){s={width:Math.round(n.width/25.4*100)/100,height:Math.round(n.height/25.4*100)/100};a=n}}}const[{width:o,height:l},h,d,c]=await Promise.all([n?s:a,this.l10n.get(n?"pdfjs-document-properties-page-size-unit-inches":"pdfjs-document-properties-page-size-unit-millimeters"),r&&this.l10n.get(r),this.l10n.get(i?"pdfjs-document-properties-page-size-orientation-portrait":"pdfjs-document-properties-page-size-orientation-landscape")]);return this.l10n.get(d?"pdfjs-document-properties-page-size-dimension-name-string":"pdfjs-document-properties-page-size-dimension-string",{width:o,height:l,unit:h,name:d,orientation:c})}async#kh(t){const e=j.PDFDateString.toDateObject(t);return e?this.l10n.get("pdfjs-document-properties-date-time-string",{dateObj:e.valueOf()}):void 0}#Rh(t){return this.l10n.get(t?"pdfjs-document-properties-linearized-yes":"pdfjs-document-properties-linearized-no")}}const Dt=0,Lt=1,kt=2,Ft=3,Rt=4,Nt=5,Bt=6,Ot=7;function getCharacterType(t){return function isAlphabeticalScript(t){return t<11904}(t)?function isAscii(t){return!(65408&t)}(t)?function isAsciiSpace(t){return 32===t||9===t||13===t||10===t}(t)?Dt:function isAsciiAlpha(t){return t>=97&&t<=122||t>=65&&t<=90}(t)||function isAsciiDigit(t){return t>=48&&t<=57}(t)||95===t?Lt:kt:function isThai(t){return 3584==(65408&t)}(t)?Ot:160===t?Dt:Lt:function isHan(t){return t>=13312&&t<=40959||t>=63744&&t<=64255}(t)?Ft:function isKatakana(t){return t>=12448&&t<=12543}(t)?Rt:function isHiragana(t){return t>=12352&&t<=12447}(t)?Nt:function isHalfwidthKatakana(t){return t>=65376&&t<=65439}(t)?Bt:Lt}let Vt;const Ht=0,zt=1,Ut=2,jt=3,Wt={"‐":"-","‘":"'","’":"'","‚":"'","‛":"'","“":'"',"”":'"',"„":'"',"‟":'"',"¼":"1/4","½":"1/2","¾":"3/4"},$t=new Set([12441,12442,2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,3642,3770,3972,4153,4154,5908,5940,6098,6752,6980,7082,7083,7154,7155,11647,43014,43052,43204,43347,43456,43766,44013,3158,3953,3954,3962,3963,3964,3965,3968,3956]);let Gt;const qt=/\p{M}+/gu,Xt=/([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu,Kt=/([^\p{M}])\p{M}*$/u,Yt=/^\p{M}*([^\p{M}])/u,Zt=/[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g,Qt=new Map,Jt=new Map;let te=null,ee=null;function normalize(t){const e=[];let i,n;for(;null!==(i=Zt.exec(t));){let{index:t}=i;for(const n of i[0]){let i=Qt.get(n);if(!i){i=n.normalize("NFD").length;Qt.set(n,i)}e.push([i,t++])}}if(0===e.length&&te)n=te;else if(e.length>0&&ee)n=ee;else{const t=`([${Object.keys(Wt).join("")}])|([${function getNormalizeWithNFKC(){Vt||=" ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩";return Vt}()}])|(${"(?:゙|゚)"}\\n)|(\\p{M}+(?:-\\n)?)|(${"\\p{Ll}-\\n\\p{Lu}"})|(\\S-\\n)|(${"(?:\\p{Ideographic}|[-ヿ])"}\\n)|(\\n)`;n=0===e.length?te=new RegExp(t+"|(\\u0000)","gum"):ee=new RegExp(t+"|([\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f])","gum")}const s=[];for(;null!==(i=qt.exec(t));)s.push([i[0].length,i.index]);let a=t.normalize("NFD");const r=[0,0];let o=0,l=0,h=0,d=0,c=0,u=!1;a=a.replace(n,((t,i,n,a,p,g,m,f,b,w,v)=>{v-=d;if(i){const t=Wt[i],e=t.length;for(let t=1;t<e;t++)r.push(v-h+t,h-t);h-=e-1;return t}if(n){let t=Jt.get(n);if(!t){t=n.normalize("NFKC");Jt.set(n,t)}const e=t.length;for(let t=1;t<e;t++)r.push(v-h+t,h-t);h-=e-1;return t}if(a){u=!0;if(v+c===s[o]?.[1])++o;else{r.push(v-1-h+1,h-1);h-=1;d+=1}r.push(v-h+1,h);d+=1;c+=1;return a.charAt(0)}if(p){const t=p.endsWith("\n"),e=t?p.length-2:p.length;u=!0;let i=e;if(v+c===s[o]?.[1]){i-=s[o][0];++o}for(let t=1;t<=i;t++)r.push(v-1-h+t,h-t);h-=i;d+=i;if(t){v+=e-1;r.push(v-h+1,1+h);h+=1;d+=1;c+=1;return p.slice(0,e)}return p}if(g){d+=1;c+=1;return g.replace("\n","")}if(m){const t=m.length-2;r.push(v-h+t,1+h);h+=1;d+=1;c+=1;return m.slice(0,-2)}if(f){const t=f.length-1;r.push(v-h+t,h);d+=1;c+=1;return f.slice(0,-1)}if(b){r.push(v-h+1,h-1);h-=1;d+=1;c+=1;return" "}if(v+c===e[l]?.[1]){const t=e[l][0]-1;++l;for(let e=1;e<=t;e++)r.push(v-(h-e),h-e);h-=t;d+=t}return w}));r.push(a.length,h);const p=new Uint32Array(r.length>>1),g=new Int32Array(r.length>>1);for(let t=0,e=r.length;t<e;t+=2){p[t>>1]=r[t];g[t>>1]=r[t+1]}return[a,[p,g],u]}class PDFFindController{#Nh=null;#Bh=!0;#Oh=0;constructor({linkService:t,eventBus:e,updateMatchesCountOnProgress:i=!0,pageViewMode:n,listenToEventBus:s}){this._linkService=t;this._eventBus=e;this.#Bh=i;this._pageViewMode=n;this.onIsPageVisible=null;this.#Ih();this._eventBus.on("pageviewmodechanged",(({pageViewMode:t})=>{this._pageViewMode=t}));if(s){e._on("find",this.#Vh.bind(this));e._on("findbarclose",this.#Hh.bind(this))}}get highlightMatches(){return this._highlightMatches}get pageMatches(){return this._pageMatches}get pageMatchesLength(){return this._pageMatchesLength}get selected(){return this._selected}get state(){return this.#Nh}setDocument(t){this._pdfDocument&&this.#Ih();if(t){this._pdfDocument=t;this._firstPageCapability.resolve()}}ngxFind(t){const e=[];this._findResultResolvers=[];for(let t=0,i=this._linkService.pagesCount;t<i;t++){const{promise:i,resolve:n}=Promise.withResolvers();e[t]=i;this._findResultResolvers[t]=n}this.#Vh(t);return e}ngxFindNext(){const t={...this.#Nh,type:"again",findPrevious:!1};this.#Vh(t)}ngxFindPrevious(){const t={...this.#Nh,type:"again",findPrevious:!0};this.#Vh(t)}#Vh(t){if(!t)return;const e=this._pdfDocument,{type:i}=t;(null===this.#Nh||this.#zh(t))&&(this._dirtyMatch=!0);this.#Nh=t;if("highlightallchange"!==i)this.#Ul(jt);else{const t=this._pageMatches.some((t=>t.length>0)),e=!this.state?.query||t;this.#Ul(e?Ht:zt)}this._firstPageCapability.promise.then((()=>{if(!this._pdfDocument||e&&this._pdfDocument!==e)return;this.#Ns();const t=!this._highlightMatches,n=!!this._findTimeout;if(this._findTimeout){clearTimeout(this._findTimeout);this._findTimeout=null}if(i)if(this._dirtyMatch)this.#Uh();else if("again"===i){this.#Uh();t&&this.#Nh.highlightAll&&this.#jh()}else if("highlightallchange"===i){n?this.#Uh():this._highlightMatches=!0;this.#jh()}else this.#Uh();else this._findTimeout=setTimeout((()=>{this.#Uh();this._findTimeout=null}),250)}))}scrollMatchIntoView({element:t=null,selectedLeft:e=0,pageIndex:i=-1,matchIndex:n=-1}){if(this.#Nh?.dontScrollIntoView)return;if(!this._scrollMatches||!t)return;this._scrollMatches=!1;scrollIntoView(t,{top:-50,left:e+-400},!0,"infinite-scroll"===this._pageViewMode)}#Ih(){this._highlightMatches=!1;this._scrollMatches=!1;this._pdfDocument=null;this._pageMatches=[];this._pageMatchesLength=[];this.#Oh=0;this.#Nh=null;this._selected={pageIdx:-1,matchIdx:-1};this._offset={pageIdx:null,matchIdx:null,wrapped:!1};this._extractTextPromises=[];this._findResultResolvers=[];this._pageContents=[];this._pageDiffs=[];this._hasDiacritics=[];this._matchesCountTotal=0;this._pagesToSearch=null;this._pendingFindMatches=new Set;this._resumePageIdx=null;this._dirtyMatch=!1;clearTimeout(this._findTimeout);this._findTimeout=null;this._firstPageCapability=Promise.withResolvers()}get#Wh(){const{query:t}=this.#Nh;if("string"==typeof t){if(t!==this._rawQuery){this._rawQuery=t;[this._normalizedQuery]=normalize(t)}return this._normalizedQuery}return(t||[]).filter((t=>!!t)).map((t=>normalize(t)[0]))}#zh(t){const e=t.query,i=this.#Nh.query,n=typeof e;if(n!==typeof i)return!0;if("string"===n){if(e!==i)return!0}else if(JSON.stringify(e)!==JSON.stringify(i))return!0;switch(t.type){case"again":const t=this._selected.pageIdx+1,e=this._linkService;return t>=1&&t<=e.pagesCount&&t!==e.page&&!(this.onIsPageVisible?.(t)??1);case"highlightallchange":return!1}return!0}#$h(t,e,i){let n=t.slice(0,e).match(Kt);if(n){const i=t.charCodeAt(e),s=n[1].charCodeAt(0);if(getCharacterType(i)===getCharacterType(s))return!1}n=t.slice(e+i).match(Yt);if(n){const s=t.charCodeAt(e+i-1),a=n[1].charCodeAt(0);if(getCharacterType(s)===getCharacterType(a))return!1}return!0}_convertToRegExpString(t,e){const{matchDiacritics:i}=this.#Nh;let n=!1;const s="[ ]*";(t=t.replaceAll(Xt,((t,s,a,r,o,l)=>{if(s)return`[ ]*\\${s}[ ]*`;if(a)return`[ ]*${a}[ ]*`;if(r)return"[ ]+";if(i)return o||l;if(o)return $t.has(o.charCodeAt(0))?o:"";if(e){n=!0;return`${l}\\p{M}*`}return l}))).endsWith(s)&&(t=t.slice(0,t.length-4));if(i&&e){Gt||=String.fromCharCode(...$t);n=!0;t=`${t}(?=[${Gt}]|[^\\p{M}]|$)`}return[n,t]}_calculateMatch(t){const e=this.#Wh;if(0===e.length)return;const i=this._pageContents[t],n=this.match(e,i,t),s=this._pageMatches[t]=[],a=this._pageMatchesLength[t]=[],r=this._pageDiffs[t];n?.forEach((({index:t,length:e})=>{const[i,n]=function getOriginalIndex(t,e,i){if(!t)return[e,i];const[n,s]=t,a=e,r=e+i-1;let o=binarySearchFirstItem(n,(t=>t>=a));n[o]>a&&--o;let l=binarySearchFirstItem(n,(t=>t>=r),o);n[l]>r&&--l;const h=a+s[o];return[h,r+s[l]+1-h]}(r,t,e);if(n){s.push(i);a.push(n)}}));this.#Nh.highlightAll&&this.#Gh(t);if(this._resumePageIdx===t){this._resumePageIdx=null;this.#qh()}const o=s.length;this._matchesCountTotal+=o;this.#Bh?o>0&&this.#Xh(t):++this.#Oh===this._linkService.pagesCount&&this.#Xh(t)}match(t,e,i){const n=this._hasDiacritics[i];let s=!1;const{caseSensitive:a,findMultiple:r,matchRegExp:o}=this.#Nh;r&&"string"==typeof t&&(t=t.trim().split(/\s+/));if(o&&"string"==typeof t){t=new RegExp(t,a?"g":"gi");s=n}else"string"==typeof t?[s,t]=this._convertToRegExpString(t,n):t=t.sort().reverse().map((t=>{const[e,i]=this._convertToRegExpString(t,n);s||=e;return`(${i})`})).join("|");if(!t)return;const{entireWord:l}=this.#Nh;t=new RegExp(t,`g${s?"u":""}${a?"":"i"}`);const h=[];let d;for(;null!==(d=t.exec(e));)l&&!this.#$h(e,d.index,d[0].length)||h.push({index:d.index,length:d[0].length});return h}#Ns(){if(this._extractTextPromises.length>0)return;let t=Promise.resolve();const e={disableNormalization:!0};for(let i=0,s=this._linkService.pagesCount;i<s;i++){const{promise:s,resolve:a}=Promise.withResolvers();this._extractTextPromises[i]=s;t=t.then((()=>this._pdfDocument.getPage(i+1).then((t=>t.getTextContent(e))).then((t=>{const e=[];for(const i of t.items){e.push(i.str);i.hasEOL&&e.push("\n")}[this._pageContents[i],this._pageDiffs[i],this._hasDiacritics[i]]=normalize(e.join(""));a()}),(t=>{n.NgxConsole.error(`Unable to get text content for page ${i+1}`,t);this._pageContents[i]="";this._pageDiffs[i]=null;this._hasDiacritics[i]=!1;a()}))))}}#Gh(t){this._scrollMatches&&this._selected.pageIdx===t&&(this.state.dontScrollIntoView||(this._linkService.page=t+1));this._eventBus.dispatch("updatetextlayermatches",{source:this,pageIndex:t})}#jh(){this._eventBus.dispatch("updatetextlayermatches",{source:this,pageIndex:-1})}#Uh(){const t=this.#Nh.findPrevious,e=this._linkService.page-1,i=this._linkService.pagesCount;this._highlightMatches=!0;if(this._dirtyMatch){this._dirtyMatch=!1;this._selected.pageIdx=this._selected.matchIdx=-1;this._offset.pageIdx=e;this._offset.matchIdx=null;this._offset.wrapped=!1;this._resumePageIdx=null;this._pageMatches.length=0;this._pageMatchesLength.length=0;this.#Oh=0;this._matchesCountTotal=0;this.#jh();for(let t=0;t<i;t++)if(!this._pendingFindMatches.has(t)){this._pendingFindMatches.add(t);this._extractTextPromises[t].then((()=>{this._pendingFindMatches.delete(t);this._calculateMatch(t)}))}}if(0===this.#Wh.length){this.#Ul(Ht);return}if(this._resumePageIdx)return;const n=this._offset;this._pagesToSearch=i;if(null!==n.matchIdx){const e=this._pageMatches[n.pageIdx].length;if(!t&&n.matchIdx+1<e||t&&n.matchIdx>0){n.matchIdx=t?n.matchIdx-1:n.matchIdx+1;this.#Kh(!0);return}this.#Yh(t)}this.#qh()}#Zh(t){const e=this._offset,i=t.length,n=this.#Nh.findPrevious;if(i){e.matchIdx=n?i-1:0;this.#Kh(!0);return!0}this.#Yh(n);if(e.wrapped){e.matchIdx=null;if(this._pagesToSearch<0){this.#Kh(!1);return!0}}return!1}#qh(){null!==this._resumePageIdx&&n.NgxConsole.error("There can only be one pending page.");let t=null;do{const e=this._offset.pageIdx;t=this._pageMatches[e];if(!t){this._resumePageIdx=e;break}}while(!this.#Zh(t))}#Yh(t){const e=this._offset,i=this._linkService.pagesCount;e.pageIdx=t?e.pageIdx-1:e.pageIdx+1;e.matchIdx=null;this._pagesToSearch--;if(e.pageIdx>=i||e.pageIdx<0){e.pageIdx=t?i-1:0;e.wrapped=!0}}#Kh(t=!1){let e=zt;const i=this._offset.wrapped;this._offset.wrapped=!1;if(t){const t=this._selected.pageIdx;this._selected.pageIdx=this._offset.pageIdx;this._selected.matchIdx=this._offset.matchIdx;e=i?Ut:Ht;-1!==t&&t!==this._selected.pageIdx&&this.#Gh(t)}this.#Ul(e,this.#Nh.findPrevious);if(-1!==this._selected.pageIdx){this._scrollMatches=!0;this.#Gh(this._selected.pageIdx)}}#Hh(t){const e=this._pdfDocument;this._firstPageCapability.promise.then((()=>{if(this._pdfDocument&&(!e||this._pdfDocument===e)){if(this._findTimeout){clearTimeout(this._findTimeout);this._findTimeout=null}if(this._resumePageIdx){this._resumePageIdx=null;this._dirtyMatch=!0}this.#Ul(Ht);this._highlightMatches=!1;this.#jh()}}))}#Qh(){const{pageIdx:t,matchIdx:e}=this._selected;let i=0,n=this._matchesCountTotal;if(-1!==e){for(let e=0;e<t;e++)i+=this._pageMatches[e]?.length||0;i+=e+1}(i<1||i>n)&&(i=n=0);return{current:i,total:n}}#Xh(t){this._eventBus.dispatch("updatefindmatchescount",{source:this,matchesCount:this.#Qh()});const e=this._pageMatches[t].length;if(this._findResultResolvers&&this._findResultResolvers[t]){this._findResultResolvers[t](e);this._findResultResolvers[t]=null}}#Ul(t,e=!1){(this.#Bh||this.#Oh===this._linkService.pagesCount&&t!==jt)&&this._eventBus.dispatch("updatefindcontrolstate",{source:this,state:t,previous:e,entireWord:this.#Nh?.entireWord??null,matchesCount:this.#Qh(),rawQuery:this.#Nh?.query??null})}}class PDFFindBar{#ql;#Jh=new ResizeObserver(this.#td.bind(this));constructor(t,e,i){this.opened=!1;this.bar=t.bar;this.toggleButton=t.toggleButton;this.findField=t.findField;this.highlightAll=t.highlightAllCheckbox;this.currentPage=t.findCurrentPageCheckbox;this.pageRange=t.findPageRangeField;this.caseSensitive=t.caseSensitiveCheckbox;this.findMultipleCheckbox=t.findMultipleCheckbox;this.matchRegExpCheckbox=t.matchRegExpCheckbox;this.matchDiacritics=t.matchDiacriticsCheckbox;this.entireWord=t.entireWordCheckbox;this.findMsg=t.findMsg;this.findResultsCount=t.findResultsCount;this.findPreviousButton=t.findPreviousButton;this.findNextButton=t.findNextButton;this.eventBus=i;this.#ql=e;const n=new Map(Array.from([[this.highlightAll,"highlightallchange"],[this.caseSensitive,"casesensitivitychange"],[this.entireWord,"entirewordchange"],[this.matchDiacritics,"diacriticmatchingchange"],[this.findMultipleCheckbox,"findmultiplechange"]]).filter((([t])=>t&&t instanceof Element)));this.toggleButton&&(isInsideNgxExtendedPdfViewer(this.toggleButton)||this.toggleButton.addEventListener("click",(()=>{this.toggle()})));this.findField.addEventListener("input",(()=>{this.dispatchEvent("")}));this.findField.parentElement.addEventListener("keydown",(t=>{const{keyCode:e}=t;13!==e&&27!==e&&t.stopPropagation();t.metaKey&&"ArrowDown"===t.key&&t.preventDefault();t.metaKey&&"ArrowUp"===t.key&&t.preventDefault()}));this.bar.addEventListener("keydown",(t=>{const{keyCode:e,shiftKey:i,target:s}=t;switch(e){case 13:if(s===this.findField)this.dispatchEvent("again",i);else if(n.has(s)){s.checked=!s.checked;this.dispatchEvent(n.get(s))}break;case 27:this.close();t.stopPropagation()}}));this.findPreviousButton.addEventListener("click",(()=>{this.dispatchEvent("again",!0)}));this.findNextButton.addEventListener("click",(()=>{this.dispatchEvent("again",!1)}));for(const[t,e]of n)t.addEventListener("click",(()=>{this.dispatchEvent(e)}));this.matchRegExpCheckbox?.addEventListener("click",(()=>{if(this.matchRegExpCheckbox.checked){this.findMultipleCheckbox.checked=!1;this.findMultipleCheckbox.disabled=!0;this.matchDiacritics.checked=!1;this.matchDiacritics.disabled=!0;this.entireWord.checked=!1;this.entireWord.disabled=!0}else{this.findMultipleCheckbox.disabled=!1;this.matchDiacritics.disabled=!1;this.entireWord.disabled=!1}this.dispatchEvent("findregexpchange")}))}reset(){this.updateUIState()}dispatchEvent(t,e=!1){this.eventBus.dispatch("find",{source:this,type:t,query:this.findField.value,caseSensitive:this.caseSensitive.checked,findMultiple:this.findMultipleCheckbox?.checked,matchRegExp:this.matchRegExpCheckbox?.checked,entireWord:this.entireWord.checked,highlightAll:this.highlightAll.checked,findPrevious:e,matchDiacritics:this.matchDiacritics.checked})}updateUIState(t,e,i){const{findField:n,findMsg:s}=this;let a="",r="";switch(t){case Ht:break;case jt:r="pending";break;case zt:a="pdfjs-find-not-found";r="notFound";break;case Ut:a=e?"pdfjs-find-reached-top":"pdfjs-find-reached-bottom"}n.setAttribute("data-status",r);n.setAttribute("aria-invalid",t===zt);s.setAttribute("data-status",r);if(a)s.setAttribute("data-l10n-id",a);else{s.removeAttribute("data-l10n-id");s.textContent=""}this.updateResultsCount(i)}updateResultsCount({current:t=0,total:e=0}={}){const{findResultsCount:i}=this;if(e>0){const n=1e3;i.setAttribute("data-l10n-id",e>n?"pdfjs-find-match-count-limit":"pdfjs-find-match-count");i.setAttribute("data-l10n-args",JSON.stringify({limit:n,current:t,total:e}))}else{i.removeAttribute("data-l10n-id");i.textContent=""}}open(){if(!this.opened){this.#Jh.observe(this.#ql);this.#Jh.observe(this.bar);this.opened=!0;toggleExpandedBtn(this.toggleButton,!0,this.bar)}this.findField.select();this.findField.focus();this.dispatchEvent("");this.eventBus.dispatch("findbaropen",{source:this})}close(){if(this.opened){this.#Jh.disconnect();this.opened=!1;toggleExpandedBtn(this.toggleButton,!1,this.bar);this.eventBus.dispatch("findbarclose",{source:this})}}toggle(){this.opened?this.close():this.open()}#td(){const{bar:t}=this;t.classList.remove("wrapContainers");t.clientHeight>t.firstElementChild.clientHeight&&t.classList.add("wrapContainers")}}function getCurrentHash(){return document.location.hash}class PDFHistory{#ed=null;constructor({linkService:t,eventBus:e}){this.linkService=t;this.eventBus=e;this._initialized=!1;this._fingerprint="";this.reset();this.eventBus._on("pagesinit",(()=>{this._isPagesLoaded=!1;this.eventBus._on("pagesloaded",(t=>{this._isPagesLoaded=!!t.pagesCount}),{once:!0})}))}initialize({fingerprint:t,resetHistory:e=!1,updateUrl:i=!1}){if(!t||"string"!=typeof t){n.NgxConsole.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.');return}this._initialized&&this.reset();const s=""!==this._fingerprint&&this._fingerprint!==t;this._fingerprint=t;this._updateUrl=!0===i;this._initialized=!0;this.#id();const a=window.history.state;this._popStateInProgress=!1;this._blockHashChange=0;this._currentHash=getCurrentHash();this._numPositionUpdates=0;this._uid=this._maxUid=0;this._destination=null;this._position=null;if(!this.#nd(a,!0)||e){const{hash:t,page:i,rotation:n}=this.#sd(!0);if(!t||s||e){this.#ad(null,!0);return}this.#ad({hash:t,page:i,rotation:n},!0);return}const r=a.destination;this.#rd(r,a.uid,!0);void 0!==r.rotation&&(this._initialRotation=r.rotation);if(r.dest){this._initialBookmark=JSON.stringify(r.dest);this._destination.page=null}else r.hash?this._initialBookmark=r.hash:r.page&&(this._initialBookmark=`page=${r.page}`)}reset(){if(this._initialized){this.#od();this._initialized=!1;this.#ld()}if(this._updateViewareaTimeout){clearTimeout(this._updateViewareaTimeout);this._updateViewareaTimeout=null}this._initialBookmark=null;this._initialRotation=null}push({namedDest:t=null,explicitDest:e,pageNumber:i}){if(!this._initialized)return;if(t&&"string"!=typeof t){n.NgxConsole.error(`PDFHistory.push: "${t}" is not a valid namedDest parameter.`);return}if(!Array.isArray(e)){n.NgxConsole.error(`PDFHistory.push: "${e}" is not a valid explicitDest parameter.`);return}if(!this.#hd(i)&&(null!==i||this._destination)){n.NgxConsole.error(`PDFHistory.push: "${i}" is not a valid pageNumber parameter.`);return}const s=t||JSON.stringify(e);if(!s)return;let a=!1;if(this._destination&&(function isDestHashesEqual(t,e){if("string"!=typeof t||"string"!=typeof e)return!1;if(t===e)return!0;if(parseQueryString(t).get("nameddest")===e)return!0;return!1}(this._destination.hash,s)||function isDestArraysEqual(t,e){function isEntryEqual(t,e){if(typeof t!=typeof e)return!1;if(Array.isArray(t)||Array.isArray(e))return!1;if(null!==t&&"object"==typeof t&&null!==e){if(Object.keys(t).length!==Object.keys(e).length)return!1;for(const i in t)if(!isEntryEqual(t[i],e[i]))return!1;return!0}return t===e||Number.isNaN(t)&&Number.isNaN(e)}if(!Array.isArray(t)||!Array.isArray(e))return!1;if(t.length!==e.length)return!1;for(let i=0,n=t.length;i<n;i++)if(!isEntryEqual(t[i],e[i]))return!1;return!0}(this._destination.dest,e))){if(this._destination.page)return;a=!0}if(!this._popStateInProgress||a){this.#ad({dest:e,hash:s,page:i,rotation:this.linkService.rotation},a);if(!this._popStateInProgress){this._popStateInProgress=!0;Promise.resolve().then((()=>{this._popStateInProgress=!1}))}}}pushPage(t){if(this._initialized)if(this.#hd(t)){if(this._destination?.page!==t&&!this._popStateInProgress){this.#ad({dest:null,hash:`page=${t}`,page:t,rotation:this.linkService.rotation});if(!this._popStateInProgress){this._popStateInProgress=!0;Promise.resolve().then((()=>{this._popStateInProgress=!1}))}}}else n.NgxConsole.error(`PDFHistory.pushPage: "${t}" is not a valid page number.`)}pushCurrentPosition(){this._initialized&&!this._popStateInProgress&&this.#dd()}back(){if(!this._initialized||this._popStateInProgress)return;const t=window.history.state;this.#nd(t)&&t.uid>0&&window.history.back()}forward(){if(!this._initialized||this._popStateInProgress)return;const t=window.history.state;this.#nd(t)&&t.uid<this._maxUid&&window.history.forward()}get popStateInProgress(){return this._initialized&&(this._popStateInProgress||this._blockHashChange>0)}get initialBookmark(){return this._initialized?this._initialBookmark:null}get initialRotation(){return this._initialized?this._initialRotation:null}#ad(t,e=!1){const i=e||!this._destination,n={fingerprint:this._fingerprint,uid:i?this._uid:this._uid+1,destination:t};this.#rd(t,n.uid);let s;if(this._updateUrl&&t?.hash){const e=document.location.href.split("#",1)[0];e.startsWith("file://")||(s=`${e}#${t.hash}`)}i?window.history.replaceState(n,"",s):window.history.pushState(n,"",s)}#dd(t=!1){if(!this._position)return;let e=this._position;if(t){e=Object.assign(Object.create(null),this._position);e.temporary=!0}if(!this._destination){this.#ad(e);return}if(this._destination.temporary){this.#ad(e,!0);return}if(this._destination.hash===e.hash)return;if(!this._destination.page&&this._numPositionUpdates<=50)return;let i=!1;if(this._destination.page>=e.first&&this._destination.page<=e.page){if(void 0!==this._destination.dest||!this._destination.first)return;i=!0}this.#ad(e,i)}#hd(t){return Number.isInteger(t)&&t>0&&t<=this.linkService.pagesCount}#nd(t,e=!1){if(!t)return!1;if(t.fingerprint!==this._fingerprint){if(!e)return!1;{if("string"!=typeof t.fingerprint||t.fingerprint.length!==this._fingerprint.length)return!1;const[e]=performance.getEntriesByType("navigation");if("reload"!==e?.type)return!1}}return!(!Number.isInteger(t.uid)||t.uid<0)&&(null!==t.destination&&"object"==typeof t.destination)}#rd(t,e,i=!1){if(this._updateViewareaTimeout){clearTimeout(this._updateViewareaTimeout);this._updateViewareaTimeout=null}i&&t?.temporary&&delete t.temporary;this._destination=t;this._uid=e;this._maxUid=Math.max(this._maxUid,e);this._numPositionUpdates=0}#sd(t=!1){const e=unescape(getCurrentHash()).substring(1),i=parseQueryString(e),n=i.get("nameddest")||"";let s=0|i.get("page");(!this.#hd(s)||t&&n.length>0)&&(s=null);return{hash:e,page:s,rotation:this.linkService.rotation}}#cd({location:t}){if(this._updateViewareaTimeout){clearTimeout(this._updateViewareaTimeout);this._updateViewareaTimeout=null}this._position={hash:t.pdfOpenParams.substring(1),page:this.linkService.page,first:t.pageNumber,rotation:t.rotation};if(!this._popStateInProgress){this._isPagesLoaded&&this._destination&&!this._destination.page&&this._numPositionUpdates++;this._updateViewareaTimeout=setTimeout((()=>{this._popStateInProgress||this.#dd(!0);this._updateViewareaTimeout=null}),1e3)}}#ud({state:t}){const e=getCurrentHash(),i=this._currentHash!==e;this._currentHash=e;if(!t){this._uid++;const{hash:t,page:e,rotation:i}=this.#sd();this.#ad({hash:t,page:e,rotation:i},!0);return}if(!this.#nd(t))return;this._popStateInProgress=!0;if(i){this._blockHashChange++;waitOnEventOrTimeout({target:window,name:"hashchange",delay:1e3}).then((()=>{this._blockHashChange--}))}const n=t.destination;this.#rd(n,t.uid,!0);isValidRotation(n.rotation)&&(this.linkService.rotation=n.rotation);n.dest?this.linkService.goToDestination(n.dest):n.hash?this.linkService.setHash&&this.linkService.setHash(n.hash):n.page&&(this.linkService.page=n.page);Promise.resolve().then((()=>{this._popStateInProgress=!1}))}#od(){this._destination&&!this._destination.temporary||this.#dd()}#id(){if(this.#ed)return;this.#ed=new AbortController;const{signal:t}=this.#ed;this.eventBus._on("updateviewarea",this.#cd.bind(this),{signal:t});window.addEventListener("popstate",this.#ud.bind(this),{signal:t});window.addEventListener("pagehide",this.#od.bind(this),{signal:t})}#ld(){this.#ed?.abort();this.#ed=null}}class PDFLayerViewer extends BaseTreeViewer{constructor(t){super(t);this.eventBus._on("optionalcontentconfigchanged",(t=>{this.#pd(t.promise)}));this.eventBus._on("resetlayers",(()=>{this.#pd()}));this.eventBus._on("togglelayerstree",this._toggleAllTreeItems.bind(this))}reset(){super.reset();this._optionalContentConfig=null;this._optionalContentVisibility?.clear();this._optionalContentVisibility=null}_dispatchEvent(t){this.eventBus.dispatch("layersloaded",{source:this,layersCount:t})}_bindLink(t,{groupId:e,input:i}){const setVisibility=()=>{const t=i.checked;this._optionalContentConfig.setVisibility(e,t);const n=this._optionalContentVisibility.get(e);n&&(n.visible=t);this.eventBus.dispatch("optionalcontentconfig",{source:this,promise:Promise.resolve(this._optionalContentConfig)})};t.onclick=e=>{if(e.target===i){setVisibility();return!0}if(e.target!==t)return!0;i.checked=!i.checked;setVisibility();return!1}}_setNestedName(t,{name:e=null}){if("string"!=typeof e){t.setAttribute("data-l10n-id","pdfjs-additional-layers");t.style.fontStyle="italic";this._l10n.translateOnce(t)}else t.textContent=this._normalizeTextContent(e)}_addToggleButton(t,{name:e=null}){super._addToggleButton(t,null===e)}_toggleAllTreeItems(){this._optionalContentConfig&&super._toggleAllTreeItems()}render({optionalContentConfig:t,pdfDocument:e}){this._optionalContentConfig&&this.reset();this._optionalContentConfig=t||null;this._pdfDocument=e||null;const i=t?.getOrder();if(!i){this._dispatchEvent(0);return}this._optionalContentVisibility=new Map;const n=document.createDocumentFragment(),s=[{parent:n,groups:i}];let a=0,r=!1;for(;s.length>0;){const e=s.shift();for(const i of e.groups){const n=document.createElement("div");n.className="treeItem";const o=document.createElement("a");n.append(o);if("object"==typeof i){r=!0;this._addToggleButton(n,i);this._setNestedName(o,i);const t=document.createElement("div");t.className="treeItems";n.append(t);s.push({parent:t,groups:i.order})}else{const e=t.getGroup(i),n=document.createElement("input");this._bindLink(o,{groupId:i,input:n});n.type="checkbox";n.checked=e.visible;this._optionalContentVisibility.set(i,{input:n,visible:n.checked});const s=document.createElement("label");s.textContent=this._normalizeTextContent(e.name);s.append(n);o.append(s);a++}e.parent.append(n)}}this._finishRendering(n,a,r)}async#pd(t=null){if(!this._optionalContentConfig)return;const e=this._pdfDocument,i=await(t||e.getOptionalContentConfig({intent:"display"}));if(e===this._pdfDocument)if(t)for(const[t,e]of this._optionalContentVisibility){const n=i.getGroup(t);n&&e.visible!==n.visible&&(e.input.checked=e.visible=!e.visible)}else{this.eventBus.dispatch("optionalcontentconfig",{source:this,promise:Promise.resolve(i)});this.render({optionalContentConfig:i,pdfDocument:this._pdfDocument})}}}class PDFOutlineViewer extends BaseTreeViewer{constructor(t){super(t);this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.eventBus._on("toggleoutlinetree",this._toggleAllTreeItems.bind(this));this.eventBus._on("currentoutlineitem",this._currentOutlineItem.bind(this));this.eventBus._on("pagechanging",(t=>{this._currentPageNumber=t.pageNumber}));this.eventBus._on("pagesloaded",(t=>{this._isPagesLoaded=!!t.pagesCount;this._currentOutlineItemCapability?.resolve(this._isPagesLoaded)}));this.eventBus._on("sidebarviewchanged",(t=>{this._sidebarView=t.view}))}reset(){super.reset();this._outline=null;this._pageNumberToDestHashCapability=null;this._currentPageNumber=1;this._isPagesLoaded=null;this._currentOutlineItemCapability?.resolve(!1);this._currentOutlineItemCapability=null}_dispatchEvent(t){this._currentOutlineItemCapability=Promise.withResolvers();0===t||this._pdfDocument?.loadingParams.disableAutoFetch?this._currentOutlineItemCapability.resolve(!1):null!==this._isPagesLoaded&&this._currentOutlineItemCapability.resolve(this._isPagesLoaded);this.eventBus.dispatch("outlineloaded",{source:this,outlineCount:t,currentOutlineItemPromise:this._currentOutlineItemCapability.promise})}_bindLink(t,{url:e,newWindow:i,action:n,attachment:s,dest:a,setOCGState:r}){const{linkService:o}=this;if(e)o.addLinkAttributes(t,e,i);else if(n){t.href=o.getAnchorUrl("");t.onclick=()=>{o.executeNamedAction(n);return!1}}else if(s){t.href=o.getAnchorUrl("");t.onclick=()=>{this.downloadManager.openOrDownloadData(s.content,s.filename);return!1}}else if(r){t.href=o.getAnchorUrl("");t.onclick=()=>{o.executeSetOCGState(r);return!1}}else{t.href=o.getDestinationHash(a);t.onclick=t=>{this._updateCurrentTreeItem(t.target.parentNode);a&&o.goToDestination(a);return!1}}}_setStyles(t,{bold:e,italic:i}){e&&(t.style.fontWeight="bold");i&&(t.style.fontStyle="italic")}_addToggleButton(t,{count:e,items:i}){let n=!1;if(e<0){let t=i.length;if(t>0){const e=[...i];for(;e.length>0;){const{count:i,items:n}=e.shift();if(i>0&&n.length>0){t+=n.length;e.push(...n)}}}Math.abs(e)===t&&(n=!0)}super._addToggleButton(t,n)}_toggleAllTreeItems(){this._outline&&super._toggleAllTreeItems()}render({outline:t,pdfDocument:e}){this._outline&&this.reset();this._outline=t||null;this._pdfDocument=e||null;if(!t){this._dispatchEvent(0);return}const i=document.createDocumentFragment(),n=[{parent:i,items:t}];let s=0,a=!1;for(;n.length>0;){const t=n.shift();for(const e of t.items){const i=document.createElement("div");i.className="treeItem";const r=document.createElement("a");this._bindLink(r,e);this._setStyles(r,e);r.textContent=this._normalizeTextContent(e.title);i.append(r);if(e.items.length>0){a=!0;this._addToggleButton(i,e);const t=document.createElement("div");t.className="treeItems";i.append(t);n.push({parent:t,items:e.items})}t.parent.append(i);s++}}this._finishRendering(i,s,a)}async _currentOutlineItem(){if(!this._isPagesLoaded)throw new Error("_currentOutlineItem: All pages have not been loaded.");if(!this._outline||!this._pdfDocument)return;const t=await this._getPageNumberToDestHash(this._pdfDocument);if(t){this._updateCurrentTreeItem(null);if(this._sidebarView===g)for(let e=this._currentPageNumber;e>0;e--){const i=t.get(e);if(!i)continue;const n=this.container.querySelector(`a[href="${i}"]`);if(n){this._scrollToCurrentTreeItem(n.parentNode);break}}}}async _getPageNumberToDestHash(t){if(this._pageNumberToDestHashCapability)return this._pageNumberToDestHashCapability.promise;this._pageNumberToDestHashCapability=Promise.withResolvers();const e=new Map,i=new Map,n=[{nesting:0,items:this._outline}];for(;n.length>0;){const s=n.shift(),a=s.nesting;for(const{dest:r,items:o}of s.items){let s,l;if("string"==typeof r){s=await t.getDestination(r);if(t!==this._pdfDocument)return null}else s=r;if(Array.isArray(s)){const[n]=s;n&&"object"==typeof n?l=t.cachedPageNumber(n):Number.isInteger(n)&&(l=n+1);if(Number.isInteger(l)&&(!e.has(l)||a>i.get(l))){const t=this.linkService.getDestinationHash(r);e.set(l,t);i.set(l,a)}}o.length>0&&n.push({nesting:a+1,items:o})}}this._pageNumberToDestHashCapability.resolve(e.size>0?e:null);return this._pageNumberToDestHashCapability.promise}}const ie="pdfPresentationMode",ne="pdfPresentationModeControls",se=Math.PI/6;class PDFPresentationMode{#Nh=o;#gd=null;#md=null;#fd=null;constructor({container:t,pdfViewer:e,eventBus:i}){this.container=t;this.pdfViewer=e;this.eventBus=i;this.contextMenuOpen=!1;this.mouseScrollTimeStamp=0;this.mouseScrollDelta=0;this.touchSwipeState=null}async request(){const{container:t,pdfViewer:e}=this;if(this.active||!e.pagesCount||!t.requestFullscreen)return!1;this.#bd();this.#wd(h);const i=t.requestFullscreen();this.#gd={pageNumber:e.currentPageNumber,scaleValue:e.currentScaleValue,scrollMode:e.scrollMode,spreadMode:null,annotationEditorMode:null};if(!(e.spreadMode===A.NONE||e.pageViewsReady&&e.hasEqualPageSizes)){console.warn("Ignoring Spread modes when entering PresentationMode, since the document may contain varying page sizes.");this.#gd.spreadMode=e.spreadMode}e.annotationEditorMode!==V.AnnotationEditorType.DISABLE&&(this.#gd.annotationEditorMode=e.annotationEditorMode);try{await i;e.focus();return!0}catch{this.#vd();this.#wd(l)}return!1}get active(){return this.#Nh===h||this.#Nh===d}#yd(t){if(!this.active)return;t.preventDefault();const e=function normalizeWheelEventDelta(t){const e=t.deltaMode;let i=normalizeWheelEventDirection(t);e===WheelEvent.DOM_DELTA_PIXEL?i/=900:e===WheelEvent.DOM_DELTA_LINE&&(i/=30);return i}(t),i=Date.now(),n=this.mouseScrollTimeStamp;if(!(i>n&&i-n<50)){(this.mouseScrollDelta>0&&e<0||this.mouseScrollDelta<0&&e>0)&&this.#Ad();this.mouseScrollDelta+=e;if(Math.abs(this.mouseScrollDelta)>=.1){const t=this.mouseScrollDelta;this.#Ad();(t>0?this.pdfViewer.previousPage():this.pdfViewer.nextPage())&&(this.mouseScrollTimeStamp=i)}}}#wd(t){this.#Nh=t;this.eventBus.dispatch("presentationmodechanged",{source:this,state:t})}#xd(){this.#wd(d);this.container.classList.add(ie);setTimeout((()=>{this.pdfViewer.scrollMode=y.PAGE;null!==this.#gd.spreadMode&&(this.pdfViewer.spreadMode=A.NONE);this.pdfViewer.currentPageNumber=this.#gd.pageNumber;this.pdfViewer.currentScaleValue="page-fit";null!==this.#gd.annotationEditorMode&&(this.pdfViewer.annotationEditorMode={mode:V.AnnotationEditorType.NONE})}),0);this.#Ed();this.#Sd();this.contextMenuOpen=!1;document.getSelection().empty()}#Pd(){const t=this.pdfViewer.currentPageNumber;this.container.classList.remove(ie);setTimeout((()=>{this.#vd();this.#wd(l);this.pdfViewer.scrollMode=this.#gd.scrollMode;null!==this.#gd.spreadMode&&(this.pdfViewer.spreadMode=this.#gd.spreadMode);this.pdfViewer.currentScaleValue=this.#gd.scaleValue;this.pdfViewer.currentPageNumber=t;null!==this.#gd.annotationEditorMode&&(this.pdfViewer.annotationEditorMode={mode:this.#gd.annotationEditorMode});this.#gd=null}),0);this.#_d();this.#Cd();this.#Ad();this.contextMenuOpen=!1}_prepareFullscreenMode(){const t=document.getElementsByClassName("zoom")[0].parentElement,e=t.parentElement;this.ngxContainer=e;for(let i=0;i<e.childElementCount;i++)e.children.item(i)===t&&(this.ngxContainerIndex=i);e.removeChild(t);document.body.append(t);const i=document.body.children;for(let e=0;e<i.length;e++){const n=i.item(e);n!==t&&n instanceof HTMLElement&&n.classList.add("hidden-by-fullscreen")}document.getElementById("sidebarContainer").classList.add("hidden-by-fullscreen");document.getElementsByClassName("toolbar")[0].classList.add("hidden-by-fullscreen")}_tidyUpFullscreenMode(){if(this.ngxContainer){const t=document.getElementsByClassName("zoom")[0].parentElement;document.body.removeChild(t);this.ngxContainerIndex>=this.ngxContainer.childElementCount?this.ngxContainer.append(t):this.ngxContainer.insertBefore(t,this.ngxContainer.children.item(this.ngxContainerIndex));this.ngxContainer=void 0;const e=document.body.children;for(let i=0;i<e.length;i++){const n=e.item(i);n!==t&&n instanceof HTMLElement&&n.classList.contains("hidden-by-fullscreen")&&n.classList.remove("hidden-by-fullscreen")}document.getElementById("sidebarContainer").classList.remove("hidden-by-fullscreen");document.getElementsByClassName("toolbar")[0].classList.remove("hidden-by-fullscreen")}}#Td(t){if(this.contextMenuOpen){this.contextMenuOpen=!1;t.preventDefault()}else if(!(0!==t.button||t.target.href&&t.target.parentNode?.hasAttribute("data-internal-link"))){t.preventDefault();t.shiftKey?this.pdfViewer.previousPage():this.pdfViewer.nextPage()}}#Md(){this.contextMenuOpen=!0}#Sd(){this.controlsTimeout?clearTimeout(this.controlsTimeout):this.container.classList.add(ne);this.controlsTimeout=setTimeout((()=>{this.container.classList.remove(ne);delete this.controlsTimeout}),3e3)}#Cd(){if(this.controlsTimeout){clearTimeout(this.controlsTimeout);this.container.classList.remove(ne);delete this.controlsTimeout}}#Ad(){this.mouseScrollTimeStamp=0;this.mouseScrollDelta=0}#Id(t){if(this.active)if(t.touches.length>1)this.touchSwipeState=null;else switch(t.type){case"touchstart":this.touchSwipeState={startX:t.touches[0].pageX,startY:t.touches[0].pageY,endX:t.touches[0].pageX,endY:t.touches[0].pageY};break;case"touchmove":if(null===this.touchSwipeState)return;this.touchSwipeState.endX=t.touches[0].pageX;this.touchSwipeState.endY=t.touches[0].pageY;t.preventDefault();break;case"touchend":if(null===this.touchSwipeState)return;let e=0;const i=this.touchSwipeState.endX-this.touchSwipeState.startX,n=this.touchSwipeState.endY-this.touchSwipeState.startY,s=Math.abs(Math.atan2(n,i));Math.abs(i)>50&&(s<=se||s>=Math.PI-se)?e=i:Math.abs(n)>50&&Math.abs(s-Math.PI/2)<=se&&(e=n);e>0?this.pdfViewer.previousPage():e<0&&this.pdfViewer.nextPage()}}#Ed(){if(this.#fd)return;this.#fd=new AbortController;const{signal:t}=this.#fd,e=this.#Id.bind(this);window.addEventListener("mousemove",this.#Sd.bind(this),{signal:t});window.addEventListener("mousedown",this.#Td.bind(this),{signal:t});window.addEventListener("wheel",this.#yd.bind(this),{passive:!1,signal:t});window.addEventListener("keydown",this.#Ad.bind(this),{signal:t});window.addEventListener("contextmenu",this.#Md.bind(this),{signal:t});window.addEventListener("touchstart",e,{signal:t});window.addEventListener("touchmove",e,{signal:t});window.addEventListener("touchend",e,{signal:t})}#_d(){this.#fd?.abort();this.#fd=null}#bd(){if(!this.#md){this.#md=new AbortController;window.addEventListener("fullscreenchange",(()=>{document.fullscreenElement?this.#xd():this.#Pd()}),{signal:this.#md.signal})}}#vd(){this.#md?.abort();this.#md=null}}class XfaLayerBuilder{constructor({pdfPage:t,annotationStorage:e=null,linkService:i,xfaHtml:n=null}){this.pdfPage=t;this.annotationStorage=e;this.linkService=i;this.xfaHtml=n;this.div=null;this._cancelled=!1}async render(t,e="display"){if("print"===e){const i={viewport:t.clone({dontFlip:!0}),div:this.div,xfaHtml:this.xfaHtml,annotationStorage:this.annotationStorage,linkService:this.linkService,intent:e};this.div=document.createElement("div");i.div=this.div;return j.XfaLayer.render(i)}const i=await this.pdfPage.getXfa();if(this._cancelled||!i)return{textDivs:[]};const n={viewport:t.clone({dontFlip:!0}),div:this.div,xfaHtml:i,annotationStorage:this.annotationStorage,linkService:this.linkService,intent:e};if(this.div)return j.XfaLayer.update(n);this.div=document.createElement("div");n.div=this.div;return j.XfaLayer.render(n)}cancel(){this._cancelled=!0}hide(){this.div&&(this.div.hidden=!0)}}function canvasTest(t){const e=t.sizes.shift(),i=Math.max(Math.ceil(e[0]),1),n=Math.max(Math.ceil(e[1]),1),s=[i-1,n-1,1,1],a=performance.now(),r="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;let o,l;if(r){o=new OffscreenCanvas(1,1);l=new OffscreenCanvas(i,n)}else{o=document.createElement("canvas");o.width=1;o.height=1;l=document.createElement("canvas");l.width=i;l.height=n}const h=o.getContext("2d"),d=l.getContext("2d");if(d){d.fillRect.apply(d,s);h.drawImage(l,i-1,n-1,1,1,0,0,1,1)}const c=h&&0!==h.getImageData(0,0,1,1).data[3],u=parseInt(performance.now()-a);[o,l].forEach((t=>{t.height=0;t.width=0}));if(r){postMessage({width:i,height:n,testTime:u,isTestPass:c});!c&&t.sizes.length&&setTimeout((()=>{canvasTest(t)}),0)}else if(c)t.onSuccess({width:i,height:n,testTime:u});else{t.onError({width:i,height:n,testTime:u});t.sizes.length&&setTimeout((()=>{canvasTest(t)}),0)}return c}const ae={area:[16384,14188,11402,11180,10836,8192,4096,1],height:[8388607,65535,32767,16384,8192,4096,1],width:[4194303,65535,32767,16384,8192,4096,1]},re={max:null,min:1,sizes:[],step:1024,useWorker:!1,onError:Function.prototype,onSuccess:Function.prototype},oe={};function createSizesArray(t){const e=t.width===t.height,i=1===t.height,n=1===t.width,s=[];if(t.width&&t.height){const a=t.min||re.min,r=t.step||re.step;let o=Math.max(t.width,t.height);for(;o>=a;){const t=e||i?o:1,a=e||n?o:1;s.push([t,a]);o-=r}}else t.sizes.forEach((t=>{const a=e||i?t:1,r=e||n?t:1;s.push([a,r])}));return s}function handleMethod(t){const e="undefined"!=typeof window,i=e&&"Promise"in window,n=e&&"HTMLCanvasElement"in window,s=e&&"OffscreenCanvas"in window,a=URL.createObjectURL(new Blob([])).slice(-36),r=performance.now(),{onError:o,onSuccess:l,...h}=t,getTotalTime=()=>parseInt(performance.now()-r);let d=null;if(!n)return!1;if(t.useWorker&&s){const t=`\n var canvasTest = ${canvasTest.toString()};\n onmessage = function(e) {\n canvasTest(e.data);\n };\n `,e=new Blob([t],{type:"application/javascript"}),i=URL.createObjectURL(e);d=new Worker(i);URL.revokeObjectURL(i);d.onmessage=function(t){const{width:e,height:i,testTime:n,isTestPass:s}=t.data,r={width:e,height:i,testTime:n,totalTime:getTotalTime()};if(s){oe[a].onSuccess(r);delete oe[a]}else oe[a].onError(r)}}if(i)return new Promise((e=>{const i={...t,onError(i){let{width:n,height:s,testTime:a}=i;const r={width:n,height:s,testTime:a,totalTime:getTotalTime()};let l;if(0===t.sizes.length)l=!0;else{const[[e,i]]=t.sizes.slice(-1);l=n===e&&s===i}o(r);l&&e({...r,success:!1})},onSuccess(t){let{width:i,height:n,testTime:s}=t;const a={width:i,height:n,testTime:s,totalTime:getTotalTime()};l(a);e({...a,success:!0})}};if(d){const{onError:t,onSuccess:e}=i;oe[a]={onError:t,onSuccess:e};d.postMessage(h)}else canvasTest(i)}));if(!d)return canvasTest(t);oe[a]={onError:o,onSuccess:l};d.postMessage(h)}const le={maxArea(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e=createSizesArray({width:t.max,height:t.max,min:t.min,step:t.step,sizes:[...ae.area]});return handleMethod({...re,...t,sizes:e})},maxHeight(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e=createSizesArray({width:1,height:t.max,min:t.min,step:t.step,sizes:[...ae.height]});return handleMethod({...re,...t,sizes:e})},maxWidth(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e=createSizesArray({width:t.max,height:1,min:t.min,step:t.step,sizes:[...ae.width]});return handleMethod({...re,...t,sizes:e})},test(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e={...re,...t};e.sizes=[...e.sizes];e.width&&e.height&&(e.sizes=[[e.width,e.height]]);return handleMethod(e)}};class MaxCanvasSize{static maxWidth=null;static maxHeight=null;static maxArea=null;static async determineMaxArea(){const{success:t,width:e,height:i}=await le.maxArea({useWorker:!0});if(!t){MaxCanvasSize.maxWidth=4096;MaxCanvasSize.maxArea=16777216;return 4096}MaxCanvasSize.maxArea=e*i;return MaxCanvasSize.maxArea}static async determineMaxWidth(){const{width:t}=await le.maxWidth({useWorker:!0});MaxCanvasSize.maxWidth=t;return MaxCanvasSize.maxWidth}static async determineMaxHeight(){const{height:t}=await le.maxHeight({useWorker:!0});MaxCanvasSize.maxHeight=t;return MaxCanvasSize.maxHeight}static async determineMaxDimensions(){if(MaxCanvasSize.maxWidth)return MaxCanvasSize.maxWidth;await this.determineMaxArea();await this.determineMaxHeight();await this.determineMaxWidth();return MaxCanvasSize.maxWidth}static async reduceToMaxCanvasSize(t,e){let i=1;if(t>=4096||e>=4096){await this.determineMaxDimensions();i=Math.max(t/MaxCanvasSize.maxWidth,e/MaxCanvasSize.maxHeight,Math.sqrt(t*e/MaxCanvasSize.maxArea));i>1&&(i=Math.ceil(1+100*i)/100)}return i}}let he=null,de=null,ce=null,ue={initialized:!1};class PDFPrintService{constructor({pdfDocument:t,pagesOverview:e,printResolution:i,printAnnotationStoragePromise:n=null,eventBus:s,cspPolicyService:a},r,o){this.pdfDocument=t;this.pagesOverview=e;this._printResolution=i||150;this._optionalContentConfigPromise=t.getOptionalContentConfig({intent:"print"});this._printAnnotationStoragePromise=n||Promise.resolve();this.currentPage=-1;this.scratchCanvas=document.createElement("canvas");this.eventBus=s;this.filteredPageCount=o;this.isInPDFPrintRange=r;this.cspPolicyService=a}layout(){this.throwIfInactive();const t=document.querySelector("body");t.setAttribute("data-pdfjsprinting",!0);document.querySelector("html").setAttribute("data-pdfjsprinting",!0);const{width:e,height:i}=this.pagesOverview[0];this.pagesOverview.every((t=>t.width===e&&t.height===i))||n.NgxConsole.warn("Not all pages have the same size. The printed result may be incorrect!");this.pageStyleSheet=document.createElement("style");const s=`@page { size: ${e}pt ${i}pt;}`;this.cspPolicyService?this.cspPolicyService.addTrustedCSS(this.pageStyleSheet,s):this.pageStyleSheet.textContent=s;t.append(this.pageStyleSheet)}destroy(){if(he!==this)return;this.printContainer.remove();this.printContainer=null;document.querySelector("body").removeAttribute("data-pdfjsprinting");document.querySelector("html").removeAttribute("data-pdfjsprinting");if(this.pageStyleSheet){this.pageStyleSheet.remove();this.pageStyleSheet=null}this.scratchCanvas.width=this.scratchCanvas.height=0;this.scratchCanvas=null;he=null;if(ce.active===de){ce.close(de);ce.unregister(de);ge=void 0}}renderPages(){if(this.pdfDocument.isPureXfa){!function getXfaHtmlForPrinting(t,e){const i=e.allXfaHtml,n=new SimpleLinkService,s=Math.round(100*j.PixelsPerInch.PDF_TO_CSS_UNITS)/100;for(const a of i.children){const i=document.createElement("div");i.className="xfaPrintedPage";t.append(i);const r=new XfaLayerBuilder({pdfPage:null,annotationStorage:e.annotationStorage,linkService:n,xfaHtml:a}),o=(0,j.getXfaPageViewport)(a,{scale:s});r.render(o,"print");i.append(r.div)}}(this.printContainer,this.pdfDocument);return Promise.resolve()}const t=this.pagesOverview.length,renderNextPage=(e,i)=>{this.throwIfInactive();for(;;){++this.currentPage;if(this.currentPage>=t)break;if(!this.isInPDFPrintRange||this.isInPDFPrintRange(this.currentPage))break}if(this.currentPage>=t){renderProgress(this.filteredPageCount??t,this.filteredPageCount??t,this.eventBus);e();return}const n=this.currentPage;renderProgress(n,this.filteredPageCount??t,this.eventBus);(async function renderPage(t,e,i,n,s,a,r){const o=he.scratchCanvas;let l=s/j.PixelsPerInch.PDF;const h=Math.floor(n.width*l),d=Math.floor(n.height*l),c=await MaxCanvasSize.reduceToMaxCanvasSize(h,d);if(c>1){const t=Math.round(100*(c-1));l=Math.ceil(.95*l/c);const e=l*j.PixelsPerInch.PDF;(0,V.warn)(`Page ${i}: Reduced the maximum resolution by ${t}% because the browser can't render larger canvases. The resolution is now ${e} DPI.`)}o.width=Math.floor(n.width*l);o.height=Math.floor(n.height*l);const u=o.getContext("2d");u.save();u.fillStyle="rgb(255, 255, 255)";u.fillRect(0,0,o.width,o.height);u.restore();return Promise.all([e.getPage(i),r]).then((function([t,e]){const i={canvasContext:u,transform:[l,0,0,l,0,0],viewport:t.getViewport({scale:1,rotation:n.rotation}),intent:"print",annotationMode:V.AnnotationMode.ENABLE_STORAGE,optionalContentConfigPromise:a,printAnnotationStorage:e};return t.render(i).promise.catch((t=>{t instanceof j.RenderingCancelledException||console.error(t);throw t}))}))})(0,this.pdfDocument,n+1,this.pagesOverview[n],this._printResolution,this._optionalContentConfigPromise,this._printAnnotationStoragePromise).then(this.useRenderedPage.bind(this)).then((function(){renderNextPage(e,i)}),i)};return new Promise(renderNextPage)}useRenderedPage(){this.throwIfInactive();const t=document.createElement("img");this.scratchCanvas.toBlob((e=>{t.src=URL.createObjectURL(e)}));const e=document.createElement("div");e.className="printedPage";e.append(t);this.printContainer.append(e);const{promise:i,resolve:n,reject:s}=Promise.withResolvers();t.onload=n;t.onerror=s;i.catch((()=>{})).then((()=>{URL.revokeObjectURL(t.src)}));return i}performPrint(){this.throwIfInactive();return new Promise((t=>{setTimeout((()=>{if(!this.active){t();return}pe.call(window);const e=navigator.platform&&["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document;setTimeout(t,e?1500:20)}),0)}))}get active(){return this===he}throwIfInactive(){if(!this.active)throw new Error("This print request was cancelled or completed.")}}const pe=window.print;function dispatchEvent(t){const e=new CustomEvent(t,{bubbles:!1,cancelable:!1,detail:"custom"});window.dispatchEvent(e)}function abort(){if(he){he.destroy();dispatchEvent("afterprint")}}function renderProgress(t,e,i){de=document.getElementById("printServiceDialog");const n=Math.round(100*t/e),s=de.querySelector("progress"),a=de.querySelector(".relative-progress");s.value=n;a.setAttribute("data-l10n-args",JSON.stringify({progress:n}));i.dispatch("progress",{source:this,type:"print",total:e,page:t,percent:100*t/e})}window.addEventListener("keydown",(function(t){if(80===t.keyCode&&(t.ctrlKey||t.metaKey)&&!t.altKey&&(!t.shiftKey||window.chrome||window.opera)){window.print();t.preventDefault();t.stopImmediatePropagation()}}),!0);if("onbeforeprint"in window){const stopPropagationIfNeeded=function(t){"custom"!==t.detail&&t.stopImmediatePropagation()};window.addEventListener("beforeprint",stopPropagationIfNeeded);window.addEventListener("afterprint",stopPropagationIfNeeded)}let ge;function ensureOverlay(){if(!ge){ce=ue.overlayManager;if(!ce)throw new Error("The overlay manager has not yet been initialized.");de=document.getElementById("printServiceDialog");ge=ce.register(de,!0);document.getElementById("printCancel").onclick=abort;de.addEventListener("close",abort)}return ge}class PDFPrintServiceFactory{static enablePrint=!0;static initGlobals(t){ue=t}static get supportsPrinting(){return(0,V.shadow)(this,"supportsPrinting",!0)}static createPrintService(t){if(he)throw new Error("The print service is created and active.");PDFPrintServiceFactory.enablePrint||console.debug("The print service is disabled.");return he=new PDFPrintService(t,PDFPrintServiceFactory.isInPDFPrintRange,PDFPrintServiceFactory.filteredPageCount)}}class PDFRenderingQueue{constructor(){this.pdfViewer=null;this.pdfThumbnailViewer=null;this.onIdle=null;this.highestPriorityPage=null;this.idleTimeout=null;this.printing=!1;this.isThumbnailViewEnabled=!1;Object.defineProperty(this,"hasViewer",{value:()=>!!this.pdfViewer})}setViewer(t){this.pdfViewer=t}setThumbnailViewer(t){this.pdfThumbnailViewer=t}isHighestPriority(t){return this.highestPriorityPage===t.renderingId}renderHighestPriority(t){if(this.idleTimeout){clearTimeout(this.idleTimeout);this.idleTimeout=null}this.pdfViewer.forceRendering(t)||this.isThumbnailViewEnabled&&this.pdfThumbnailViewer?.forceRendering()||this.printing||this.onIdle&&(this.idleTimeout=setTimeout(this.onIdle.bind(this),3e4))}getHighestPriority(t,e,i,n=!1){const s=t.views,a=s.length;if(0===a)return null;for(let t=0;t<a;t++){const e=s[t].view;if(!this.isViewFinished(e))return e}const r=t.first.id,o=t.last.id;if(o-r+1>a){const n=t.ids;for(let t=1,s=o-r;t<s;t++){const s=i?r+t:o-t;if(n.has(s))continue;const a=e[s-1];if(!this.isViewFinished(a))return a}}let l=i?o:r-2,h=e[l];if(h&&!this.isViewFinished(h))return h;if(n){l+=i?1:-1;h=e[l];if(h&&!this.isViewFinished(h))return h}return null}isViewFinished(t){return t.renderingState===r.FINISHED}renderView(t){switch(t.renderingState){case r.FINISHED:return!1;case r.PAUSED:this.highestPriorityPage=t.renderingId;t.resume();break;case r.RUNNING:this.highestPriorityPage=t.renderingId;break;case r.INITIAL:this.highestPriorityPage=t.renderingId;t.draw().finally((()=>{this.renderHighestPriority()})).catch((t=>{t instanceof j.RenderingCancelledException||n.NgxConsole.error("renderView:",t)}))}return!0}}class PDFScriptingManager{#Dd=null;#Ld=null;#kd=null;#ed=null;#Ma=null;#Fd=null;#Rd=null;#Nd=null;#Bd=!1;#Od=null;#Vd=null;constructor({eventBus:t,externalServices:e=null,docProperties:i=null}){this.#Ma=t;this.#Fd=e;this.#kd=i}setViewer(t){this.#Nd=t}async setDocument(t){this.#Rd&&await this.#Hd();this.#Rd=t;if(!t)return;const[e,i,s]=await Promise.all([t.getFieldObjects(),t.getCalculationOrderIds(),t.getJSActions()]);if(!e&&!s){await this.#Hd();return}if(t!==this.#Rd)return;try{this.#Od=this.#zd()}catch(t){n.NgxConsole.error("setDocument:",t);await this.#Hd();return}const a=this.#Ma;this.#ed=new AbortController;const{signal:r}=this.#ed;a._on("updatefromsandbox",(t=>{t?.source===window&&this.#Ud(t.detail)}),{signal:r});a._on("dispatcheventinsandbox",(t=>{this.#Od?.dispatchEventInSandbox(t.detail)}),{signal:r});a._on("pagechanging",(({pageNumber:t,previous:e})=>{if(t!==e){this.#jd(e);this.#Wd(t)}}),{signal:r});a._on("pagerendered",(({pageNumber:t})=>{this._pageOpenPending.has(t)&&t===this.#Nd.currentPageNumber&&this.#Wd(t)}),{signal:r});a._on("pagesdestroy",(async()=>{await this.#jd(this.#Nd.currentPageNumber);await(this.#Od?.dispatchEventInSandbox({id:"doc",name:"WillClose"}));this.#Dd?.resolve()}),{signal:r});try{const n=await this.#kd(t);if(t!==this.#Rd)return;await this.#Od.createSandbox({objects:e,calculationOrder:i,appInfo:{platform:navigator.platform,language:navigator.language},docInfo:{...n,actions:s}});a.dispatch("sandboxcreated",{source:this})}catch(t){n.NgxConsole.error("setDocument:",t);await this.#Hd();return}await(this.#Od?.dispatchEventInSandbox({id:"doc",name:"Open"}));await this.#Wd(this.#Nd.currentPageNumber,!0);Promise.resolve().then((()=>{t===this.#Rd&&(this.#Bd=!0)}))}async dispatchWillSave(){return this.#Od?.dispatchEventInSandbox({id:"doc",name:"WillSave"})}async dispatchDidSave(){return this.#Od?.dispatchEventInSandbox({id:"doc",name:"DidSave"})}async dispatchWillPrint(){if(this.#Od){await(this.#Vd?.promise);this.#Vd=Promise.withResolvers();try{await this.#Od.dispatchEventInSandbox({id:"doc",name:"WillPrint"})}catch(t){this.#Vd.resolve();this.#Vd=null;throw t}await this.#Vd.promise}}async dispatchDidPrint(){return this.#Od?.dispatchEventInSandbox({id:"doc",name:"DidPrint"})}get destroyPromise(){return this.#Ld?.promise||null}get ready(){return this.#Bd}get _pageOpenPending(){return(0,V.shadow)(this,"_pageOpenPending",new Set)}get _visitedPages(){return(0,V.shadow)(this,"_visitedPages",new Map)}async#Ud(t){const e=this.#Nd,i=e.isInPresentationMode||e.isChangingPresentationMode,{id:s,siblings:a,command:r,value:o}=t;if(!s){switch(r){case"clear":n.NgxConsole.clear();break;case"error":n.NgxConsole.error(o);break;case"layout":if(!i){const t=apiPageLayoutToViewerModes(o);e.spreadMode=t.spreadMode}break;case"page-num":e.currentPageNumber=o+1;break;case"print":await e.pagesPromise;this.#Ma.dispatch("print",{source:this});break;case"println":n.NgxConsole.log(o);break;case"zoom":i||(e.currentScaleValue=o);break;case"SaveAs":this.#Ma.dispatch("download",{source:this});break;case"FirstPage":e.currentPageNumber=1;break;case"LastPage":e.currentPageNumber=e.pagesCount;break;case"NextPage":e.nextPage();break;case"PrevPage":e.previousPage();break;case"ZoomViewIn":i||e.increaseScale();break;case"ZoomViewOut":i||e.decreaseScale();break;case"WillPrintFinished":this.#Vd?.resolve();this.#Vd=null}return}if(i&&t.focus)return;delete t.id;delete t.siblings;const l=a?[s,...a]:[s];for(const e of l){const i=document.querySelector(`[data-element-id="${e}"]`);i?i.dispatchEvent(new CustomEvent("updatefromsandbox",{detail:t})):this.#Rd?.annotationStorage.setValue(e,t)}}async#Wd(t,e=!1){const i=this.#Rd,n=this._visitedPages;e&&(this.#Dd=Promise.withResolvers());if(!this.#Dd)return;const s=this.#Nd.getPageView(t-1);if(s?.renderingState!==r.FINISHED){this._pageOpenPending.add(t);return}this._pageOpenPending.delete(t);const a=(async()=>{const e=await(n.has(t)?null:s.pdfPage?.getJSActions());i===this.#Rd&&await(this.#Od?.dispatchEventInSandbox({id:"page",name:"PageOpen",pageNumber:t,actions:e}))})();n.set(t,a)}async#jd(t){const e=this.#Rd,i=this._visitedPages;if(!this.#Dd)return;if(this._pageOpenPending.has(t))return;const n=i.get(t);if(n){i.set(t,null);await n;e===this.#Rd&&await(this.#Od?.dispatchEventInSandbox({id:"page",name:"PageClose",pageNumber:t}))}}#zd(){this.#Ld=Promise.withResolvers();if(this.#Od)throw new Error("#initScripting: Scripting already exists.");return this.#Fd.createScripting()}async#Hd(){if(this.#Od){if(this.#Dd){await Promise.race([this.#Dd.promise,new Promise((t=>{setTimeout(t,1e3)}))]).catch((()=>{}));this.#Dd=null}this.#Rd=null;try{await this.#Od.destroySandbox()}catch{}this.#Vd?.reject(new Error("Scripting destroyed."));this.#Vd=null;this.#ed?.abort();this.#ed=null;this._pageOpenPending.clear();this._visitedPages.clear();this.#Od=null;this.#Bd=!1;this.#Ld?.resolve()}else{this.#Rd=null;this.#Ld?.resolve()}}}const me="sidebarResizing",fe="pdfSidebarNotification";class PDFSidebar{#Oo=!1;#$d=null;#Gd=null;#qd=null;constructor({elements:t,eventBus:e,l10n:i}){this.isOpen=!1;this.active=p;this.isInitialViewSet=!1;this.isInitialEventDispatched=!1;this.onToggled=null;this.onUpdateThumbnails=null;this.outerContainer=t.outerContainer;this.sidebarContainer=t.sidebarContainer;this.toggleButton=t.toggleButton;this.resizer=t.resizer;this.thumbnailButton=t.thumbnailButton;this.outlineButton=t.outlineButton;this.attachmentsButton=t.attachmentsButton;this.layersButton=t.layersButton;this.thumbnailView=t.thumbnailView;this.outlineView=t.outlineView;this.attachmentsView=t.attachmentsView;this.layersView=t.layersView;this._currentOutlineItemButton=t.currentOutlineItemButton;this.eventBus=e;this.#Oo="rtl"===i.getDirection();this.#Ch()}reset(){this.isInitialViewSet=!1;this.isInitialEventDispatched=!1;this.#Xd(!0);this.switchView(p);this.outlineButton.disabled=!1;this.attachmentsButton.disabled=!1;this.layersButton.disabled=!1;this.outlineButton.hidden=!1;this.attachmentsButton.hidden=!1;this.layersButton.hidden=!1;this._currentOutlineItemButton.disabled=!0}get visibleView(){return this.isOpen?this.active:u}setInitialView(t=u){if(!this.isInitialViewSet){this.isInitialViewSet=!0;if(t!==u&&t!==c){this.switchView(t,!0);this.isInitialEventDispatched||this.#Kd()}else this.#Kd()}}switchView(t,e=!1){const i=t!==this.active;let s=!1;switch(t){case u:this.isOpen&&this.close();return;case p:this.isOpen&&i&&(s=!0);break;case g:if(this.outlineButton.disabled)return;break;case m:if(this.attachmentsButton.disabled)return;break;case f:if(this.layersButton.disabled)return;break;default:n.NgxConsole.error(`PDFSidebar.switchView: "${t}" is not a valid view.`);return}this.active=t;toggleCheckedBtn(this.thumbnailButton,t===p,this.thumbnailView);toggleCheckedBtn(this.outlineButton,t===g,this.outlineView);toggleCheckedBtn(this.attachmentsButton,t===m,this.attachmentsView);toggleCheckedBtn(this.layersButton,t===f,this.layersView);if(!e||this.isOpen){if(s){this.onUpdateThumbnails();this.onToggled()}i&&this.#Kd()}else this.open()}open(){if(!this.isOpen){this.isOpen=!0;toggleExpandedBtn(this.toggleButton,!0);this.outerContainer.classList.add("sidebarMoving","sidebarOpen");this.active===p&&this.onUpdateThumbnails();this.onToggled();this.#Kd();this.#Xd()}}close(t=null){if(this.isOpen){this.isOpen=!1;toggleExpandedBtn(this.toggleButton,!1);this.outerContainer.classList.add("sidebarMoving");this.outerContainer.classList.remove("sidebarOpen");this.onToggled();this.#Kd();t?.detail>0&&this.toggleButton.blur()}}toggle(t=null){this.isOpen?this.close(t):this.open()}#Kd(){this.isInitialViewSet&&(this.isInitialEventDispatched||=!0);this.eventBus.dispatch("sidebarviewchanged",{source:this,view:this.visibleView})}#Yd(){this.toggleButton.setAttribute("data-l10n-id","pdfjs-toggle-sidebar-notification-button");this.isOpen||this.toggleButton.classList.add(fe)}#Xd(t=!1){(this.isOpen||t)&&this.toggleButton.classList.remove(fe);t&&this.toggleButton.setAttribute("data-l10n-id","pdfjs-toggle-sidebar-button")}#Ch(){const{eventBus:t,outerContainer:e}=this;this.sidebarContainer.addEventListener("transitionend",(i=>{if(i.target===this.sidebarContainer){e.classList.remove("sidebarMoving");t.dispatch("resize",{source:this})}}));isInsideNgxExtendedPdfViewer(this.toggleButton)||this.toggleButton.addEventListener("click",(t=>{this.toggle(t)}));this.thumbnailButton.addEventListener("click",(()=>{this.switchView(p)}));this.outlineButton.addEventListener("click",(()=>{this.switchView(g)}));this.outlineButton.addEventListener("dblclick",(()=>{t.dispatch("toggleoutlinetree",{source:this})}));this.attachmentsButton.addEventListener("click",(()=>{this.switchView(m)}));this.layersButton.addEventListener("click",(()=>{this.switchView(f)}));this.layersButton.addEventListener("dblclick",(()=>{t.dispatch("resetlayers",{source:this})}));this._currentOutlineItemButton.addEventListener("click",(()=>{t.dispatch("currentoutlineitem",{source:this})}));const onTreeLoaded=(t,e,i)=>{e.disabled=!t;e.hidden=!t;t?this.#Yd():this.active===i&&this.switchView(p)};t._on("outlineloaded",(t=>{onTreeLoaded(t.outlineCount,this.outlineButton,g);t.enableCurrentOutlineItemButton&&t.currentOutlineItemPromise&&t.currentOutlineItemPromise.then((t=>{this.isInitialViewSet&&(this._currentOutlineItemButton.disabled=!t)}))}));t._on("attachmentsloaded",(t=>{onTreeLoaded(t.attachmentsCount,this.attachmentsButton,m)}));t._on("layersloaded",(t=>{onTreeLoaded(t.layersCount,this.layersButton,f)}));t._on("presentationmodechanged",(t=>{t.state===l&&this.visibleView===p&&this.onUpdateThumbnails()}));this.resizer.addEventListener("mousedown",(t=>{if(0!==t.button)return;e.classList.add(me);this.#$d=new AbortController;const i={signal:this.#$d.signal};window.addEventListener("mousemove",this.#Zd.bind(this),i);window.addEventListener("mouseup",this.#Qd.bind(this),i);window.addEventListener("blur",this.#Qd.bind(this),i)}));t._on("resize",(i=>{if(i.source!==window)return;this.#Gd=null;if(!this.#qd)return;if(!this.isOpen){this.#Jd(this.#qd);return}e.classList.add(me);const n=this.#Jd(this.#qd);Promise.resolve().then((()=>{e.classList.remove(me);n&&t.dispatch("resize",{source:this})}))}))}get outerContainerWidth(){return this.#Gd||=this.outerContainer.clientWidth}#Jd(t=0){const e=Math.floor(this.outerContainerWidth/2);t>e&&(t=e);t<200&&(t=200);if(t===this.#qd)return!1;this.#qd=t;C.setProperty("--sidebar-width",`${t}px`);return!0}#Zd(t){let e=t.clientX;this.#Oo&&(e=this.outerContainerWidth-e);this.#Jd(e)}#Qd(t){this.outerContainer.classList.remove(me);this.eventBus.dispatch("resize",{source:this});this.#$d?.abort();this.#$d=null}}class TempImageFactory{static#tc=null;static getCanvas(t,e){const i=this.#tc||=document.createElement("canvas");i.width=t;i.height=e;const n=i.getContext("2d",{alpha:!1});n.save();n.fillStyle="rgb(255, 255, 255)";n.fillRect(0,0,t,e);n.restore();return[i,i.getContext("2d")]}static destroyCanvas(){const t=this.#tc;if(t){t.width=0;t.height=0}this.#tc=null}}class PDFThumbnailView{constructor({container:t,eventBus:e,id:i,defaultViewport:n,optionalContentConfigPromise:s,linkService:a,renderingQueue:o,pageColors:l,enableHWA:h}){this.id=i;this.renderingId="thumbnail"+i;this.pageLabel=null;this.pdfPage=null;this.rotation=0;this.viewport=n;this.pdfPageRotate=n.rotation;this._optionalContentConfigPromise=s||null;this.pageColors=l||null;this.enableHWA=h||!1;this.eventBus=e;this.linkService=a;this.renderingQueue=o;this.eventBus=e;this.renderTask=null;this.renderingState=r.INITIAL;this.resume=null;e.dispatch("rendercustomthumbnail",{pdfThumbnailView:this,linkService:a,id:i,container:t,thumbPageTitlePromiseOrPageL10nArgs:this.#ec});t.querySelector(`.${this.renderingId}`)?this._placeholderImg=t.querySelector(`.${this.renderingId} .thumbnailImage`):this.createThumbnail(this,a,i,t,this.#ec)}createThumbnail(t,e,i,n,s){const a=document.createElement("a");a.href=e.getAnchorUrl("#page="+i);a.setAttribute("data-l10n-id","pdfjs-thumb-page-title");a.setAttribute("data-l10n-args",this.#ec);a.className=this.renderingId;a.onclick=function(){e.goToPage(i);return!1};this.anchor=a;const r=document.createElement("div");r.className="thumbnail";r.setAttribute("data-page-number",this.id);this.div=r;this.#ic();const o=document.createElement("div");o.className="thumbnailImage";this._placeholderImg=o;r.append(o);a.append(r);n.append(a)}#ic(){const{width:t,height:e}=this.viewport,i=t/e;this.canvasWidth=98;this.canvasHeight=this.canvasWidth/i|0;this.scale=this.canvasWidth/t;const{style:n}=this.div;n.setProperty("--thumbnail-width",`${this.canvasWidth}px`);n.setProperty("--thumbnail-height",`${this.canvasHeight}px`)}setPdfPage(t){this.pdfPage=t;this.pdfPageRotate=t.rotate;const e=(this.rotation+this.pdfPageRotate)%360;this.viewport=t.getViewport({scale:1,rotation:e});this.reset()}reset(){this.cancelRendering();this.renderingState=r.INITIAL;this.div.removeAttribute("data-loaded");this.image?.replaceWith(this._placeholderImg);this.#ic();if(this.image){this.image.removeAttribute("src");delete this.image}}update({rotation:t=null}){"number"==typeof t&&(this.rotation=t);const e=(this.rotation+this.pdfPageRotate)%360;this.viewport=this.viewport.clone({scale:1,rotation:e});this.reset()}cancelRendering(){if(this.renderTask){this.renderTask.cancel();this.renderTask=null}this.resume=null}#nc(t=1,e=this.enableHWA){const i=document.createElement("canvas"),n=i.getContext("2d",{alpha:!1,willReadFrequently:!e}),s=new j.OutputScale;i.width=t*this.canvasWidth*s.sx|0;i.height=t*this.canvasHeight*s.sy|0;return{ctx:n,canvas:i,transform:s.scaled?[s.sx,0,0,s.sy,0,0]:null}}#sc(t){if(this.renderingState!==r.FINISHED)throw new Error("#convertCanvasToImage: Rendering has not finished.");const e=this.#ac(t),i=document.createElement("img");i.className="thumbnailImage";i.setAttribute("data-l10n-id","pdfjs-thumb-page-canvas");i.setAttribute("data-l10n-args",this.#ec);i.src=e.toDataURL();this.image=i;this.div.setAttribute("data-loaded",!0);this._placeholderImg.replaceWith(i);e.width=0;e.height=0}async#rc(t,e,i=null){t===this.renderTask&&(this.renderTask=null);if(!(i instanceof j.RenderingCancelledException)){this.renderingState=r.FINISHED;this.#sc(e);if(i)throw i;this.eventBus.dispatch("thumbnailRendered",this.id)}}async draw(){if(this.renderingState!==r.INITIAL){n.NgxConsole.error("Must be in new state before drawing");return}const{pdfPage:t}=this;if(!t){this.renderingState=r.FINISHED;throw new Error("pdfPage is not loaded")}this.renderingState=r.RUNNING;const{ctx:e,canvas:i,transform:s}=this.#nc(2),a={canvasContext:e,transform:s,viewport:this.viewport.clone({scale:2*this.scale}),optionalContentConfigPromise:this._optionalContentConfigPromise,pageColors:this.pageColors},o=this.renderTask=t.render(a);o.onContinue=t=>{if(this.renderingQueue.isHighestPriority(this))t();else{this.renderingState=r.PAUSED;this.resume=()=>{this.renderingState=r.RUNNING;t()}}};const l=o.promise.then((()=>this.#rc(o,i)),(t=>this.#rc(o,i,t)));l.finally((()=>{i.width=0;i.height=0;this.eventBus.dispatch("thumbnailrendered",{source:this,pageNumber:this.id,pdfPage:this.pdfPage})}));return l}setImage(t){if(this.renderingState!==r.INITIAL)return;const{thumbnailCanvas:e,pdfPage:i,scale:n}=t;if(e){this.pdfPage||this.setPdfPage(i);if(!(n<this.scale)){this.renderingState=r.FINISHED;this.#sc(e)}}}#ac(t){const{ctx:e,canvas:i}=this.#nc(1,!0);if(t.width<=2*i.width){e.drawImage(t,0,0,t.width,t.height,0,0,i.width,i.height);return i}let n=i.width<<3,s=i.height<<3;const[a,r]=TempImageFactory.getCanvas(n,s);for(;n>t.width||s>t.height;){n>>=1;s>>=1}r.drawImage(t,0,0,t.width,t.height,0,0,n,s);for(;n>2*i.width;){r.drawImage(a,0,0,n,s,0,0,n>>1,s>>1);n>>=1;s>>=1}e.drawImage(a,0,0,n,s,0,0,i.width,i.height);return i}get#ec(){return JSON.stringify({page:this.pageLabel??this.id})}setPageLabel(t){this.pageLabel="string"==typeof t?t:null;this.anchor.setAttribute("data-l10n-args",this.#ec);this.renderingState===r.FINISHED&&this.image?.setAttribute("data-l10n-args",this.#ec)}}const be="selected";class PDFThumbnailViewer{constructor({container:t,eventBus:e,linkService:i,renderingQueue:n,pageColors:s,abortSignal:a,enableHWA:r}){this.container=t;this.eventBus=e;this.linkService=i;this.renderingQueue=n;this.pageColors=s||null;this.enableHWA=r||!1;this.scroll=watchScroll(this.container,this.#oc.bind(this),a);this.#lc()}#oc(){this.renderingQueue.renderHighestPriority()}getThumbnail(t){return this._thumbnails[t]}#hc(){return getVisibleElements({scrollEl:this.container,views:this._thumbnails})}scrollThumbnailIntoView(t){if(!this.pdfDocument)return;const e=this._thumbnails[t-1];if(!e){n.NgxConsole.error('scrollThumbnailIntoView: Invalid "pageNumber" parameter.');return}if(t!==this._currentPageNumber){this._thumbnails[this._currentPageNumber-1].div.classList.remove(be);e.div.classList.add(be)}const{first:i,last:s,views:a}=this.#hc();if(a.length>0){let n=!1;if(t<=i.id||t>=s.id)n=!0;else for(const{id:e,percent:i}of a)if(e===t){n=i<100;break}n&&scrollIntoView(e.div,{top:-19})}this._currentPageNumber=t}get pagesRotation(){return this._pagesRotation}set pagesRotation(t){if(!isValidRotation(t))throw new Error("Invalid thumbnails rotation angle.");if(!this.pdfDocument)return;if(this._pagesRotation===t)return;this._pagesRotation=t;const e={rotation:t};for(const t of this._thumbnails)t.update(e)}cleanup(){for(const t of this._thumbnails)t.renderingState!==r.FINISHED&&t.reset();TempImageFactory.destroyCanvas()}#lc(){this._thumbnails=[];this._currentPageNumber=1;this._pageLabels=null;this._pagesRotation=0;this.container.textContent=""}setDocument(t){this.initialized=!1;if(this.pdfDocument){this.#dc();this.#lc()}this.pdfDocument=t;if(!t)return;if(this.initialized)return;this.initialized=!0;const e=t.getPage(1),i=t.getOptionalContentConfig({intent:"display"});e.then((e=>{const n=t.numPages,s=e.getViewport({scale:1});for(let t=1;t<=n;++t){const e=new PDFThumbnailView({container:this.container,eventBus:this.eventBus,id:t,defaultViewport:s.clone(),optionalContentConfigPromise:i,linkService:this.linkService,renderingQueue:this.renderingQueue,pageColors:this.pageColors,eventBus:this.eventBus,enableHWA:this.enableHWA});this._thumbnails.push(e)}this._thumbnails[0]?.setPdfPage(e);this._thumbnails[this._currentPageNumber-1].div.classList.add(be)})).catch((t=>{n.NgxConsole.error("Unable to initialize thumbnail viewer",t)}))}#dc(){for(const t of this._thumbnails)t.cancelRendering()}setPageLabels(t){if(this.pdfDocument){if(t)if(Array.isArray(t)&&this.pdfDocument.numPages===t.length)this._pageLabels=t;else{this._pageLabels=null;n.NgxConsole.error("PDFThumbnailViewer_setPageLabels: Invalid page labels.")}else this._pageLabels=null;for(let t=0,e=this._thumbnails.length;t<e;t++)this._thumbnails[t].setPageLabel(this._pageLabels?.[t]??null)}}async#cc(t){if(t.pdfPage)return t.pdfPage;try{const e=await this.pdfDocument.getPage(t.id);t.pdfPage||t.setPdfPage(e);return e}catch(t){n.NgxConsole.error("Unable to get page for thumb view",t);return null}}#uc(t){return 1===t.first?.id||t.last?.id!==this._thumbnails.length&&this.scroll.down}forceRendering(){const t=this.#hc(),e=this.#uc(t),i=this.renderingQueue.getHighestPriority(t,this._thumbnails,e);if(i){this.#cc(i).then((()=>{this.renderingQueue.renderView(i)}));return!0}return!1}stopRendering(){this.#dc()}}class Page{constructor(t,e){this.state={angle:0,area:[],position:{x:0,y:0},hardAngle:0,hardDrawingAngle:0};this.createdDensity=e;this.nowDrawingDensity=this.createdDensity;this.render=t}setDensity(t){this.createdDensity=t;this.nowDrawingDensity=t}setDrawingDensity(t){this.nowDrawingDensity=t}setPosition(t){this.state.position=t}setAngle(t){this.state.angle=t}setArea(t){this.state.area=t}setHardDrawingAngle(t){this.state.hardDrawingAngle=t}setHardAngle(t){this.state.hardAngle=t;this.state.hardDrawingAngle=t}setOrientation(t){this.orientation=t}getDrawingDensity(){return this.nowDrawingDensity}getDensity(){return this.createdDensity}getHardAngle(){return this.state.hardAngle}}class PageCollection{constructor(t,e){this.pages=[];this.currentPageIndex=0;this.currentSpreadIndex=0;this.landscapeSpread=[];this.portraitSpread=[];this.render=e;this.app=t;this.currentPageIndex=0;this.isShowCover=this.app.getSettings().showCover}destroy(){this.pages=[]}createSpread(){this.landscapeSpread=[];this.portraitSpread=[];for(let t=0;t<this.pages.length;t++)this.portraitSpread.push([t]);let t=0;if(this.isShowCover){this.pages[0].setDensity("hard");this.landscapeSpread.push([t]);t++}for(let e=t;e<this.pages.length;e+=2)if(e<this.pages.length-1)this.landscapeSpread.push([e,e+1]);else{this.landscapeSpread.push([e]);this.pages[e].setDensity("hard")}}getSpread(){return"landscape"===this.render.getOrientation()?this.landscapeSpread:this.portraitSpread}getSpreadIndexByPage(t){const e=this.getSpread();for(let i=0;i<e.length;i++)if(t===e[i][0]||t===e[i][1])return i;return null}getPageCount(){return this.pages.length}getPages(){return this.pages}getPage(t){if(t>=0&&t<this.pages.length)return this.pages[t];throw new Error("Invalid page number")}nextBy(t){const e=this.pages.indexOf(t);return e<this.pages.length-1?this.pages[e+1]:null}prevBy(t){const e=this.pages.indexOf(t);return e>0?this.pages[e-1]:null}getFlippingPage(t){const e=this.currentSpreadIndex;if("portrait"===this.render.getOrientation())return 0===t?this.pages[e].newTemporaryCopy():this.pages[e-1];{const i=0===t?this.getSpread()[e+1]:this.getSpread()[e-1];return 1===i.length||0===t?this.pages[i[0]]:this.pages[i[1]]}}getBottomPage(t){const e=this.currentSpreadIndex;if("portrait"===this.render.getOrientation())return 0===t?this.pages[e+1]:this.pages[e-1];{const i=0===t?this.getSpread()[e+1]:this.getSpread()[e-1];return 1===i.length?this.pages[i[0]]:0===t?this.pages[i[1]]:this.pages[i[0]]}}showNext(){if(this.currentSpreadIndex<this.getSpread().length){this.currentSpreadIndex++;this.showSpread()}}showPrev(){if(this.currentSpreadIndex>0){this.currentSpreadIndex--;this.showSpread()}}getCurrentPageIndex(){return this.currentPageIndex}show(t=null){null===t&&(t=this.currentPageIndex);if(t<0||t>=this.pages.length)return;const e=this.getSpreadIndexByPage(t);if(null!==e){this.currentSpreadIndex=e;this.showSpread()}}getCurrentSpreadIndex(){return this.currentSpreadIndex}setCurrentSpreadIndex(t){if(!(t>=0&&t<this.getSpread().length))throw new Error("Invalid page");this.currentSpreadIndex=t}showSpread(){const t=this.getSpread()[this.currentSpreadIndex];if(2===t.length){this.render.setLeftPage(this.pages[t[0]]);this.render.setRightPage(this.pages[t[1]])}else if("landscape"===this.render.getOrientation())if(t[0]===this.pages.length-1){this.render.setLeftPage(this.pages[t[0]]);this.render.setRightPage(null)}else{this.render.setLeftPage(null);this.render.setRightPage(this.pages[t[0]])}else{this.render.setLeftPage(null);this.render.setRightPage(this.pages[t[0]])}this.currentPageIndex=t[0];this.app.updatePageIndex(this.currentPageIndex)}}class Helper{static GetDistanceBetweenTwoPoint(t,e){return null===t||null===e?1/0:Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}static GetSegmentLength(t){return Helper.GetDistanceBetweenTwoPoint(t[0],t[1])}static GetAngleBetweenTwoLine(t,e){const i=t[0].y-t[1].y,n=e[0].y-e[1].y,s=t[1].x-t[0].x,a=e[1].x-e[0].x;return Math.acos((i*n+s*a)/(Math.sqrt(i*i+s*s)*Math.sqrt(n*n+a*a)))}static PointInRect(t,e){return null===e?null:e.x>=t.left&&e.x<=t.width+t.left&&e.y>=t.top&&e.y<=t.top+t.height?e:null}static GetRotatedPoint(t,e,i){return{x:t.x*Math.cos(i)+t.y*Math.sin(i)+e.x,y:t.y*Math.cos(i)-t.x*Math.sin(i)+e.y}}static LimitPointToCircle(t,e,i){if(Helper.GetDistanceBetweenTwoPoint(t,i)<=e)return i;const n=t.x,s=t.y,a=i.x,r=i.y;let o=Math.sqrt(Math.pow(e,2)*Math.pow(n-a,2)/(Math.pow(n-a,2)+Math.pow(s-r,2)))+n;i.x<0&&(o*=-1);let l=(o-n)*(s-r)/(n-a)+s;n-a+s===0&&(l=e);return{x:o,y:l}}static GetIntersectBetweenTwoSegment(t,e,i){return Helper.PointInRect(t,Helper.GetIntersectBeetwenTwoLine(e,i))}static GetIntersectBeetwenTwoLine(t,e){const i=t[0].y-t[1].y,n=e[0].y-e[1].y,s=t[1].x-t[0].x,a=e[1].x-e[0].x,r=t[0].x*t[1].y-t[1].x*t[0].y,o=e[0].x*e[1].y-e[1].x*e[0].y,l=i*o-n*r,h=s*o-a*r,d=-(r*a-o*s)/(i*a-n*s),c=-(i*o-n*r)/(i*a-n*s);if(isFinite(d)&&isFinite(c))return{x:d,y:c};if(Math.abs(l-h)<.1)throw new Error("Segment included");return null}static GetCordsFromTwoPoint(t,e){const i=Math.abs(t.x-e.x),n=Math.abs(t.y-e.y),s=Math.max(i,n),a=[t];function getCord(t,e,i,n,s){return e>t?t+s*(i/n):e<t?t-s*(i/n):t}for(let r=1;r<=s;r+=1)a.push({x:getCord(t.x,e.x,i,s,r),y:getCord(t.y,e.y,n,s,r)});return a}}class HTMLPage extends Page{constructor(t,e,i){super(t,i);this.copiedElement=null;this.temporaryCopy=null;this.isLoad=!1;this.element=e;this.element.classList.add("stf__item");this.element.classList.add("--"+i)}newTemporaryCopy(){if("hard"===this.nowDrawingDensity)return this;if(null===this.temporaryCopy){this.copiedElement=this.element.cloneNode(!0);this.element.parentElement.appendChild(this.copiedElement);this.temporaryCopy=new HTMLPage(this.render,this.copiedElement,this.nowDrawingDensity)}return this.getTemporaryCopy()}getTemporaryCopy(){return this.temporaryCopy}hideTemporaryCopy(){if(null!==this.temporaryCopy){this.copiedElement.remove();this.copiedElement=null;this.temporaryCopy=null}}draw(t){const e=t||this.nowDrawingDensity,i=this.render.convertToGlobal(this.state.position),n=this.render.getRect().pageWidth,s=this.render.getRect().height;this.element.classList.remove("--simple");const a=`\n position: absolute;\n display: block;\n z-index: ${this.element.style.zIndex};\n left: 0;\n top: 0;\n width: ${n}px;\n height: ${s}px;\n `;"hard"===e?this.drawHard(a):this.drawSoft(i,a)}drawHard(t=""){const e=this.render.getRect().left+this.render.getRect().width/2,i=this.state.hardDrawingAngle,n=t+"\n backface-visibility: hidden;\n -webkit-backface-visibility: hidden;\n clip-path: none;\n -webkit-clip-path: none;\n "+(0===this.orientation?`transform-origin: ${this.render.getRect().pageWidth}px 0;\n transform: translate3d(0, 0, 0) rotateY(${i}deg);`:`transform-origin: 0 0;\n transform: translate3d(${e}px, 0, 0) rotateY(${i}deg);`);this.element.style.cssText=n}drawSoft(t,e=""){let i="polygon( ";for(const t of this.state.area)if(null!==t){let e=1===this.render.getDirection()?{x:-t.x+this.state.position.x,y:t.y-this.state.position.y}:{x:t.x-this.state.position.x,y:t.y-this.state.position.y};e=Helper.GetRotatedPoint(e,{x:0,y:0},this.state.angle);i+=e.x+"px "+e.y+"px, "}i=i.slice(0,-2);i+=")";const n=e+`transform-origin: 0 0; clip-path: ${i}; -webkit-clip-path: ${i};`+(this.render.isSafari()&&0===this.state.angle?`transform: translate(${t.x}px, ${t.y}px);`:`transform: translate3d(${t.x}px, ${t.y}px, 0) rotate(${this.state.angle}rad);`);this.element.style.cssText=n}simpleDraw(t){const e=this.render.getRect(),i=e.pageWidth,n=e.height,s=1===t?e.left+e.pageWidth:e.left,a=e.top;this.element.classList.add("--simple");this.element.style.cssText=`\n position: absolute;\n display: block;\n height: ${n}px;\n left: ${s}px;\n top: ${a}px;\n width: ${i}px;\n z-index: ${this.render.getSettings().startZIndex+1};`}getElement(){return this.element}load(){this.isLoad=!0}setOrientation(t){super.setOrientation(t);this.element.classList.remove("--left","--right");this.element.classList.add(1===t?"--right":"--left")}setDrawingDensity(t){this.element.classList.remove("--soft","--hard");this.element.classList.add("--"+t);super.setDrawingDensity(t)}}class HTMLPageCollection extends PageCollection{constructor(t,e,i,n){super(t,e);this.element=i;this.pagesElement=n}load(){for(const t of this.pagesElement){const e=new HTMLPage(this.render,t,"hard"===t.dataset.density?"hard":"soft");e.load();this.pages.push(e)}this.createSpread()}}class FlipCalculation{constructor(t,e,i,n){this.direction=t;this.corner=e;this.topIntersectPoint=null;this.sideIntersectPoint=null;this.bottomIntersectPoint=null;this.pageWidth=parseInt(i,10);this.pageHeight=parseInt(n,10)}calc(t){try{this.position=this.calcAngleAndPosition(t);this.calculateIntersectPoint(this.position);return!0}catch(t){return!1}}getFlippingClipArea(){const t=[];let e=!1;t.push(this.rect.topLeft);t.push(this.topIntersectPoint);if(null===this.sideIntersectPoint)e=!0;else{t.push(this.sideIntersectPoint);null===this.bottomIntersectPoint&&(e=!1)}t.push(this.bottomIntersectPoint);(e||"bottom"===this.corner)&&t.push(this.rect.bottomLeft);return t}getBottomClipArea(){const t=[];t.push(this.topIntersectPoint);if("top"===this.corner)t.push({x:this.pageWidth,y:0});else{null!==this.topIntersectPoint&&t.push({x:this.pageWidth,y:0});t.push({x:this.pageWidth,y:this.pageHeight})}null!==this.sideIntersectPoint?Helper.GetDistanceBetweenTwoPoint(this.sideIntersectPoint,this.topIntersectPoint)>=10&&t.push(this.sideIntersectPoint):"top"===this.corner&&t.push({x:this.pageWidth,y:this.pageHeight});t.push(this.bottomIntersectPoint);t.push(this.topIntersectPoint);return t}getAngle(){return 0===this.direction?-this.angle:this.angle}getRect(){return this.rect}getPosition(){return this.position}getActiveCorner(){return 0===this.direction?this.rect.topLeft:this.rect.topRight}getDirection(){return this.direction}getFlippingProgress(){return Math.abs((this.position.x-this.pageWidth)/(2*this.pageWidth)*100)}getCorner(){return this.corner}getBottomPagePosition(){return 1===this.direction?{x:this.pageWidth,y:0}:{x:0,y:0}}getShadowStartPoint(){return"top"===this.corner?this.topIntersectPoint:null!==this.sideIntersectPoint?this.sideIntersectPoint:this.topIntersectPoint}getShadowAngle(){const t=Helper.GetAngleBetweenTwoLine(this.getSegmentToShadowLine(),[{x:0,y:0},{x:this.pageWidth,y:0}]);return 0===this.direction?t:Math.PI-t}calcAngleAndPosition(t){let e=t;this.updateAngleAndGeometry(e);e="top"===this.corner?this.checkPositionAtCenterLine(e,{x:0,y:0},{x:0,y:this.pageHeight}):this.checkPositionAtCenterLine(e,{x:0,y:this.pageHeight},{x:0,y:0});if(Math.abs(e.x-this.pageWidth)<1&&Math.abs(e.y)<1)throw new Error("Point is too small");return e}updateAngleAndGeometry(t){this.angle=this.calculateAngle(t);this.rect=this.getPageRect(t)}calculateAngle(t){const e=this.pageWidth-t.x+1,i="bottom"===this.corner?this.pageHeight-t.y:t.y;let n=2*Math.acos(e/Math.sqrt(i*i+e*e));i<0&&(n=-n);const s=Math.PI-n;if(!isFinite(n)||s>=0&&s<.003)throw new Error("The G point is too small");"bottom"===this.corner&&(n=-n);return n}getPageRect(t){return"top"===this.corner?this.getRectFromBasePoint([{x:0,y:0},{x:this.pageWidth,y:0},{x:0,y:this.pageHeight},{x:this.pageWidth,y:this.pageHeight}],t):this.getRectFromBasePoint([{x:0,y:-this.pageHeight},{x:this.pageWidth,y:-this.pageHeight},{x:0,y:0},{x:this.pageWidth,y:0}],t)}getRectFromBasePoint(t,e){return{topLeft:this.getRotatedPoint(t[0],e),topRight:this.getRotatedPoint(t[1],e),bottomLeft:this.getRotatedPoint(t[2],e),bottomRight:this.getRotatedPoint(t[3],e)}}getRotatedPoint(t,e){return{x:t.x*Math.cos(this.angle)+t.y*Math.sin(this.angle)+e.x,y:t.y*Math.cos(this.angle)-t.x*Math.sin(this.angle)+e.y}}calculateIntersectPoint(t){const e={left:-1,top:-1,width:this.pageWidth+2,height:this.pageHeight+2};if("top"===this.corner){this.topIntersectPoint=Helper.GetIntersectBetweenTwoSegment(e,[t,this.rect.topRight],[{x:0,y:0},{x:this.pageWidth,y:0}]);this.sideIntersectPoint=Helper.GetIntersectBetweenTwoSegment(e,[t,this.rect.bottomLeft],[{x:this.pageWidth,y:0},{x:this.pageWidth,y:this.pageHeight}]);this.bottomIntersectPoint=Helper.GetIntersectBetweenTwoSegment(e,[this.rect.bottomLeft,this.rect.bottomRight],[{x:0,y:this.pageHeight},{x:this.pageWidth,y:this.pageHeight}])}else{this.topIntersectPoint=Helper.GetIntersectBetweenTwoSegment(e,[this.rect.topLeft,this.rect.topRight],[{x:0,y:0},{x:this.pageWidth,y:0}]);this.sideIntersectPoint=Helper.GetIntersectBetweenTwoSegment(e,[t,this.rect.topLeft],[{x:this.pageWidth,y:0},{x:this.pageWidth,y:this.pageHeight}]);this.bottomIntersectPoint=Helper.GetIntersectBetweenTwoSegment(e,[this.rect.bottomLeft,this.rect.bottomRight],[{x:0,y:this.pageHeight},{x:this.pageWidth,y:this.pageHeight}])}}checkPositionAtCenterLine(t,e,i){let n=t;const s=Helper.LimitPointToCircle(e,this.pageWidth,n);if(n!==s){n=s;this.updateAngleAndGeometry(n)}const a=Math.sqrt(Math.pow(this.pageWidth,2)+Math.pow(this.pageHeight,2));let r=this.rect.bottomRight,o=this.rect.topLeft;if("bottom"===this.corner){r=this.rect.topRight;o=this.rect.bottomLeft}if(r.x<=0){const t=Helper.LimitPointToCircle(i,a,o);if(t!==n){n=t;this.updateAngleAndGeometry(n)}}return n}getSegmentToShadowLine(){const t=this.getShadowStartPoint();return[t,t!==this.sideIntersectPoint&&null!==this.sideIntersectPoint?this.sideIntersectPoint:this.bottomIntersectPoint]}}class Flip{constructor(t,e){this.flippingPage=null;this.bottomPage=null;this.calc=null;this.state="read";this.render=t;this.app=e}fold(t){this.setState("user_fold");null===this.calc&&this.start(t);this.do(this.render.convertToPage(t))}flip(t){if(this.app.getSettings().disableFlipByClick&&!this.isPointOnCorners(t))return;null!==this.calc&&this.render.finishAnimation();if(!this.start(t))return;const e=this.getBoundsRect();this.setState("flipping");const i=e.height/10,n="bottom"===this.calc.getCorner()?e.height-i:i,s="bottom"===this.calc.getCorner()?e.height:0;this.calc.calc({x:e.pageWidth-i,y:n});this.animateFlippingTo({x:e.pageWidth-i,y:n},{x:-e.pageWidth,y:s},!0)}start(t){this.reset();const e=this.render.convertToBook(t),i=this.getBoundsRect(),n=this.getDirectionByPoint(e),s=e.y>=i.height/2?"bottom":"top";if(!this.checkDirection(n))return!1;try{this.flippingPage=this.app.getPageCollection().getFlippingPage(n);this.bottomPage=this.app.getPageCollection().getBottomPage(n);if("landscape"===this.render.getOrientation())if(1===n){const t=this.app.getPageCollection().nextBy(this.flippingPage);if(null!==t&&this.flippingPage.getDensity()!==t.getDensity()){this.flippingPage.setDrawingDensity("hard");t.setDrawingDensity("hard")}}else{const t=this.app.getPageCollection().prevBy(this.flippingPage);if(null!==t&&this.flippingPage.getDensity()!==t.getDensity()){this.flippingPage.setDrawingDensity("hard");t.setDrawingDensity("hard")}}this.render.setDirection(n);this.calc=new FlipCalculation(n,s,i.pageWidth.toString(10),i.height.toString(10));return!0}catch(t){return!1}}do(t){if(null!==this.calc&&this.calc.calc(t)){const t=this.calc.getFlippingProgress();this.bottomPage.setArea(this.calc.getBottomClipArea());this.bottomPage.setPosition(this.calc.getBottomPagePosition());this.bottomPage.setAngle(0);this.bottomPage.setHardAngle(0);this.flippingPage.setArea(this.calc.getFlippingClipArea());this.flippingPage.setPosition(this.calc.getActiveCorner());this.flippingPage.setAngle(this.calc.getAngle());0===this.calc.getDirection()?this.flippingPage.setHardAngle(90*(200-2*t)/100):this.flippingPage.setHardAngle(-90*(200-2*t)/100);this.render.setPageRect(this.calc.getRect());this.render.setBottomPage(this.bottomPage);this.render.setFlippingPage(this.flippingPage);this.render.setShadowData(this.calc.getShadowStartPoint(),this.calc.getShadowAngle(),t,this.calc.getDirection())}}flipToPage(t,e){const i=this.app.getPageCollection().getCurrentSpreadIndex(),n=this.app.getPageCollection().getSpreadIndexByPage(t);try{if(n>i){this.app.getPageCollection().setCurrentSpreadIndex(n-1);this.flipNext(e)}if(n<i){this.app.getPageCollection().setCurrentSpreadIndex(n+1);this.flipPrev(e)}}catch(t){}}flipNext(t){this.flip({x:this.render.getRect().left+2*this.render.getRect().pageWidth-10,y:"top"===t?1:this.render.getRect().height-2})}flipPrev(t){this.flip({x:10,y:"top"===t?1:this.render.getRect().height-2})}stopMove(){if(null===this.calc)return;const t=this.calc.getPosition(),e=this.getBoundsRect(),i="bottom"===this.calc.getCorner()?e.height:0;t.x<=0?this.animateFlippingTo(t,{x:-e.pageWidth,y:i},!0):this.animateFlippingTo(t,{x:e.pageWidth,y:i},!1)}showCorner(t){if(!this.checkState("read","fold_corner"))return;const e=this.getBoundsRect(),i=e.pageWidth;if(this.isPointOnCorners(t))if(null===this.calc){if(!this.start(t))return;this.setState("fold_corner");this.calc.calc({x:i-1,y:1});const n=50,s="bottom"===this.calc.getCorner()?e.height-1:1,a="bottom"===this.calc.getCorner()?e.height-n:n;this.animateFlippingTo({x:i-1,y:s},{x:i-n,y:a},!1,!1)}else this.do(this.render.convertToPage(t));else{this.setState("read");this.render.finishAnimation();this.stopMove()}}animateFlippingTo(t,e,i,n=!0){const s=Helper.GetCordsFromTwoPoint(t,e),a=[];for(const t of s)a.push((()=>this.do(t)));const r=this.getAnimationDuration(s.length);this.render.startAnimation(a,r,(()=>{if(this.calc){i&&(1===this.calc.getDirection()?this.app.turnToPrevPage():this.app.turnToNextPage());if(n){this.render.setBottomPage(null);this.render.setFlippingPage(null);this.render.clearShadow();this.setState("read");this.reset()}}}))}getCalculation(){return this.calc}getState(){return this.state}setState(t){if(this.state!==t){this.app.updateState(t);this.state=t}}getDirectionByPoint(t){const e=this.getBoundsRect();if("portrait"===this.render.getOrientation()){if(t.x-e.pageWidth<=e.width/5)return 1}else if(t.x<e.width/2)return 1;return 0}getAnimationDuration(t){const e=this.app.getSettings().flippingTime;return t>=1e3?e:t/1e3*e}checkDirection(t){return 0===t?this.app.getCurrentPageIndex()<this.app.getPageCount()-1:this.app.getCurrentPageIndex()>=1}reset(){this.calc=null;this.flippingPage=null;this.bottomPage=null}getBoundsRect(){return this.render.getRect()}checkState(...t){for(const e of t)if(this.state===e)return!0;return!1}isPointOnCorners(t){const e=this.getBoundsRect(),i=e.pageWidth,n=Math.sqrt(Math.pow(i,2)+Math.pow(e.height,2))/5,s=this.render.convertToBook(t);return s.x>0&&s.y>0&&s.x<e.width&&s.y<e.height&&(s.x<n||s.x>e.width-n)&&(s.y<n||s.y>e.height-n)}}class Render{constructor(t,e){this.leftPage=null;this.rightPage=null;this.flippingPage=null;this.bottomPage=null;this.direction=null;this.orientation=null;this.shadow=null;this.animation=null;this.pageRect=null;this.boundsRect=null;this.timer=0;this.safari=!1;this.setting=e;this.app=t;const i=new RegExp("Version\\/[\\d\\.]+.*Safari/");this.safari=null!==i.exec(window.navigator.userAgent)}render(t){if(null!==this.animation){const e=Math.round((t-this.animation.startedAt)/this.animation.durationFrame);if(e<this.animation.frames.length)this.animation.frames[e]();else{this.animation.onAnimateEnd();this.animation=null}}this.timer=t;this.drawFrame()}start(){this.update();const loop=t=>{this.render(t);requestAnimationFrame(loop)};requestAnimationFrame(loop)}startAnimation(t,e,i){this.finishAnimation();this.animation={frames:t,duration:e,durationFrame:e/t.length,onAnimateEnd:i,startedAt:this.timer}}finishAnimation(){if(null!==this.animation){this.animation.frames[this.animation.frames.length-1]();null!==this.animation.onAnimateEnd&&this.animation.onAnimateEnd()}this.animation=null}update(){this.boundsRect=null;const t=this.calculateBoundsRect();if(this.orientation!==t){this.orientation=t;this.app.updateOrientation(t)}}calculateBoundsRect(){let t="landscape";const e=this.getBlockWidth(),i=e/2,n=this.getBlockHeight()/2,s=this.setting.width/this.setting.height;let a=this.setting.width,r=this.setting.height,o=i-a;if("stretch"===this.setting.size){e<2*this.setting.minWidth&&this.app.getSettings().usePortrait&&(t="portrait");a="portrait"===t?this.getBlockWidth():this.getBlockWidth()/2;a>this.setting.maxWidth&&(a=this.setting.maxWidth);r=a/s;if(r>this.getBlockHeight()){r=this.getBlockHeight();a=r*s}o="portrait"===t?i-a/2-a:i-a}else if(e<2*a&&this.app.getSettings().usePortrait){t="portrait";o=i-a/2-a}this.boundsRect={left:o,top:n-r/2,width:2*a,height:r,pageWidth:a};return t}setShadowData(t,e,i,n){if(!this.app.getSettings().drawShadow)return;const s=100*this.getSettings().maxShadowOpacity;this.shadow={pos:t,angle:e,width:3*this.getRect().pageWidth/4*i/100,opacity:(100-i)*s/100/100,direction:n,progress:2*i}}clearShadow(){this.shadow=null}getBlockWidth(){return this.app.getUI().getDistElement().offsetWidth}getBlockHeight(){return this.app.getUI().getDistElement().offsetHeight}getDirection(){return this.direction}getRect(){null===this.boundsRect&&this.calculateBoundsRect();return this.boundsRect}getSettings(){return this.app.getSettings()}getOrientation(){return this.orientation}setPageRect(t){this.pageRect=t}setDirection(t){this.direction=t}setRightPage(t){null!==t&&t.setOrientation(1);this.rightPage=t}setLeftPage(t){null!==t&&t.setOrientation(0);this.leftPage=t}setBottomPage(t){null!==t&&t.setOrientation(1===this.direction?0:1);this.bottomPage=t}setFlippingPage(t){null!==t&&t.setOrientation(0===this.direction&&"portrait"!==this.orientation?0:1);this.flippingPage=t}convertToBook(t){const e=this.getRect();return{x:t.x-e.left,y:t.y-e.top}}isSafari(){return this.safari}convertToPage(t,e){e||(e=this.direction);const i=this.getRect();return{x:0===e?t.x-i.left-i.width/2:i.width/2-t.x+i.left,y:t.y-i.top}}convertToGlobal(t,e){e||(e=this.direction);if(null==t)return null;const i=this.getRect();return{x:0===e?t.x+i.left+i.width/2:i.width/2-t.x+i.left,y:t.y+i.top}}convertRectToGlobal(t,e){e||(e=this.direction);return{topLeft:this.convertToGlobal(t.topLeft,e),topRight:this.convertToGlobal(t.topRight,e),bottomLeft:this.convertToGlobal(t.bottomLeft,e),bottomRight:this.convertToGlobal(t.bottomRight,e)}}}class UI{constructor(t,e,i){this.cspPolicyService=e.cspPolicyService;this.touchPoint=null;this.swipeTimeout=250;this.onResize=()=>{this.update()};this.onMouseDown=t=>{if(this.checkTarget(t.target)){const e=this.getMousePos(t.clientX,t.clientY);this.app.startUserTouch(e);t.preventDefault()}};this.onTouchStart=t=>{if(this.checkTarget(t.target)&&t.changedTouches.length>0){const e=t.changedTouches[0],i=this.getMousePos(e.clientX,e.clientY);this.touchPoint={point:i,time:Date.now()};setTimeout((()=>{null!==this.touchPoint&&this.app.startUserTouch(i)}),this.swipeTimeout);this.app.getSettings().mobileScrollSupport||t.preventDefault()}};this.onMouseUp=t=>{const e=this.getMousePos(t.clientX,t.clientY);this.app.userStop(e)};this.onMouseMove=t=>{const e=this.getMousePos(t.clientX,t.clientY);this.app.userMove(e,!1)};this.onTouchMove=t=>{if(t.changedTouches.length>0){const e=t.changedTouches[0],i=this.getMousePos(e.clientX,e.clientY);if(this.app.getSettings().mobileScrollSupport){null!==this.touchPoint&&(Math.abs(this.touchPoint.point.x-i.x)>10||"read"!==this.app.getState())&&t.cancelable&&this.app.userMove(i,!0);"read"!==this.app.getState()&&t.preventDefault()}else this.app.userMove(i,!0)}};this.onTouchEnd=t=>{if(t.changedTouches.length>0){const e=t.changedTouches[0],i=this.getMousePos(e.clientX,e.clientY);let n=!1;if(null!==this.touchPoint){const t=i.x-this.touchPoint.point.x,e=Math.abs(i.y-this.touchPoint.point.y);if(Math.abs(t)>this.swipeDistance&&e<2*this.swipeDistance&&Date.now()-this.touchPoint.time<this.swipeTimeout){t>0?this.app.flipPrev(this.touchPoint.point.y<this.app.getRender().getRect().height/2?"top":"bottom"):this.app.flipNext(this.touchPoint.point.y<this.app.getRender().getRect().height/2?"top":"bottom");n=!0}this.touchPoint=null}this.app.userStop(i,n)}};this.parentElement=t;t.classList.add("stf__parent");const n=this.cspPolicyService.createTrustedHTML('<div class="stf__wrapper"></div>');t.insertAdjacentHTML("afterbegin",n);this.wrapper=t.querySelector(".stf__wrapper");this.app=e;const s=this.app.getSettings().usePortrait?1:2;t.style.minWidth=i.minWidth*s+"px";t.style.minHeight=i.minHeight+"px";if("fixed"===i.size){t.style.minWidth=i.width*s+"px";t.style.minHeight=i.height+"px"}if(i.autoSize){t.style.width="100%";t.style.maxWidth=2*i.maxWidth+"px"}t.style.display="block";window.addEventListener("resize",this.onResize,!1);this.swipeDistance=i.swipeDistance}destroy(){this.app.getSettings().useMouseEvents&&this.removeHandlers();this.distElement.remove();this.wrapper.remove()}getDistElement(){return this.distElement}getWrapper(){return this.wrapper}setOrientationStyle(t){this.wrapper.classList.remove("--portrait","--landscape");if("portrait"===t){this.app.getSettings().autoSize&&(this.wrapper.style.paddingBottom=this.app.getSettings().height/this.app.getSettings().width*100+"%");this.wrapper.classList.add("--portrait")}else{this.app.getSettings().autoSize&&(this.wrapper.style.paddingBottom=this.app.getSettings().height/(2*this.app.getSettings().width)*100+"%");this.wrapper.classList.add("--landscape")}this.update()}removeHandlers(){window.removeEventListener("resize",this.onResize);this.distElement.removeEventListener("mousedown",this.onMouseDown);this.distElement.removeEventListener("touchstart",this.onTouchStart);window.removeEventListener("mousemove",this.onMouseMove);window.removeEventListener("touchmove",this.onTouchMove);window.removeEventListener("mouseup",this.onMouseUp);window.removeEventListener("touchend",this.onTouchEnd)}setHandlers(){window.addEventListener("resize",this.onResize,!1);if(this.app.getSettings().useMouseEvents){this.distElement.addEventListener("mousedown",this.onMouseDown);this.distElement.addEventListener("touchstart",this.onTouchStart);window.addEventListener("mousemove",this.onMouseMove);window.addEventListener("touchmove",this.onTouchMove,{passive:!this.app.getSettings().mobileScrollSupport});window.addEventListener("mouseup",this.onMouseUp);window.addEventListener("touchend",this.onTouchEnd)}}getMousePos(t,e){const i=this.distElement.getBoundingClientRect();return{x:t-i.left,y:e-i.top}}checkTarget(t){return!this.app.getSettings().clickEventForward||!["a","button"].includes(t.tagName.toLowerCase())}}class HTMLUI extends UI{constructor(t,e,i,n,s){super(t,e,i);this.cspPolicyService=s;const a=this.cspPolicyService.createTrustedHTML('<div class="stf__block"></div>');this.wrapper.insertAdjacentHTML("afterbegin",a);this.distElement=t.querySelector(".stf__block");this.items=n;for(const t of n)this.distElement.appendChild(t);this.setHandlers()}clear(){for(const t of this.items)this.parentElement.appendChild(t)}updateItems(t){this.removeHandlers();this.distElement.innerHTML="";for(const e of t)this.distElement.appendChild(e);this.items=t;this.setHandlers()}update(){this.app.getRender().update()}}class EventObject{constructor(){this.events=new Map}on(t,e){this.events.has(t)?this.events.get(t).push(e):this.events.set(t,[e]);return this}off(t){this.events.delete(t)}trigger(t,e,i=null){if(this.events.has(t))for(const n of this.events.get(t))n({data:i,object:e})}}class HTMLRender extends Render{constructor(t,e,i){super(t,e);this.outerShadow=null;this.innerShadow=null;this.hardShadow=null;this.hardInnerShadow=null;this.element=i;this.createShadows()}createShadows(){const t=this.app.cspPolicyService.createTrustedHTML('<div class="stf__outerShadow"></div>\n <div class="stf__innerShadow"></div>\n <div class="stf__hardShadow"></div>\n <div class="stf__hardInnerShadow"></div>');this.element.insertAdjacentHTML("beforeend",t);this.outerShadow=this.element.querySelector(".stf__outerShadow");this.innerShadow=this.element.querySelector(".stf__innerShadow");this.hardShadow=this.element.querySelector(".stf__hardShadow");this.hardInnerShadow=this.element.querySelector(".stf__hardInnerShadow")}clearShadow(){super.clearShadow();this.outerShadow.style.cssText="display: none";this.innerShadow.style.cssText="display: none";this.hardShadow.style.cssText="display: none";this.hardInnerShadow.style.cssText="display: none"}reload(){this.element.querySelector(".stf__outerShadow")||this.createShadows()}drawHardInnerShadow(){const t=this.getRect(),e=this.shadow.progress>100?200-this.shadow.progress:this.shadow.progress;let i=(100-e)*(2.5*t.pageWidth)/100+20;i>t.pageWidth&&(i=t.pageWidth);let n=`\n display: block;\n z-index: ${(this.getSettings().startZIndex+5).toString(10)};\n width: ${i}px;\n height: ${t.height}px;\n background: linear-gradient(to right,\n rgba(0, 0, 0, ${this.shadow.opacity*e/100}) 5%,\n rgba(0, 0, 0, 0) 100%);\n left: ${t.left+t.width/2}px;\n transform-origin: 0 0;\n `;n+=0===this.getDirection()&&this.shadow.progress>100||1===this.getDirection()&&this.shadow.progress<=100?"transform: translate3d(0, 0, 0);":"transform: translate3d(0, 0, 0) rotateY(180deg);";this.hardInnerShadow.style.cssText=n}drawHardOuterShadow(){const t=this.getRect();let e=(100-(this.shadow.progress>100?200-this.shadow.progress:this.shadow.progress))*(2.5*t.pageWidth)/100+20;e>t.pageWidth&&(e=t.pageWidth);let i=`\n display: block;\n z-index: ${(this.getSettings().startZIndex+4).toString(10)};\n width: ${e}px;\n height: ${t.height}px;\n background: linear-gradient(to left, rgba(0, 0, 0, ${this.shadow.opacity}) 5%, rgba(0, 0, 0, 0) 100%);\n left: ${t.left+t.width/2}px;\n transform-origin: 0 0;\n `;i+=0===this.getDirection()&&this.shadow.progress>100||1===this.getDirection()&&this.shadow.progress<=100?"transform: translate3d(0, 0, 0) rotateY(180deg);":"transform: translate3d(0, 0, 0);";this.hardShadow.style.cssText=i}drawInnerShadow(){const t=this.getRect(),e=3*this.shadow.width/4,i=0===this.getDirection()?e:0,n=0===this.getDirection()?"to left":"to right",s=this.convertToGlobal(this.shadow.pos),a=this.shadow.angle+3*Math.PI/2,r=[this.pageRect.topLeft,this.pageRect.topRight,this.pageRect.bottomRight,this.pageRect.bottomLeft];let o="polygon( ";for(const t of r){let e=1===this.getDirection()?{x:-t.x+this.shadow.pos.x,y:t.y-this.shadow.pos.y}:{x:t.x-this.shadow.pos.x,y:t.y-this.shadow.pos.y};e=Helper.GetRotatedPoint(e,{x:i,y:100},a);o+=e.x+"px "+e.y+"px, "}o=o.slice(0,-2);o+=")";const l=`\n display: block;\n z-index: ${(this.getSettings().startZIndex+10).toString(10)};\n width: ${e}px;\n height: ${2*t.height}px;\n background: linear-gradient(${n},\n rgba(0, 0, 0, ${this.shadow.opacity}) 5%,\n rgba(0, 0, 0, 0.05) 15%,\n rgba(0, 0, 0, ${this.shadow.opacity}) 35%,\n rgba(0, 0, 0, 0) 100%);\n transform-origin: ${i}px 100px;\n transform: translate3d(${s.x-i}px, ${s.y-100}px, 0) rotate(${a}rad);\n clip-path: ${o};\n -webkit-clip-path: ${o};\n `;this.innerShadow.style.cssText=l}drawOuterShadow(){const t=this.getRect(),e=this.convertToGlobal({x:this.shadow.pos.x,y:this.shadow.pos.y}),i=this.shadow.angle+3*Math.PI/2,n=1===this.getDirection()?this.shadow.width:0,s=0===this.getDirection()?"to right":"to left",a=[{x:0,y:0},{x:t.pageWidth,y:0},{x:t.pageWidth,y:t.height},{x:0,y:t.height}];let r="polygon( ";for(const t of a)if(null!==t){let e=1===this.getDirection()?{x:-t.x+this.shadow.pos.x,y:t.y-this.shadow.pos.y}:{x:t.x-this.shadow.pos.x,y:t.y-this.shadow.pos.y};e=Helper.GetRotatedPoint(e,{x:n,y:100},i);r+=e.x+"px "+e.y+"px, "}r=r.slice(0,-2);r+=")";const o=`\n display: block;\n z-index: ${(this.getSettings().startZIndex+10).toString(10)};\n width: ${this.shadow.width}px;\n height: ${2*t.height}px;\n background: linear-gradient(${s}, rgba(0, 0, 0, ${this.shadow.opacity}), rgba(0, 0, 0, 0));\n transform-origin: ${n}px 100px;\n transform: translate3d(${e.x-n}px, ${e.y-100}px, 0) rotate(${i}rad);\n clip-path: ${r};\n -webkit-clip-path: ${r};\n `;this.outerShadow.style.cssText=o}drawLeftPage(){if("portrait"!==this.orientation&&null!==this.leftPage)if(1===this.direction&&null!==this.flippingPage&&"hard"===this.flippingPage.getDrawingDensity()){if(this.flippingPage.getHardAngle()<-90){this.leftPage.getElement().style.zIndex=(this.getSettings().startZIndex+5).toString(10);this.leftPage.setHardDrawingAngle(180+this.flippingPage.getHardAngle());this.leftPage.draw(this.flippingPage.getDrawingDensity())}else this.leftPage.getElement().style.display="none"}else this.leftPage.simpleDraw(0)}drawRightPage(){if(null!==this.rightPage)if(0===this.direction&&null!==this.flippingPage&&"hard"===this.flippingPage.getDrawingDensity()){if(this.flippingPage.getHardAngle()>90){this.rightPage.getElement().style.zIndex=(this.getSettings().startZIndex+5).toString(10);this.rightPage.setHardDrawingAngle(180+this.flippingPage.getHardAngle());this.rightPage.draw(this.flippingPage.getDrawingDensity())}else this.rightPage.getElement().style.display="none"}else this.rightPage.simpleDraw(1)}drawBottomPage(){if(null===this.bottomPage)return;const t=null!=this.flippingPage?this.flippingPage.getDrawingDensity():null;if("portrait"!==this.orientation||1!==this.direction){this.bottomPage.getElement().style.zIndex=(this.getSettings().startZIndex+3).toString(10);this.bottomPage.draw(t)}}drawFrame(){if(null!==this.flippingPage){if(this.flippingPage.getHardAngle()===this.lastAngle)return;this.lastAngle=this.flippingPage.getHardAngle()}else this.lastAngle=-1234;this.clear();this.drawLeftPage();this.drawRightPage();this.drawBottomPage();if(null!=this.flippingPage){if(this.flippingPage.state.hardDrawingAngle<=90){this.flippingPage.getElement().style.zIndex=(this.getSettings().startZIndex+5).toString(10);this.flippingPage.draw()}else this.flippingPage.getElement().style.display="none"}if(null!=this.shadow&&null!==this.flippingPage)if("soft"===this.flippingPage.getDrawingDensity()){this.drawOuterShadow();this.drawInnerShadow()}else{this.drawHardOuterShadow();this.drawHardInnerShadow()}}clear(){for(const t of this.app.getPageCollection().getPages()){if(t!==this.leftPage&&t!==this.rightPage&&t!==this.flippingPage&&t!==this.bottomPage){const e=t.getElement().style;"none"!==e.display&&(e.cssText="display: none")}t.getTemporaryCopy()!==this.flippingPage&&t.hideTemporaryCopy()}}update(){super.update();null!==this.rightPage&&this.rightPage.setOrientation(1);null!==this.leftPage&&this.leftPage.setOrientation(0)}}class Settings{constructor(){this._default={startPage:0,size:"fixed",width:0,height:0,minWidth:0,maxWidth:0,minHeight:0,maxHeight:0,drawShadow:!0,flippingTime:1e3,usePortrait:!0,startZIndex:0,autoSize:!0,maxShadowOpacity:1,showCover:!1,mobileScrollSupport:!0,swipeDistance:30,clickEventForward:!0,useMouseEvents:!0,showPageCorners:!0,disableFlipByClick:!1}}getSettings(t){const e=this._default;Object.assign(e,t);if("stretch"!==e.size&&"fixed"!==e.size)throw new Error('Invalid size type. Available only "fixed" and "stretch" value');if(e.width<=0||e.height<=0)throw new Error("Invalid width or height");if(e.flippingTime<=0)throw new Error("Invalid flipping time");if("stretch"===e.size){e.minWidth<=0&&(e.minWidth=100);e.maxWidth<e.minWidth&&(e.maxWidth=2e3);e.minHeight<=0&&(e.minHeight=100);e.maxHeight<e.minHeight&&(e.maxHeight=2e3)}else{e.minWidth=e.width;e.maxWidth=e.width;e.minHeight=e.height;e.maxHeight=e.height}return e}}class PageFlip extends EventObject{constructor(t,e,i){super();this.isUserTouch=!1;this.isUserMove=!1;this.setting=null;this.pages=null;this.setting=(new Settings).getSettings(e);this.block=t;this.cspPolicyService=i}destroy(){this.ui.destroy();this.render=void 0}update(){this.render.update();this.pages.show()}loadFromHTML(t){this.ui=new HTMLUI(this.block,this,this.setting,t,this.cspPolicyService);this.render=new HTMLRender(this,this.setting,this.ui.getDistElement());this.flipController=new Flip(this.render,this);this.pages=new HTMLPageCollection(this,this.render,this.ui.getDistElement(),t);this.pages.load();this.render.start();this.pages.show(this.setting.startPage);setTimeout((()=>{this.ui.update();this.trigger("init",this,{page:this.setting.startPage,mode:this.render.getOrientation()})}),1)}updateFromHtml(t){const e=this.pages.getCurrentPageIndex();this.pages.destroy();this.pages=new HTMLPageCollection(this,this.render,this.ui.getDistElement(),t);this.pages.load();this.ui.updateItems(t);this.render.reload();this.pages.show(e);this.trigger("update",this,{page:e,mode:this.render.getOrientation()})}clear(){this.pages.destroy();this.ui.clear()}turnToPrevPage(){this.pages.showPrev()}turnToNextPage(){this.pages.showNext()}turnToPage(t){this.pages.show(t)}flipNext(t="top"){this.flipController.flipNext(t)}flipPrev(t="top"){this.flipController.flipPrev(t)}flip(t,e="top"){this.flipController.flipToPage(t,e)}updateState(t){this.trigger("changeState",this,t)}updatePageIndex(t){this.trigger("flip",this,t)}updateOrientation(t){this.ui.setOrientationStyle(t);this.update();this.trigger("changeOrientation",this,t)}getPageCount(){return this.pages.getPageCount()}getCurrentPageIndex(){return this.pages.getCurrentPageIndex()}getPage(t){return this.pages.getPage(t)}getRender(){return this.render}getFlipController(){return this.flipController}getOrientation(){return this.render.getOrientation()}getBoundsRect(){return this.render.getRect()}getSettings(){return this.setting}getUI(){return this.ui}getState(){return this.flipController.getState()}getPageCollection(){return this.pages}startUserTouch(t){this.mousePosition=t;this.isUserTouch=!0;this.isUserMove=!1}userMove(t,e){if(this.isUserTouch||e||!this.setting.showPageCorners){if(this.isUserTouch&&Helper.GetDistanceBetweenTwoPoint(this.mousePosition,t)>5){this.isUserMove=!0;this.flipController.fold(t)}}else this.flipController.showCorner(t)}userStop(t,e=!1){if(this.isUserTouch){this.isUserTouch=!1;e||(this.isUserMove?this.flipController.stopMove():this.flipController.flip(t))}}}class AnnotationEditorLayerBuilder{#no=null;#pc=null;#gc=null;#Cs=null;#uo=null;#Ce;constructor(t){this.pdfPage=t.pdfPage;this.accessibilityManager=t.accessibilityManager;this.l10n=t.l10n;this.l10n||=new genericl10n_GenericL10n;this.annotationEditorLayer=null;this.div=null;this._cancelled=!1;this.#Ce=t.uiManager;this.#no=t.annotationLayer||null;this.#uo=t.textLayer||null;this.#pc=t.drawLayer||null;this.#gc=t.onAppend||null;this.eventBus=t.eventBus;this.#Cs=t.structTreeLayer||null}async render(t,e="display"){if("display"!==e)return;if(this._cancelled)return;const i=t.clone({dontFlip:!0});if(this.div){this.annotationEditorLayer.update({viewport:i});this.show();return}const n=this.div=document.createElement("div");n.className="annotationEditorLayer";n.hidden=!0;n.dir=this.#Ce.direction;this.#gc?.(n);this.annotationEditorLayer=new j.AnnotationEditorLayer({uiManager:this.#Ce,div:n,structTreeLayer:this.#Cs,accessibilityManager:this.accessibilityManager,pageIndex:this.pdfPage.pageNumber-1,l10n:this.l10n,viewport:i,annotationLayer:this.#no,textLayer:this.#uo,drawLayer:this.#pc,eventBus:this.eventBus});const s={viewport:i,div:n,annotations:null,intent:e};this.annotationEditorLayer.render(s);this.show()}cancel(){this._cancelled=!0;this.div&&this.annotationEditorLayer.destroy()}hide(){if(this.div){this.annotationEditorLayer.pause(!0);this.div.hidden=!0}}show(){if(this.div&&!this.annotationEditorLayer.isInvisible){this.div.hidden=!1;this.annotationEditorLayer.pause(!1)}}}class AnnotationLayerBuilder{#gc=null;#ed=null;constructor({pdfPage:t,linkService:e,downloadManager:i,annotationStorage:n=null,imageResourcesPath:s="",renderForms:a=!0,enableScripting:r=!1,hasJSActionsPromise:o=null,fieldObjectsPromise:l=null,annotationCanvasMap:h=null,accessibilityManager:d=null,annotationEditorUIManager:c=null,onAppend:u=null}){this.pdfPage=t;this.linkService=e;this.downloadManager=i;this.imageResourcesPath=s;this.renderForms=a;this.annotationStorage=n;this.enableScripting=r;this._hasJSActionsPromise=o||Promise.resolve(!1);this._fieldObjectsPromise=l||Promise.resolve(null);this._annotationCanvasMap=h;this._accessibilityManager=d;this._annotationEditorUIManager=c;this.#gc=u;this.annotationLayer=null;this.div=null;this._cancelled=!1;this._eventBus=e.eventBus}async render(t,e,i="display"){if(this.div){if(this._cancelled||!this.annotationLayer)return;this.annotationLayer.update({viewport:t.clone({dontFlip:!0})});return}const[n,s,a]=await Promise.all([this.pdfPage.getAnnotations({intent:i}),this._hasJSActionsPromise,this._fieldObjectsPromise]);if(this._cancelled)return;const r=this.div=document.createElement("div");r.className="annotationLayer";this.#gc?.(r);if(0!==n.length){this.annotationLayer=new j.AnnotationLayer({div:r,accessibilityManager:this._accessibilityManager,annotationCanvasMap:this._annotationCanvasMap,annotationEditorUIManager:this._annotationEditorUIManager,page:this.pdfPage,viewport:t.clone({dontFlip:!0}),structTreeLayer:e?.structTreeLayer||null});await this.annotationLayer.render({annotations:n,imageResourcesPath:this.imageResourcesPath,renderForms:this.renderForms,linkService:this.linkService,downloadManager:this.downloadManager,annotationStorage:this.annotationStorage,enableScripting:this.enableScripting,hasJSActions:s,fieldObjects:a});this.linkService.isInPresentationMode&&this.#mc(d);if(!this.#ed){this.#ed=new AbortController;this._eventBus?._on("presentationmodechanged",(t=>{this.#mc(t.state)}),{signal:this.#ed.signal})}}else this.hide()}cancel(){this._cancelled=!0;this.#ed?.abort();this.#ed=null}hide(){this.div&&(document.querySelector("[data-pdfjsprinting=true]")||(this.div.hidden=!0))}hasEditableAnnotations(){return!!this.annotationLayer?.hasEditableAnnotations()}#mc(t){if(!this.div)return;let e=!1;switch(t){case d:e=!0;break;case l:break;default:return}for(const t of this.div.childNodes)t.hasAttribute("data-internal-link")||(t.inert=e)}}class DrawLayerBuilder{#pc=null;constructor(t){this.pageIndex=t.pageIndex}async render(t="display"){"display"!==t||this.#pc||this._cancelled||(this.#pc=new j.DrawLayer({pageIndex:this.pageIndex}))}cancel(){this._cancelled=!0;if(this.#pc){this.#pc.destroy();this.#pc=null}}setParent(t){this.#pc?.setParent(t)}getDrawLayer(){return this.#pc}}const we={Document:null,DocumentFragment:null,Part:"group",Sect:"group",Div:"group",Aside:"note",NonStruct:"none",P:null,H:"heading",Title:null,FENote:"note",Sub:"group",Lbl:null,Span:null,Em:null,Strong:null,Link:"link",Annot:"note",Form:"form",Ruby:null,RB:null,RT:null,RP:null,Warichu:null,WT:null,WP:null,L:"list",LI:"listitem",LBody:null,Table:"table",TR:"row",TH:"columnheader",TD:"cell",THead:"columnheader",TBody:null,TFoot:null,Caption:null,Figure:"figure",Formula:null,Artifact:null},ve=/^H(\d+)$/;class StructTreeLayerBuilder{#fc;#bc=null;#wc;#vc=new Map;#yc;#Ac=null;constructor(t,e){this.#fc=t.getStructTree();this.#yc=e}async render(){if(this.#wc)return this.#wc;const{promise:t,resolve:e,reject:i}=Promise.withResolvers();this.#wc=t;try{this.#bc=this.#xc(await this.#fc)}catch(t){i(t)}this.#fc=null;this.#bc?.classList.add("structTree");e(this.#bc);return t}async getAriaAttributes(t){try{await this.render();return this.#vc.get(t)}catch{}return null}hide(){this.#bc&&!this.#bc.hidden&&(this.#bc.hidden=!0)}show(){this.#bc?.hidden&&(this.#bc.hidden=!1)}#Ec(t,e){const{alt:i,id:n,lang:s}=t;if(void 0!==i){let n=!1;const s=removeNullCharacters(i);for(const e of t.children)if("annotation"===e.type){let t=this.#vc.get(e.id);if(!t){t=new Map;this.#vc.set(e.id,t)}t.set("aria-label",s);n=!0}n||e.setAttribute("aria-label",s)}void 0!==n&&e.setAttribute("aria-owns",n);void 0!==s&&e.setAttribute("lang",removeNullCharacters(s,!0))}#Sc(t,e){const{alt:i,bbox:n,children:s}=t,a=s?.[0];if(!this.#yc||!i||!n||"content"!==a?.type)return!1;const{id:r}=a;if(!r)return!1;e.setAttribute("aria-owns",r);const o=document.createElement("span");(this.#Ac||=new Map).set(r,o);o.setAttribute("role","img");o.setAttribute("aria-label",removeNullCharacters(i));const{pageHeight:l,pageX:h,pageY:d}=this.#yc,c="calc(var(--scale-factor)*",{style:u}=o;u.width=`${c}${n[2]-n[0]}px)`;u.height=`${c}${n[3]-n[1]}px)`;u.left=`${c}${n[0]-h}px)`;u.top=`${c}${l-n[3]+d}px)`;return!0}addElementsToTextLayer(){if(this.#Ac){for(const[t,e]of this.#Ac)document.getElementById(t)?.append(e);this.#Ac.clear();this.#Ac=null}}#xc(t){if(!t)return null;const e=document.createElement("span");if("role"in t){const{role:i}=t,n=i.match(ve);if(n){e.setAttribute("role","heading");e.setAttribute("aria-level",n[1])}else we[i]&&e.setAttribute("role",we[i]);if("Figure"===i&&this.#Sc(t,e))return e}this.#Ec(t,e);if(t.children)if(1===t.children.length&&"id"in t.children[0])this.#Ec(t.children[0],e);else for(const i of t.children)e.append(this.#xc(i));return e}}class TextAccessibilityManager{#Pc=!1;#_c=null;#Cc=new Map;#Tc=new Map;setTextMapping(t){this.#_c=t}static#Mc(t,e){const i=t.getBoundingClientRect(),n=e.getBoundingClientRect();if(0===i.width&&0===i.height)return 1;if(0===n.width&&0===n.height)return-1;const s=i.y,a=i.y+i.height,r=i.y+i.height/2,o=n.y,l=n.y+n.height,h=n.y+n.height/2;if(r<=o&&h>=a)return-1;if(h<=s&&r>=l)return 1;return i.x+i.width/2-(n.x+n.width/2)}enable(){if(this.#Pc)throw new Error("TextAccessibilityManager is already enabled.");if(!this.#_c)throw new Error("Text divs and strings have not been set.");this.#Pc=!0;this.#_c=this.#_c.slice();this.#_c.sort(TextAccessibilityManager.#Mc);if(this.#Cc.size>0){const t=this.#_c;for(const[e,i]of this.#Cc){document.getElementById(e)?this.#Ic(e,t[i]):this.#Cc.delete(e)}}for(const[t,e]of this.#Tc)this.addPointerInTextLayer(t,e);this.#Tc.clear()}disable(){if(this.#Pc){this.#Tc.clear();this.#_c=null;this.#Pc=!1}}removePointerInTextLayer(t){if(!this.#Pc){this.#Tc.delete(t);return}const e=this.#_c;if(!e||0===e.length)return;const{id:i}=t,n=this.#Cc.get(i);if(void 0===n)return;const s=e[n];this.#Cc.delete(i);let a=s.getAttribute("aria-owns");if(a?.includes(i)){a=a.split(" ").filter((t=>t!==i)).join(" ");if(a)s.setAttribute("aria-owns",a);else{s.removeAttribute("aria-owns");s.setAttribute("role","presentation")}}}#Ic(t,e){const i=e.getAttribute("aria-owns");i?.includes(t)||e.setAttribute("aria-owns",i?`${i} ${t}`:t);e.removeAttribute("role")}addPointerInTextLayer(t,e){const{id:i}=t;if(!i)return null;if(!this.#Pc){this.#Tc.set(t,e);return null}e&&this.removePointerInTextLayer(t);const n=this.#_c;if(!n||0===n.length)return null;const s=binarySearchFirstItem(n,(e=>TextAccessibilityManager.#Mc(t,e)<0)),a=Math.max(0,s-1),r=n[a];this.#Ic(i,r);this.#Cc.set(i,a);const o=r.parentNode;return o?.classList.contains("markedContent")?o.id:null}moveElementInDOM(t,e,i,n){const s=this.addPointerInTextLayer(i,n);if(!t.hasChildNodes()){t.append(e);return s}const a=Array.from(t.childNodes).filter((t=>t!==e));if(0===a.length)return s;const r=i||e,o=binarySearchFirstItem(a,(t=>TextAccessibilityManager.#Mc(r,t)<0));0===o?a[0].before(e):a[o-1].after(e);return s}}class TextHighlighter{#ed=null;constructor({findController:t,customFindController:e,eventBus:i,pageIndex:n}){this.findController=t;this.customFindController=e;this.matches=[];this.eventBus=i;this.pageIdx=n;this.textDivs=null;this.textContentItemsStr=null;this.enabled=!1}setTextMapping(t,e){this.textDivs=t;this.textContentItemsStr=e}enable(){if(!this.textDivs||!this.textContentItemsStr)throw new Error("Text divs and strings have not been set.");if(!this.enabled){this.enabled=!0;if(!this.#ed){this.#ed=new AbortController;this.eventBus._on("updatetextlayermatches",(t=>{t.pageIndex!==this.pageIdx&&-1!==t.pageIndex||this._updateMatches()}),{signal:this.#ed.signal})}this._updateMatches()}}disable(){if(this.enabled){this.enabled=!1;this.#ed?.abort();this.#ed=null;this._updateMatches(!0)}}_convertMatches(t,e,i="highlight",s=!1,a=!1,r=-1){if(!t)return[];const{textContentItemsStr:o}=this;let l=0,h=0;const d=o.length-1,c=[];for(let u=0,p=t.length;u<p;u++){let p=t[u];for(;l!==d&&p>=h+o[l].length;){h+=o[l].length;l++}l===o.length&&n.NgxConsole.error("Could not find a matching mapping");const g={begin:{divIdx:l,offset:p-h},cssClass:i,highlightAll:s,selected:a&&u===r};p+=e[u];for(;l!==d&&p>h+o[l].length;){h+=o[l].length;l++}g.end={divIdx:l,offset:p-h};c.push(g)}return c}_renderMatches(t,e){if(0===t.length)return;const{pageIdx:i}=this,{textContentItemsStr:n,textDivs:s}=this;let a=null;const r={divIdx:-1,offset:void 0};function beginText(t,e){const i=t.divIdx;s[i].textContent="";return appendTextToDiv(i,0,t.offset,e)}function appendTextToDiv(t,e,i,a){let r=s[t];if(r.nodeType===Node.TEXT_NODE){const e=document.createElement("span");r.before(e);e.append(r);s[t]=e;r=e}const o=n[t].substring(e,i),l=document.createTextNode(o);if(a){const t=document.createElement("span");t.className=`${a} appended`;t.append(l);r.append(t);if(a.includes("selected")){const{left:e}=t.getClientRects()[0];return e-r.getBoundingClientRect().left}return 0}r.append(l);return 0}let o=-1,l=-1;for(let n=0;n<t.length;n++){const h=t[n];if(!h.selected&&!h.highlightAll)continue;const d=h.begin;if(d.divIdx===o&&d.offset===l)continue;o=d.divIdx;l=d.offset;const c=h.end,u=h.selected?" selected":"";let p=0;if(a&&d.divIdx===a.divIdx)appendTextToDiv(a.divIdx,a.offset,d.offset);else{null!==a&&appendTextToDiv(a.divIdx,a.offset,r.offset);beginText(d)}if(d.divIdx===c.divIdx)p=appendTextToDiv(d.divIdx,d.offset,c.offset,h.cssClass+u);else{p=appendTextToDiv(d.divIdx,d.offset,r.offset,h.cssClass+" begin"+u);for(let t=d.divIdx+1,e=c.divIdx;t<e;t++)s[t].className=h.cssClass+" middle"+u;beginText(c,h.cssClass+" end"+u)}a=c;h.selected&&e.scrollMatchIntoView({element:s[d.divIdx],selectedLeft:p,pageIndex:i,matchIndex:n});if(this.textDivs.length>0){const t=this.textDivs[0].closest(".textLayer").querySelectorAll(`.${h.cssClass}`);this.eventBus.dispatch("renderedtextlayerhighlights",{pageIndex:i,highlights:t})}}a&&appendTextToDiv(a.divIdx,a.offset,r.offset)}_updateMatches(t=!1){if(!this.enabled&&!t)return;const{findController:e,customFindController:i,matches:n,pageIdx:s}=this,{textContentItemsStr:a,textDivs:r}=this;let o=-1;for(const t of n){for(let e=Math.max(o,t.begin.divIdx),i=t.end.divIdx;e<=i;e++){const t=r[e];t.textContent=a[e];t.className=""}o=t.end.divIdx+1}if(t)return;const l=i.pageMatches[s]||null,h=i.pageMatchesLength[s]||null,d=e.pageMatches[s]||null,c=this._convertMatches(l,h,"customHighlight",i.state?.highlightAll,s===i.selected.pageIdx,i.selected.matchIdx);this.matches=[...c];e?.highlightMatches&&!t||t||this._renderMatches(this.matches,this.customFindController);const u=e.pageMatchesLength[s]||null,p=this._convertMatches(d,u,"highlight",e.state?.highlightAll,s===e.selected.pageIdx,e.selected.matchIdx);this.matches.push(...p);this.matches.sort(((t,e)=>{const i=t.begin.divIdx-e.begin.divIdx;return 0===i?t.begin.offset-e.begin.offset:i}));this._renderMatches(this.matches,this.findController)}}class TextLayerBuilder{#Dc=!1;#gc=null;#Lc=!1;#uo=null;static#kc=new Map;static#Fc=null;constructor({pdfPage:t,highlighter:e=null,accessibilityManager:i=null,enablePermissions:n=!1,onAppend:s=null}){this.pdfPage=t;this.highlighter=e;this.accessibilityManager=i;this.#Dc=!0===n;this.#gc=s;this.div=document.createElement("div");this.div.tabIndex=0;this.div.className="textLayer"}async render(t,e=null){if(this.#Lc&&this.#uo){this.#uo.update({viewport:t,onBefore:this.hide.bind(this)});this.show();return}this.cancel();this.#uo=new j.TextLayer({textContentSource:this.pdfPage.streamTextContent(e||{includeMarkedContent:!0,disableNormalization:!0}),container:this.div,viewport:t});const{textDivs:i,textContentItemsStr:n}=this.#uo;this.highlighter?.setTextMapping(i,n);this.accessibilityManager?.setTextMapping(i);await this.#uo.render();this.#Lc=!0;const s=document.createElement("div");s.className="endOfContent";this.div.append(s);this.#Rc(s);this.#gc?.(this.div);this.highlighter?.enable();this.accessibilityManager?.enable()}hide(){if(!this.div.hidden&&this.#Lc){this.highlighter?.disable();this.div.hidden=!0}}show(){if(this.div.hidden&&this.#Lc){this.div.hidden=!1;this.highlighter?.enable()}}cancel(){this.#uo?.cancel();this.#uo=null;this.highlighter?.disable();this.accessibilityManager?.disable();TextLayerBuilder.#Nc(this.div)}#Rc(t){const{div:e}=this;e.addEventListener("mousedown",(()=>{e.classList.add("selecting")}));e.addEventListener("copy",(t=>{if(!this.#Dc){const e=document.getSelection();t.clipboardData.setData("text/plain",removeNullCharacters((0,V.normalizeUnicode)(e.toString())))}(0,U.stopEvent)(t)}));TextLayerBuilder.#kc.set(e,t);TextLayerBuilder.#Bc()}static#Nc(t){this.#kc.delete(t);if(0===this.#kc.size){this.#Fc?.abort();this.#Fc=null}}static#Bc(){if(this.#Fc)return;this.#Fc=new AbortController;const{signal:t}=this.#Fc,reset=(t,e)=>{e.append(t);t.style.width="";t.style.height="";e.classList.remove("selecting")};let e=!1;document.addEventListener("pointerdown",(()=>{e=!0}),{signal:t});document.addEventListener("pointerup",(()=>{e=!1;this.#kc.forEach(reset)}),{signal:t});window.addEventListener("blur",(()=>{e=!1;this.#kc.forEach(reset)}),{signal:t});document.addEventListener("keyup",(()=>{e||this.#kc.forEach(reset)}),{signal:t});var i,n;document.addEventListener("selectionchange",(()=>{const t=document.getSelection();if(0===t.rangeCount){this.#kc.forEach(reset);return}if(0===this.#kc.size)return;const e=new Set;for(let i=0;i<t.rangeCount;i++){const n=t.getRangeAt(i);for(const t of this.#kc.keys())!e.has(t)&&n.intersectsNode(t)&&e.add(t)}for(const[t,i]of this.#kc)e.has(t)?t.classList.add("selecting"):reset(i,t);i??="none"===getComputedStyle(this.#kc.values().next().value).getPropertyValue("-moz-user-select");if(i)return;const s=t.getRangeAt(0),a=n&&(0===s.compareBoundaryPoints(Range.END_TO_END,n)||0===s.compareBoundaryPoints(Range.START_TO_END,n));let r=a?s.startContainer:s.endContainer;r.nodeType===Node.TEXT_NODE&&(r=r.parentNode);const o=r.parentElement?.closest(".textLayer"),l=this.#kc.get(o);if(l){l.style.width=o.style.width;l.style.height=o.style.height;r.parentElement.insertBefore(l,a?r:r.nextSibling)}n=s.cloneRange()}),{signal:t})}}const ye=new Map([["canvasWrapper",0],["textLayer",1],["annotationLayer",2],["annotationEditorLayer",3],["xfaLayer",3]]);class PDFPageView{#Oc=V.AnnotationMode.ENABLE_FORMS;#Vc=null;#c=!1;#Hc=!1;#Ut=!1;#zc=null;#Uc=null;#jc=null;#Wc=null;#$c=1;#Gc=1;#qc=null;#Xc=r.INITIAL;#Kc=w;#Yc={directDrawing:!0,initialOptionalContent:!0,regularAnnotations:!0};#Zc=[null,null,null,null];constructor(t){const e=t.container,i=t.defaultViewport;this.id=t.id;this.renderingId="page"+this.id;this.#zc=t.layerProperties||null;this.pdfPage=null;this.pageLabel=null;this.rotation=0;this.scale=t.scale||1;this.viewport=i;this.pdfPageRotate=i.rotation;this._optionalContentConfigPromise=t.optionalContentConfigPromise||null;this.#Kc=t.textLayerMode??w;this.#Oc=t.annotationMode??V.AnnotationMode.ENABLE_FORMS;this.imageResourcesPath=t.imageResourcesPath||"";this.maxCanvasPixels=t.maxCanvasPixels??AppOptions.get("maxCanvasPixels");this.pageColors=t.pageColors||null;this.#c=t.enableHWA||!1;this.eventBus=t.eventBus;this.renderingQueue=t.renderingQueue;this.l10n=t.l10n;this.l10n||=new genericl10n_GenericL10n;this.renderTask=null;this.resume=null;this._isStandalone=!this.renderingQueue?.hasViewer();this._container=e;this._annotationCanvasMap=null;this.annotationLayer=null;this.annotationEditorLayer=null;this.textLayer=null;this.xfaLayer=null;this.structTreeLayer=null;this.drawLayer=null;const n=document.createElement("div");n.className="page";n.setAttribute("data-page-number",this.id);n.setAttribute("role","region");n.setAttribute("data-l10n-id","pdfjs-page-landmark");n.setAttribute("data-l10n-args",JSON.stringify({page:this.id}));this.div=n;this.#Qc();e?.append(n);if(this._isStandalone){e?.style.setProperty("--scale-factor",this.scale*j.PixelsPerInch.PDF_TO_CSS_UNITS);this.pageColors?.background&&e?.style.setProperty("--page-bg-color",this.pageColors.background);const{optionalContentConfigPromise:i}=t;i&&i.then((t=>{i===this._optionalContentConfigPromise&&(this.#Yc.initialOptionalContent=t.hasInitialVisibility)}));t.l10n||this.l10n.translate(this.div)}}#Jc(t,e){const i=ye.get(e),n=this.#Zc[i];this.#Zc[i]=t;if(n)n.replaceWith(t);else{for(let e=i-1;e>=0;e--){const i=this.#Zc[e];if(i){i.after(t);return}}this.div.prepend(t)}}get renderingState(){return this.#Xc}set renderingState(t){if(t!==this.#Xc){this.#Xc=t;if(this.#Uc){clearTimeout(this.#Uc);this.#Uc=null}switch(t){case r.PAUSED:this.div.classList.remove("loading");break;case r.RUNNING:this.div.classList.add("loadingIcon");this.#Uc=setTimeout((()=>{this.div.classList.add("loading");this.#Uc=null}),0);break;case r.INITIAL:case r.FINISHED:this.div.classList.remove("loadingIcon","loading")}}}#Qc(){const{viewport:t}=this;if(this.pdfPage){if(this.#Wc===t.rotation)return;this.#Wc=t.rotation}(0,j.setLayerDimensions)(this.div,t,!0,!1)}setPdfPage(t){if(this._isStandalone&&("CanvasText"===this.pageColors?.foreground||"Canvas"===this.pageColors?.background)){this._container?.style.setProperty("--hcm-highlight-filter",t.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight"));this._container?.style.setProperty("--hcm-highlight-selected-filter",t.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","Highlight"))}this.pdfPage=t;this.pdfPageRotate=t.rotate;const e=(this.rotation+this.pdfPageRotate)%360;this.viewport=t.getViewport({scale:this.scale*j.PixelsPerInch.PDF_TO_CSS_UNITS,rotation:e});this.#Qc();this.reset()}destroy(){this.reset();this.pdfPage?.cleanup()}hasEditableAnnotations(){return!!this.annotationLayer?.hasEditableAnnotations()}get _textHighlighter(){return(0,V.shadow)(this,"_textHighlighter",new TextHighlighter({pageIndex:this.id-1,eventBus:this.eventBus,findController:this.#zc.findController,customFindController:this.#zc.customFindController}))}#tu(t,e,i){this.eventBus.dispatch(t,{source:this,pageNumber:this.id,error:e,layer:i})}async#eu(){let t=null;try{await this.annotationLayer.render(this.viewport,{structTreeLayer:this.structTreeLayer},"display")}catch(e){console.error("#renderAnnotationLayer:",e);t=e}finally{this.#tu("annotationlayerrendered",t,this.annotationLayer)}}async#iu(){let t=null;try{await this.annotationEditorLayer.render(this.viewport,"display")}catch(e){console.error("#renderAnnotationEditorLayer:",e);t=e}finally{this.#tu("annotationeditorlayerrendered",t,this.annotationEditorLayer)}}async#nu(){try{await this.drawLayer.render("display")}catch(t){console.error("#renderDrawLayer:",t)}}async#su(){let t=null;try{const t=await this.xfaLayer.render(this.viewport,"display");t?.textDivs&&this._textHighlighter&&this.#au(t.textDivs)}catch(e){console.error("#renderXfaLayer:",e);t=e}finally{if(this.xfaLayer?.div){this.l10n.pause();this.#Jc(this.xfaLayer.div,"xfaLayer");this.l10n.resume()}this.#tu("xfalayerrendered",t,this.xfaLayer)}}async#ru(){if(!this.textLayer)return;let t=null;try{await this.textLayer.render(this.viewport)}catch(e){if(e instanceof V.AbortException)return;console.error("#renderTextLayer:",e);t=e}this.#tu("textlayerrendered",t,this.textLayer);this.#ou()}async#ou(){if(!this.textLayer)return;const t=await(this.structTreeLayer?.render());if(t){this.l10n.pause();this.structTreeLayer?.addElementsToTextLayer();this.canvas&&t.parentNode!==this.canvas&&this.canvas.append(t);this.l10n.resume()}this.structTreeLayer?.show()}async#au(t){const e=await this.pdfPage.getTextContent(),i=[];for(const t of e.items)i.push(t.str);this._textHighlighter.setTextMapping(t,i);this._textHighlighter.enable()}#lu(){const{canvas:t}=this;if(t){t.remove();t.width=t.height=0;this.canvas=null;this.#jc=null}}reset({keepAnnotationLayer:t=!1,keepAnnotationEditorLayer:e=!1,keepXfaLayer:i=!1,keepTextLayer:n=!1,keepCanvasWrapper:s=!1}={}){this.cancelRendering({keepAnnotationLayer:t,keepAnnotationEditorLayer:e,keepXfaLayer:i,keepTextLayer:n});this.renderingState=r.INITIAL;const a=this.div,o=a.childNodes,l=t&&this.annotationLayer?.div||null,h=e&&this.annotationEditorLayer?.div||null,d=i&&this.xfaLayer?.div||null,c=n&&this.textLayer?.div||null,u=s&&this.#Vc||null;for(let t=o.length-1;t>=0;t--){const e=o[t];switch(e){case l:case h:case d:case c:case u:continue}e.remove();const i=this.#Zc.indexOf(e);i>=0&&(this.#Zc[i]=null)}a.removeAttribute("data-loaded");l&&this.annotationLayer.hide();h&&this.annotationEditorLayer.hide();d&&this.xfaLayer.hide();c&&this.textLayer.hide();this.structTreeLayer?.hide();if(!s&&this.#Vc){this.#Vc=null;this.#lu()}}toggleEditingMode(t){if(this.hasEditableAnnotations()){this.#Ut=t;this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0})}}update({scale:t=0,rotation:e=null,optionalContentConfigPromise:i=null,drawingDelay:n=-1}){this.scale=t||this.scale;"number"==typeof e&&(this.rotation=e);if(i instanceof Promise){this._optionalContentConfigPromise=i;i.then((t=>{i===this._optionalContentConfigPromise&&(this.#Yc.initialOptionalContent=t.hasInitialVisibility)}))}this.#Yc.directDrawing=!0;const s=(this.rotation+this.pdfPageRotate)%360;this.viewport=this.viewport.clone({scale:this.scale*j.PixelsPerInch.PDF_TO_CSS_UNITS,rotation:s});this.#Qc();this._isStandalone&&this._container?.style.setProperty("--scale-factor",this.viewport.scale);if(this.canvas){let t=!1;if(this.#Hc)if(0===this.maxCanvasPixels)t=!0;else if(this.maxCanvasPixels>0){const{width:e,height:i}=this.viewport,{sx:n,sy:s}=this.outputScale;t=(Math.floor(e)*n|0)*(Math.floor(i)*s|0)>this.maxCanvasPixels}const e=n>=0&&n<1e3;if(e||t){if(e&&!t&&this.renderingState!==r.FINISHED){this.cancelRendering({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,cancelExtraDelay:n});this.renderingState=r.FINISHED;this.#Yc.directDrawing=!1}this.cssTransform({redrawAnnotationLayer:!0,redrawAnnotationEditorLayer:!0,redrawXfaLayer:!0,redrawTextLayer:!e,hideTextLayer:e});if(e)return;this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!0,timestamp:performance.now(),error:this.#qc});return}}this.cssTransform({});this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0})}cancelRendering({keepAnnotationLayer:t=!1,keepAnnotationEditorLayer:e=!1,keepXfaLayer:i=!1,keepTextLayer:n=!1,cancelExtraDelay:s=0}={}){if(this.renderTask){this.renderTask.cancel(s);this.renderTask=null}this.resume=null;if(this.textLayer&&(!n||!this.textLayer.div)){this.textLayer.cancel();this.textLayer=null}if(this.annotationLayer&&(!t||!this.annotationLayer.div)){this.annotationLayer.cancel();this.annotationLayer=null;this._annotationCanvasMap=null}this.structTreeLayer&&!this.textLayer&&(this.structTreeLayer=null);if(this.annotationEditorLayer&&(!e||!this.annotationEditorLayer.div)){if(this.drawLayer){this.drawLayer.cancel();this.drawLayer=null}this.annotationEditorLayer.cancel();this.annotationEditorLayer=null}if(this.xfaLayer&&(!i||!this.xfaLayer.div)){this.xfaLayer.cancel();this.xfaLayer=null;this._textHighlighter?.disable()}}cssTransform({redrawAnnotationLayer:t=!1,redrawAnnotationEditorLayer:e=!1,redrawXfaLayer:i=!1,redrawTextLayer:n=!1,hideTextLayer:s=!1}){const{canvas:a}=this;if(!a)return;const r=this.#jc;if(this.viewport!==r){const t=(360+this.viewport.rotation-r.rotation)%360;if(90===t||270===t){const{width:e,height:i}=this.viewport,n=i/e,s=e/i;a.style.transform=`rotate(${t}deg) scale(${n},${s})`}else a.style.transform=0===t?"":`rotate(${t}deg)`}t&&this.annotationLayer&&this.#eu();if(e&&this.annotationEditorLayer){this.drawLayer&&this.#nu();this.#iu()}i&&this.xfaLayer&&this.#su();if(this.textLayer)if(s){this.textLayer.hide();this.structTreeLayer?.hide()}else n&&this.#ru()}get width(){return this.viewport.width}get height(){return this.viewport.height}getPagePoint(t,e){return this.viewport.convertToPdfPoint(t,e)}async#rc(t,e=null){t===this.renderTask&&(this.renderTask=null);if(e instanceof j.RenderingCancelledException)this.#qc=null;else{this.#qc=e;this.renderingState=r.FINISHED;this.#Yc.regularAnnotations=!t.separateAnnots;this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!1,timestamp:performance.now(),error:this.#qc});if(e)throw e}}async draw(){if(this.renderingState!==r.INITIAL){n.NgxConsole.error("Must be in new state before drawing");this.reset()}const{div:t,l10n:e,pageColors:i,pdfPage:s,viewport:a}=this;if(!s){this.renderingState=r.FINISHED;throw new Error("pdfPage is not loaded")}this.renderingState=r.RUNNING;let o=this.#Vc;if(!o){o=this.#Vc=document.createElement("div");o.classList.add("canvasWrapper");this.#Jc(o,"canvasWrapper")}if(!this.textLayer&&this.#Kc!==b&&!s.isPureXfa){this._accessibilityManager||=new TextAccessibilityManager;this.textLayer=new TextLayerBuilder({pdfPage:s,highlighter:this._textHighlighter,accessibilityManager:this._accessibilityManager,enablePermissions:this.#Kc===v,onAppend:t=>{this.l10n.pause();this.#Jc(t,"textLayer");this.l10n.resume()}})}if(!this.annotationLayer&&this.#Oc!==V.AnnotationMode.DISABLE){const{annotationStorage:t,annotationEditorUIManager:e,downloadManager:i,enableScripting:n,fieldObjectsPromise:a,hasJSActionsPromise:r,linkService:o}=this.#zc;this._annotationCanvasMap||=new Map;this.annotationLayer=new AnnotationLayerBuilder({pdfPage:s,annotationStorage:t,imageResourcesPath:this.imageResourcesPath,renderForms:this.#Oc===V.AnnotationMode.ENABLE_FORMS,linkService:o,downloadManager:i,enableScripting:n,hasJSActionsPromise:r,fieldObjectsPromise:a,annotationCanvasMap:this._annotationCanvasMap,accessibilityManager:this._accessibilityManager,annotationEditorUIManager:e,onAppend:t=>{this.#Jc(t,"annotationLayer")}})}let{width:l,height:h}=a;const d=document.createElement("canvas");d.setAttribute("role","presentation");const c=!(!i?.background||!i?.foreground),u=this.canvas,p=!u&&!c;this.canvas=d;this.#jc=a;let showCanvas=t=>{if(p){o.prepend(d);showCanvas=null}else if(t){if(u){u.replaceWith(d);u.width=u.height=0}else o.prepend(d);showCanvas=null}};const g=d.getContext("2d",{alpha:!1,willReadFrequently:!this.#c}),m=this.outputScale=new j.OutputScale;if(0===this.maxCanvasPixels){const t=1/this.scale;m.sx*=t;m.sy*=t;this.#Hc=!0}else if(this.maxCanvasPixels>0){const t=l*h,e=Math.sqrt(this.maxCanvasPixels/t);if(m.sx>e||m.sy>e){m.sx=e;m.sy=e;this.#Hc=!0}else this.#Hc=!1}const f=approximateFraction(m.sx),w=approximateFraction(m.sy);let y=floorToDivide(l*m.sx,f[0]),A=floorToDivide(h*m.sy,w[0]);const x=await MaxCanvasSize.reduceToMaxCanvasSize(y,A);if(x>1){y/=x;y*=.95;A/=x;A*=.95;const t=Math.round(100*(x/.95-1));(0,V.warn)(`Page ${this.id}: Reduced the maximum resolution by ${t}% because the browser can't render larger canvases.`)}d.width=y;d.height=A;const E=floorToDivide(T(l),f[1]),S=floorToDivide(T(h),w[1]);m.sx=y/E;m.sy=A/S;if(this.#$c!==f[1]){t.style.setProperty("--scale-round-x",`${f[1]}px`);this.#$c=f[1]}if(this.#Gc!==w[1]){t.style.setProperty("--scale-round-y",`${w[1]}px`);this.#Gc=w[1]}const P={canvasContext:g,transform:m.scaled?[m.sx,0,0,m.sy,0,0]:null,viewport:a,annotationMode:this.#Oc,optionalContentConfigPromise:this._optionalContentConfigPromise,annotationCanvasMap:this._annotationCanvasMap,pageColors:i,isEditing:this.#Ut},_=this.renderTask=s.render(P);_.onContinue=t=>{showCanvas?.(!1);if(!this.renderingQueue||this.renderingQueue.isHighestPriority(this))t();else{this.renderingState=r.PAUSED;this.resume=()=>{this.renderingState=r.RUNNING;t()}}};const C=_.promise.then((async()=>{showCanvas?.(!0);await this.#rc(_);this.structTreeLayer||=new StructTreeLayerBuilder(s,a.rawDims);this.#ru();this.annotationLayer&&await this.#eu();const{annotationEditorUIManager:t}=this.#zc;if(t){this.drawLayer||=new DrawLayerBuilder({pageIndex:this.id});await this.#nu();this.drawLayer.setParent(o);this.annotationEditorLayer||=new AnnotationEditorLayerBuilder({uiManager:t,pdfPage:s,l10n:e,structTreeLayer:this.structTreeLayer,accessibilityManager:this._accessibilityManager,annotationLayer:this.annotationLayer?.annotationLayer,textLayer:this.textLayer,drawLayer:this.drawLayer.getDrawLayer(),onAppend:t=>{this.#Jc(t,"annotationEditorLayer")},eventBus:this.eventBus});this.#iu()}}),(t=>{if(t instanceof j.RenderingCancelledException){u?.remove();this.#lu()}else showCanvas?.(!0);return this.#rc(_,t)}));if(s.isPureXfa){if(!this.xfaLayer){const{annotationStorage:t,linkService:e}=this.#zc;this.xfaLayer=new XfaLayerBuilder({pdfPage:s,annotationStorage:t,linkService:e})}this.#su()}t.setAttribute("data-loaded",!0);this.eventBus.dispatch("pagerender",{source:this,pageNumber:this.id});return C}setPageLabel(t){this.pageLabel="string"==typeof t?t:null;this.div.setAttribute("data-l10n-args",JSON.stringify({page:this.pageLabel??this.id}));null!==this.pageLabel?this.div.setAttribute("data-page-label",this.pageLabel):this.div.removeAttribute("data-page-label")}get thumbnailCanvas(){const{directDrawing:t,initialOptionalContent:e,regularAnnotations:i}=this.#Yc;return t&&e&&i?this.canvas:null}}const Ae=1e4,xe=5e3,Ee=250;function isValidAnnotationEditorMode(t){return Object.values(V.AnnotationEditorType).includes(t)&&t!==V.AnnotationEditorType.DISABLE}class PDFPageViewBuffer{#hu=new Set;#du=0;constructor(t){this.#du=t}push(t){const e=this.#hu;e.has(t)&&e.delete(t);e.add(t);e.size>this.#du&&this.#cu()}resize(t,e=null){this.#du=t;const i=this.#hu;if(e){const t=i.size;let n=1;for(const s of i){if(e.has(s.id)){i.delete(s);i.add(s)}if(++n>t)break}}for(;i.size>this.#du;)this.#cu()}has(t){return this.#hu.has(t)}[Symbol.iterator](){return this.#hu.keys()}#cu(){const t=this.#hu.keys().next().value;t?.destroy();this.#hu.delete(t)}}class PDFViewer{#uu=null;#Ue=null;#pu=null;#gu=V.AnnotationEditorType.NONE;#mu=null;#Oc=V.AnnotationMode.ENABLE_FORMS;#fu=null;#bu=null;#c=!1;#Je=!1;#Dc=!1;#ti=!1;#ei=!1;#ed=null;#gi=null;#wu=null;#vu=null;#yu=!1;#Au=null;#xu=!1;#Eu=0;#Jh=new ResizeObserver(this.#td.bind(this));#Su=null;#Pu=null;#_u=!0;#Kc=w;#Cu=void 0;#Tu="multiple";#Mu=10;#Iu=a;constructor(t){const e="4.10.708";if(j.version!==e)throw new Error(`The API version "${j.version}" does not match the Viewer version "${e}".`);this.container=t.container;this.viewer=t.viewer||t.container.firstElementChild;this.eventBus=t.eventBus;this.pageViewMode=t.pageViewMode||"multiple";this.defaultCacheSize=t.defaultCacheSize;this.#Mu=t.maxZoom;this.#Iu=t.minZoom;if("DIV"!==this.container?.tagName||"DIV"!==this.viewer?.tagName)throw new Error("Invalid `container` and/or `viewer` option.");if(this.container.offsetParent&&"absolute"!==getComputedStyle(this.container).position)throw new Error("The `container` must be absolutely positioned.");this.#Jh.observe(this.container);this.linkService=t.linkService||new SimpleLinkService;this.downloadManager=t.downloadManager||null;this.findController=t.findController||null;this.customFindController=t.customFindController||null;this.#Ue=t.altTextManager||null;this.#bu=t.editorUndoBar||null;this.findController&&(this.findController.onIsPageVisible=t=>this._getVisiblePages().ids.has(t));this._scriptingManager=t.scriptingManager||null;this.#Kc=t.textLayerMode??w;this.#Oc=t.annotationMode??V.AnnotationMode.ENABLE_FORMS;this.#gu=t.annotationEditorMode??V.AnnotationEditorType.NONE;this.#pu=t.annotationEditorHighlightColors||null;this.#Je=!0===t.enableHighlightFloatingButton;this.#ti=!0===t.enableUpdatedAddImage;this.#ei=!0===t.enableNewAltTextWhenAddingImage;this.imageResourcesPath=t.imageResourcesPath||"";this.enablePrintAutoRotate=t.enablePrintAutoRotate||!1;this.removePageBorders=t.removePageBorders||!1;this.maxCanvasPixels=t.maxCanvasPixels;this.l10n=t.l10n;this.l10n||=new genericl10n_GenericL10n;this.#Dc=t.enablePermissions||!1;this.pageColors=t.pageColors||null;this.#gi=t.mlManager||null;this.#c=t.enableHWA||!1;this.#_u=!1!==t.supportsPinchToZoom;this.defaultRenderingQueue=!t.renderingQueue;if(this.defaultRenderingQueue){this.renderingQueue=new PDFRenderingQueue;this.renderingQueue.setViewer(this)}else this.renderingQueue=t.renderingQueue;const{abortSignal:i}=t;i?.addEventListener("abort",(()=>{this.#Jh.disconnect();this.#Jh=null}),{once:!0});this.scroll=watchScroll(this.container,this._scrollUpdate.bind(this),i);this.presentationModeState=o;this._resetView();this.removePageBorders&&this.viewer.classList.add("removePageBorders");this.#Du();this.eventBus._on("thumbnailrendered",(({pageNumber:t,pdfPage:e})=>{const i=this._pages[t-1];this.#uu.has(i)||e?.cleanup()}));t.l10n||this.l10n.translate(this.container);this.cspPolicyService=t.cspPolicyService}get maxZoom(){return this.#Mu}set maxZoom(t){this.#Mu=t}get minZoom(){return this.#Iu}set minZoom(t){this.#Iu=t}setTextLayerMode(t){this.#Kc=t}get pageViewMode(){return this.#Tu}set pageViewMode(t){if(this.#Tu!==t){this.#Tu=t;if(!this.#Cu&&"infinite-scroll"===t){this.#Cu=this.#Lu(this.container.offsetParent);this.#Cu&&watchScroll(this.#Cu,this._scrollUpdate.bind(this))}this.eventBus.dispatch("pageviewmodechanged",{source:this,pageViewMode:t})}}#Lu(t){for(;t;){if(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)return t;t=t.parentElement}return null}get pagesCount(){return this._pages.length}getPageView(t){return this._pages[t]}getCachedPageViews(){return new Set(this.#uu)}get pageViewsReady(){return this._pages.every((t=>t?.pdfPage))}get renderForms(){return this.#Oc===V.AnnotationMode.ENABLE_FORMS}get enableScripting(){return!!this._scriptingManager}get currentPageNumber(){return this._currentPageNumber}set currentPageNumber(t){if(!Number.isInteger(t))throw new Error("Invalid page number.");if(!this.pdfDocument)return;const e=Math.abs(this._currentPageNumber-t)<=2;this._setCurrentPageNumber(t,!0)||n.NgxConsole.error(`currentPageNumber: "${t}" is not a valid page.`);if(this.pageFlip){e?this.pageFlip.flip(t-1):this.pageFlip.turnToPage(t-1);this.ensureAdjacentPagesAreLoaded()}}hidePagesDependingOnpageViewMode(){"book"===this.pageViewMode&&(this.pageFlip||setTimeout((()=>{if(!this.pageFlip){const t=this._pages[0].div,e=t.parentElement,i=e.parentElement;i.style.width=2*t.clientWidth+"px";i.style.overflow="hidden";i.style.marginLeft="auto";i.style.marginRight="auto";this.pageFlip=new PageFlip(e,{width:t.clientWidth,height:t.clientHeight,showCover:!0,size:"fixed"},this.cspPolicyService);this.pageFlip.loadFromHTML(this.container.querySelectorAll(".page"));this.pageFlip.on("flip",(t=>{this._currentPageNumber!==t.data+1&&this._setCurrentPageNumber(t.data+1,!1)}))}}),100))}async _setCurrentPageNumber(t,e=!1){if(this._currentPageNumber===t){e&&this.#ku();return!0}if(!(0<t&&t<=this.pagesCount))return!1;const i=this._currentPageNumber;this._currentPageNumber=t;this.hidePagesDependingOnpageViewMode();if("book"===this.pageViewMode||"infinite-scroll"===this.pageViewMode){const t=this._pages[this.currentPageNumber-1];if(t.div.parentElement.classList.contains("spread"))t.div.parentElement.childNodes.forEach((async t=>{const e=Number(t.getAttribute("data-page-number")),i=this._pages[e-1];await this.#cc(i);this.renderingQueue.renderView(i);t.style.display="inline-block"}));else{await this.#cc(t);this.renderingQueue.renderView(t);"book"===this.#Tu&&this.ensureAdjacentPagesAreLoaded()}}this.eventBus.dispatch("pagechanging",{source:this,pageNumber:t,pageLabel:this._pageLabels?.[t-1]??null,previous:i});e&&this.#ku();return!0}addPageToRenderQueue(t=0){if(t>=0&&t<=this._pages.length-1){const e=this._pages[t];if(e.renderingState===r.INITIAL){this.#cc(e).then((()=>{this.renderingQueue.renderView(e)}));return!0}}return!1}async ensureAdjacentPagesAreLoaded(){const t=[0,1,-1,2,-2,-3];let e=0;this.currentPageNumber%2==1&&(e=-1);let i=!1;for(const s of t){const t=this.currentPageNumber+s+e;if(t>=0&&t<this._pages.length)try{const e=this._pages[t];await this.#cc(e);if(this._pages.some((t=>t.renderingState===r.RUNNING||t.renderingState===r.PAUSED))||i){const loader=()=>this.adjacentPagesRenderer(loader,t);this.eventBus._on("pagerendered",loader);this.eventBus._on("thumbnailRendered",loader)}else i=this.adjacentPagesRenderer(null,t)}catch(e){n.NgxConsole.log("Exception during pre-rendering page %s",t,e)}}}adjacentPagesRenderer(t,e){if(this._pages.find((t=>t.renderingState===r.RUNNING)))return!0;const i=this._pages.find((t=>t.renderingState===r.PAUSED));if(i){this.renderingQueue.renderView(i);return!0}if(t){this.eventBus._off("pagerendered",t);this.eventBus._off("thumbnailRendered",t)}if(e>=0&&e<this._pages.length){const t=this._pages[e];if(t.renderingState===r.INITIAL){this.renderingQueue.renderView(t);return!0}}return!1}get currentPageLabel(){return this._pageLabels?.[this._currentPageNumber-1]??null}set currentPageLabel(t){if(!this.pdfDocument)return;let e=0|t;if(this._pageLabels){const i=this._pageLabels.indexOf(t);i>=0&&(e=i+1)}this._setCurrentPageNumber(e,!0)||n.NgxConsole.error(`currentPageLabel: "${t}" is not a valid page.`)}get currentScale(){return 0!==this._currentScale?this._currentScale:1}set currentScale(t){if(isNaN(t))throw new Error("Invalid numeric scale.");this.pdfDocument&&this.#Fu(t,{noScroll:!1})}get currentScaleValue(){return this._currentScaleValue}set currentScaleValue(t){this.pdfDocument&&this.#Fu(t,{noScroll:!1})}get pagesRotation(){return this._pagesRotation}set pagesRotation(t){if(!isValidRotation(t))throw new Error("Invalid pages rotation angle.");if(!this.pdfDocument)return;(t%=360)<0&&(t+=360);if(this._pagesRotation===t)return;this._pagesRotation=t;const e=this._currentPageNumber;this.refresh(!0,{rotation:t});this._currentScaleValue&&this.#Fu(this._currentScaleValue,{noScroll:!0});this.eventBus.dispatch("rotationchanging",{source:this,pagesRotation:t,pageNumber:e});this.defaultRenderingQueue&&this.update()}get firstPagePromise(){return this.pdfDocument?this._firstPageCapability.promise:null}get onePageRendered(){return this.pdfDocument?this._onePageRenderedCapability.promise:null}get pagesPromise(){return this.pdfDocument?this._pagesCapability.promise:null}get _layerProperties(){const t=this;return(0,V.shadow)(this,"_layerProperties",{get annotationEditorUIManager(){return t.#mu},get annotationStorage(){return t.pdfDocument?.annotationStorage},get downloadManager(){return t.downloadManager},get enableScripting(){return!!t._scriptingManager},get fieldObjectsPromise(){return t.pdfDocument?.getFieldObjects()},get findController(){return t.findController},get customFindController(){return t.customFindController},get hasJSActionsPromise(){return t.pdfDocument?.hasJSActions()},get linkService(){return t.linkService}})}#Ru(t){const e={annotationEditorMode:this.#gu,annotationMode:this.#Oc,textLayerMode:this.#Kc};if(!t)return e;t.includes(V.PermissionFlag.COPY)||this.#Kc!==w||(e.textLayerMode=v);t.includes(V.PermissionFlag.MODIFY_CONTENTS)||(e.annotationEditorMode=V.AnnotationEditorType.DISABLE);t.includes(V.PermissionFlag.MODIFY_ANNOTATIONS)||t.includes(V.PermissionFlag.FILL_INTERACTIVE_FORMS)||this.#Oc!==V.AnnotationMode.ENABLE_FORMS||(e.annotationMode=V.AnnotationMode.ENABLE);return e}async#Nu(t){if("hidden"===document.visibilityState||!this.container.offsetParent||0===this._getVisiblePages().views.length)return;const e=Promise.withResolvers(),i=new AbortController;document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&e.resolve()}),{signal:"function"==typeof AbortSignal.any?AbortSignal.any([t,i.signal]):t});await Promise.race([this._onePageRenderedCapability.promise,e.promise]);i.abort()}async getAllText(){const t=[],e=[];for(let i=1,n=this.pdfDocument.numPages;i<=n;++i){if(this.#xu)return null;e.length=0;const n=await this.pdfDocument.getPage(i),{items:s}=await n.getTextContent();for(const t of s){t.str&&e.push(t.str);t.hasEOL&&e.push("\n")}t.push(removeNullCharacters(e.join("")))}return t.join("\n")}#Bu(t,e){const i=document.getSelection(),{focusNode:s,anchorNode:a}=i;if(a&&s&&i.containsNode(this.#Au)){if(this.#yu||t===v){(0,U.stopEvent)(e);return}this.#yu=!0;const{classList:i}=this.viewer;i.add("copyAll");const s=new AbortController;window.addEventListener("keydown",(t=>this.#xu="Escape"===t.key),{signal:s.signal});this.getAllText().then((async t=>{null!==t&&await navigator.clipboard.writeText(t)})).catch((t=>{n.NgxConsole.warn(`Something goes wrong when extracting the text: ${t.message}`)})).finally((()=>{this.#yu=!1;this.#xu=!1;s.abort();i.remove("copyAll")}));(0,U.stopEvent)(e)}}setDocument(t){if(this.pdfDocument){this.eventBus.dispatch("pagesdestroy",{source:this});this._cancelRendering();this._resetView();this.findController?.setDocument(null);this.customFindController?.setDocument(null);this._scriptingManager?.setDocument(null);this.#mu?.destroy();this.#mu=null}this.pdfDocument=t;if(!t)return;const e=t.numPages,i=t.getPage(1),s=t.getOptionalContentConfig({intent:"display"}),a=this.#Dc?t.getPermissions():Promise.resolve(),{eventBus:r,pageColors:o,viewer:l}=this;this.#ed=new AbortController;const{signal:h}=this.#ed;if(e>Ae){n.NgxConsole.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");const t=this._scrollMode=y.PAGE;r.dispatch("scrollmodechanged",{source:this,mode:t})}this._pagesCapability.promise.then((()=>{r.dispatch("pagesloaded",{source:this,pagesCount:e})}),(()=>{}));r._on("pagerender",(t=>{const e=this._pages[t.pageNumber-1];e&&this.#uu.push(e)}),{signal:h});const onAfterDraw=t=>{if(!t.cssTransform){this._onePageRenderedCapability.resolve({timestamp:t.timestamp});r._off("pagerendered",onAfterDraw)}};r._on("pagerendered",onAfterDraw,{signal:h});Promise.all([i,a]).then((([i,a])=>{if(t!==this.pdfDocument)return;this._firstPageCapability.resolve(i);this._optionalContentConfigPromise=s;const{annotationEditorMode:d,annotationMode:c,textLayerMode:u}=this.#Ru(a);if(u!==b){const t=this.#Au=document.createElement("div");t.id="hiddenCopyElement";l.before(t)}if("function"==typeof AbortSignal.any&&d!==V.AnnotationEditorType.DISABLE){const e=d;if(t.isPureXfa)n.NgxConsole.warn("Warning: XFA-editing is not implemented.");else if(isValidAnnotationEditorMode(e)){this.#mu=new j.AnnotationEditorUIManager(this.container,l,this.#Ue,r,t,o,this.#pu,this.#Je,this.#ti,this.#ei,this.#gi,this.#bu,this.#_u);r.dispatch("annotationeditoruimanager",{source:this,uiManager:this.#mu});if(e!==V.AnnotationEditorType.NONE){e===V.AnnotationEditorType.STAMP&&this.#gi?.loadModel("altText");this.#mu.updateMode(e)}}else n.NgxConsole.error(`Invalid AnnotationEditor mode: ${e}`)}const p=this._scrollMode===y.PAGE?null:l,g=this.currentScale,m=i.getViewport({scale:g*j.PixelsPerInch.PDF_TO_CSS_UNITS});l.style.setProperty("--scale-factor",m.scale);o?.background&&l.style.setProperty("--page-bg-color",o.background);if("CanvasText"===o?.foreground||"Canvas"===o?.background){l.style.setProperty("--hcm-highlight-filter",t.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight"));l.style.setProperty("--hcm-highlight-selected-filter",t.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","ButtonText"))}for(let t=1;t<=e;++t){const e=new PDFPageView({container:p,eventBus:r,id:t,scale:g,defaultViewport:m.clone(),optionalContentConfigPromise:s,renderingQueue:this.renderingQueue,textLayerMode:u,annotationMode:c,imageResourcesPath:this.imageResourcesPath,maxCanvasPixels:this.maxCanvasPixels,pageColors:o,l10n:this.l10n,layerProperties:this._layerProperties,enableHWA:this.#c});this._pages.push(e)}this._pages[0]?.setPdfPage(i);this._scrollMode===y.PAGE?this.#Ou():this._spreadMode!==A.NONE&&this._updateSpreadMode();this.#Nu(h).then((async()=>{if(t!==this.pdfDocument)return;this.findController?.setDocument(t);this.customFindController?.setDocument(t);this._scriptingManager?.setDocument(t);this.#Au&&document.addEventListener("copy",this.#Bu.bind(this,u),{signal:h});this.#mu&&r.dispatch("annotationeditormodechanged",{source:this,mode:this.#gu});if(t.loadingParams.disableAutoFetch||e>xe){this._pagesCapability.resolve();return}let i=e-1;if(i<=0)this._pagesCapability.resolve();else{"book"===this.#Tu&&await this.ensureAdjacentPagesAreLoaded();for(let s=2;s<=e;++s){const e=t.getPage(s).then((t=>{const e=this._pages[s-1];e.pdfPage||e.setPdfPage(t);0==--i&&this._pagesCapability.resolve()}),(t=>{n.NgxConsole.error(`Unable to get page ${s} to initialize viewer`,t);0==--i&&this._pagesCapability.resolve()}));s%Ee==0&&await e}}}));this.hidePagesDependingOnpageViewMode();r.dispatch("pagesinit",{source:this});t.getMetadata().then((({info:e})=>{t===this.pdfDocument&&e.Language&&(l.lang=e.Language)}));this.defaultRenderingQueue&&this.update()})).catch((t=>{n.NgxConsole.error("Unable to initialize viewer",t);this._pagesCapability.reject(t)}))}setPageLabels(t){if(this.pdfDocument){if(t)if(Array.isArray(t)&&this.pdfDocument.numPages===t.length)this._pageLabels=t;else{this._pageLabels=null;n.NgxConsole.error("setPageLabels: Invalid page labels.")}else this._pageLabels=null;for(let t=0,e=this._pages.length;t<e;t++)this._pages[t].setPageLabel(this._pageLabels?.[t]??null)}}_resetView(){this._pages=[];this._currentPageNumber=1;this._currentScale=0;this._currentScaleValue=null;this._pageLabels=null;const t=this.defaultCacheSize||10;this.#uu=new PDFPageViewBuffer(t);this._location=null;this._pagesRotation=0;this._optionalContentConfigPromise=null;this._firstPageCapability=Promise.withResolvers();this._onePageRenderedCapability=Promise.withResolvers();this._pagesCapability=Promise.withResolvers();this._scrollMode=y.VERTICAL;this._previousScrollMode=y.UNKNOWN;this._spreadMode=A.NONE;this.#Su={previousPageNumber:1,scrollDown:!0,pages:[]};this.#ed?.abort();this.#ed=null;this.viewer.textContent="";this._updateScrollMode();this.viewer.removeAttribute("lang");this.#Au?.remove();this.#Au=null;this.#Vu()}#Ou(){if(this._scrollMode!==y.PAGE)throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");const t=this._currentPageNumber,e=this.#Su,i=this.viewer;i.textContent="";e.pages.length=0;if(this._spreadMode!==A.NONE||this.isInPresentationMode){const n=new Set,s=this._spreadMode-1;if(-1===s)n.add(t-1);else if(t%2!==s){n.add(t-1);n.add(t)}else{n.add(t-2);n.add(t-1)}const a=document.createElement("div");a.className="spread";if(this.isInPresentationMode){const t=document.createElement("div");t.className="dummyPage";a.append(t)}for(const t of n){const i=this._pages[t];if(i){a.append(i.div);e.pages.push(i)}}i.append(a)}else{const n=this._pages[t-1];i.append(n.div);e.pages.push(n)}e.scrollDown=t>=e.previousPageNumber;e.previousPageNumber=t}_scrollUpdate(){0!==this.pagesCount&&this.update()}scrollPagePosIntoView(t,e){const i=this._pages[t-1].div;if(e){const n={...e};if("string"==typeof n.top&&n.top.endsWith("%")){const t=Number(n.top.replace("%","")),e=this.viewer.querySelector(".page")?.clientHeight;let s=i.clientHeight??e;const a=this.viewer.parentElement.clientHeight;s=Math.max(0,s-a);n.top=t*s/100}if("string"==typeof n.left&&n.left.endsWith("%")){const t=Number(n.left.replace("%","")),e=this.viewer.querySelector(".page")?.clientWidth,s=i.clientWidth??e;n.left=t*s/100}this.#Hu({div:i,id:t},n)}else this.#Hu({div:i,id:t})}#Hu(t,e=null){if(!t)return;const{div:i,id:n}=t;this._currentPageNumber!==n&&this._setCurrentPageNumber(n);if(this._scrollMode===y.PAGE){this.#Ou();this.update()}if(!e&&!this.isInPresentationMode){const t=i.offsetLeft+i.clientLeft,n=t+i.clientWidth,{scrollLeft:s,clientWidth:a}=this.container;(this._scrollMode===y.HORIZONTAL||t<s||n>s+a)&&(e={left:0,top:0})}scrollIntoView(i,e,!1,"infinite-scroll"===this.pageViewMode);!this._currentScaleValue&&this._location&&(this._location=null)}#zu(t){return t===this._currentScale||Math.abs(t-this._currentScale)<1e-15}#Uu(t,e,{noScroll:i=!1,preset:n=!1,drawingDelay:s=-1,origin:a=null}){const r=isNaN(Number(this.currentScale))?void 0:Number(this.currentScale),o=this.currentScaleValue;this._currentScaleValue=e.toString();if(this.#zu(t)){n&&this.eventBus.dispatch("scalechanging",{source:this,scale:t,presetValue:e,previousScale:r,previousPresetValue:o,noScroll:i});return}this.viewer.style.setProperty("--scale-factor",t*j.PixelsPerInch.PDF_TO_CSS_UNITS);const l=s>=0&&s<1e3;this.refresh(!0,{scale:t,drawingDelay:l?s:-1});l&&(this.#Pu=setTimeout((()=>{this.#Pu=null;this.refresh()}),s));this._currentScale=t;if(!i){let e,i=this._currentPageNumber;if(this._location&&!this.isInPresentationMode&&!this.isChangingPresentationMode){i=this._location.pageNumber;e=[null,{name:"XYZ"},this._location.left,this._location.top,null]}this.scrollPageIntoView({pageNumber:i,destArray:e,allowNegativeOffset:!0});if(Array.isArray(a)){const e=t/r-1,[i,n]=this.containerTopLeft;this.container.scrollLeft+=(a[0]-n)*e;this.container.scrollTop+=(a[1]-i)*e}}this.eventBus.dispatch("scalechanging",{source:this,scale:t,presetValue:n?e:void 0,previousScale:r,previousPresetValue:o,noScroll:i});this.defaultRenderingQueue&&this.update()}get#ju(){return this._spreadMode!==A.NONE&&this._scrollMode!==y.HORIZONTAL?2:1}#Fu(t,e){t||(t="auto");this.maxZoom&&this.maxZoom===this.minZoom&&(t=this.maxZoom);let i=parseFloat(t);if(this._currentScale!==i)if(i>0){e.preset=!1;this.#Uu(i,t,e)}else{const s=this._pages[this._currentPageNumber-1];if(!s)return;let a=40,r=5;if(this.isInPresentationMode){a=r=4;this._spreadMode!==A.NONE&&(a*=2)}else this.removePageBorders?a=r=0:this._scrollMode===y.HORIZONTAL&&([a,r]=[r,a]);const o=(this.container.clientWidth-a)/s.width*s.scale/this.#ju,l=(this.container.clientHeight-r)/s.height*s.scale;switch(t){case"page-actual":i=1;break;case"page-width":i=o;break;case"page-height":i=l;break;case"page-fit":i=Math.min(o,l);break;case"auto":const e=isPortraitOrientation(s)?o:Math.min(l,o);i=Math.min(1.25,e);break;default:n.NgxConsole.error(`#setScale: "${t}" is an unknown zoom value.`);return}e.preset=!0;this.#Uu(i,t,e)}}#ku(){const t=this._pages[this._currentPageNumber-1];this.isInPresentationMode&&this.#Fu(this._currentScaleValue,{noScroll:!0});this.#Hu(t)}pageLabelToPageNumber(t){if(!this._pageLabels)return null;const e=this._pageLabels.indexOf(t);return e<0?null:e+1}scrollPageIntoView({pageNumber:t,destArray:e=null,allowNegativeOffset:i=!1,ignoreDestinationZoom:a=!1}){if(!this.pdfDocument)return;const r=Number.isInteger(t)&&this._pages[t-1];if(!r){n.NgxConsole.error(`scrollPageIntoView: "${t}" is not a valid pageNumber parameter.`);return}if(this.isInPresentationMode||!e){this._setCurrentPageNumber(t,!0);return}let o,l,h=0,d=0,c=0,u=0;const p=r.rotation%180!=0,g=(p?r.height:r.width)/r.scale/j.PixelsPerInch.PDF_TO_CSS_UNITS,m=(p?r.width:r.height)/r.scale/j.PixelsPerInch.PDF_TO_CSS_UNITS;let f=0;switch(e[1].name){case"XYZ":h=e[2];d=e[3];f=e[4];h=null!==h?h:0;d=null!==d?d:m;break;case"Fit":case"FitB":f="page-fit";break;case"FitH":case"FitBH":d=e[2];f="page-width";if(null===d&&this._location){h=this._location.left;d=this._location.top}else("number"!=typeof d||d<0)&&(d=m);break;case"FitV":case"FitBV":h=e[2];c=g;u=m;f="page-height";break;case"FitR":h=e[2];d=e[3];c=e[4]-h;u=e[5]-d;let t=40,i=5;this.removePageBorders&&(t=i=0);o=(this.container.clientWidth-t)/c/j.PixelsPerInch.PDF_TO_CSS_UNITS;l=(this.container.clientHeight-i)/u/j.PixelsPerInch.PDF_TO_CSS_UNITS;f=Math.min(Math.abs(o),Math.abs(l));break;default:n.NgxConsole.error(`scrollPageIntoView: "${e[1].name}" is not a valid destination type.`);return}a||(f&&f!==this._currentScale?this.currentScaleValue=f:0===this._currentScale&&(this.currentScaleValue=s));this.#cc(r).then((()=>{this.renderingQueue.renderView(r);"single"===this.pageViewMode&&this.currentPageNumber!==t&&(this.currentPageNumber=t)}));if("page-fit"===f&&!e[4]){this.#Hu(r);return}const b=[r.viewport.convertToViewportPoint(h,d),r.viewport.convertToViewportPoint(h+c,d+u)];let w=Math.min(b[0][0],b[1][0]),v=Math.min(b[0][1],b[1][1]);if(!i){w=Math.max(w,0);v=Math.max(v,0)}this.#Hu(r,{left:w,top:v})}_updateLocation(t){const e=this._currentScale,i=this._currentScaleValue,n=parseFloat(i)===e?Math.round(1e4*e)/100:i,s=t.id,a=this._pages[s-1],r=this.container,o=a.getPagePoint(r.scrollLeft-t.x,r.scrollTop-t.y),l=Math.round(o[0]),h=Math.round(o[1]);let d=`#page=${s}`;this.isInPresentationMode||(d+=`&zoom=${n},${l},${h}`);this._location={pageNumber:s,scale:n,top:h,left:l,rotation:this._pagesRotation,pdfOpenParams:d}}update(t=!1){this.scrollMode===y.PAGE?this.viewer.classList.add("singlePageView"):this.viewer.classList.remove("singlePageView");const e=this._getVisiblePages(),i=e.views,n=i.length;if(0===n)return;const s=this.defaultCacheSize||10,a=Math.max(s,2*n+1);this.#uu.resize(a,e.ids);this.renderingQueue.renderHighestPriority(e);const r=this._spreadMode===A.NONE&&(this._scrollMode===y.PAGE||this._scrollMode===y.VERTICAL),o=this._currentPageNumber;let l=!1;for(const t of i){if(t.percent<100)break;if(t.id===o&&r){l=!0;break}}this.scrollMode===y.PAGE||t||this._setCurrentPageNumber(l?o:i[0].id);this._updateLocation(e.first);this.eventBus.dispatch("updateviewarea",{source:this,location:this._location});this.hidePagesDependingOnpageViewMode()}#Wu(){const t=this._getVisiblePages(),e=[],{ids:i,views:n}=t;for(const t of n){const{view:n}=t;n.hasEditableAnnotations()?e.push(t):i.delete(n.id)}if(0===e.length)return null;this.renderingQueue.renderHighestPriority({first:e[0],last:e.at(-1),views:e,ids:i});return i}containsElement(t){return this.container.contains(t)}focus(){this.container.focus()}get _isContainerRtl(){return"rtl"===getComputedStyle(this.container).direction}get isInPresentationMode(){return this.presentationModeState===d}get isChangingPresentationMode(){return this.presentationModeState===h}get isHorizontalScrollbarEnabled(){return!this.isInPresentationMode&&this.container.scrollWidth>this.container.clientWidth}get isVerticalScrollbarEnabled(){return!this.isInPresentationMode&&this.container.scrollHeight>this.container.clientHeight}_getVisiblePages(){const t=this._scrollMode===y.PAGE?this.#Su.pages:this._pages,e=this._scrollMode===y.HORIZONTAL,i=e&&this._isContainerRtl;return getVisibleElements({scrollEl:this.container,views:t,sortByVisibility:!0,horizontal:e,rtl:i})}cleanup(){for(const t of this._pages)t.renderingState!==r.FINISHED&&t.reset()}_cancelRendering(){for(const t of this._pages)t.cancelRendering()}async#cc(t){if(t.pdfPage)return t.pdfPage;try{const e=await this.pdfDocument.getPage(t.id);t.pdfPage||t.setPdfPage(e);return e}catch(t){n.NgxConsole.error("Unable to get page for page view",t);return null}}#uc(t){if(1===t.first?.id)return!0;if(t.last?.id===this.pagesCount)return!1;switch(this._scrollMode){case y.PAGE:return this.#Su.scrollDown;case y.HORIZONTAL:return this.scroll.right}return this.scroll.down}forceRendering(t){const e=t||this._getVisiblePages(),i=this.#uc(e),n=this._spreadMode!==A.NONE&&this._scrollMode!==y.HORIZONTAL,s=this.renderingQueue.getHighestPriority(e,this._pages,i,n);if(s){this.#cc(s).then((()=>{this.renderingQueue.renderView(s)}));return!0}return!1}get hasEqualPageSizes(){const t=this._pages[0];for(let e=1,i=this._pages.length;e<i;++e){const i=this._pages[e];if(i.width!==t.width||i.height!==t.height)return!1}return!0}getPagesOverview(){let t;return this._pages.map((e=>{const i=e.pdfPage.getViewport({scale:1}),n=isPortraitOrientation(i);if(void 0===t)t=n;else if(this.enablePrintAutoRotate&&n!==t)return{width:i.height,height:i.width,rotation:(i.rotation-90)%360};return{width:i.width,height:i.height,rotation:i.rotation}}))}get optionalContentConfigPromise(){if(!this.pdfDocument)return Promise.resolve(null);if(!this._optionalContentConfigPromise){n.NgxConsole.error("optionalContentConfigPromise: Not initialized yet.");return this.pdfDocument.getOptionalContentConfig({intent:"display"})}return this._optionalContentConfigPromise}set optionalContentConfigPromise(t){if(!(t instanceof Promise))throw new Error(`Invalid optionalContentConfigPromise: ${t}`);if(this.pdfDocument&&this._optionalContentConfigPromise){this._optionalContentConfigPromise=t;this.refresh(!1,{optionalContentConfigPromise:t});this.eventBus.dispatch("optionalcontentconfigchanged",{source:this,promise:t})}}get scrollMode(){return this._scrollMode}set scrollMode(t){if(this._scrollMode!==t){if(!isValidScrollMode(t))throw new Error(`Invalid scroll mode: ${t}`);if(!(this.pagesCount>Ae)){this._previousScrollMode=this._scrollMode;this._scrollMode=t;this.eventBus.dispatch("scrollmodechanged",{source:this,mode:t});this._updateScrollMode(this._currentPageNumber)}}}_updateScrollMode(t=null){const e=this._scrollMode,i=this.viewer;i.classList.toggle("scrollHorizontal",e===y.HORIZONTAL);i.classList.toggle("scrollWrapped",e===y.WRAPPED);if(this.pdfDocument&&t){e===y.PAGE?this.#Ou():this._previousScrollMode===y.PAGE&&this._updateSpreadMode();this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#Fu(this._currentScaleValue,{noScroll:!0});this._setCurrentPageNumber(t,!0);this.update()}}get spreadMode(){return this._spreadMode}set spreadMode(t){if(this._spreadMode!==t){if(!isValidSpreadMode(t))throw new Error(`Invalid spread mode: ${t}`);this._spreadMode=t;this.eventBus.dispatch("spreadmodechanged",{source:this,mode:t});this._updateSpreadMode(this._currentPageNumber)}}_updateSpreadMode(t=null){if(!this.pdfDocument)return;const e=this.viewer,i=this._pages;if(this._scrollMode===y.PAGE)this.#Ou();else{e.textContent="";if(this._spreadMode===A.NONE)for(const t of this._pages)e.append(t.div);else{const t=this._spreadMode-1;let n=null;for(let s=0,a=i.length;s<a;++s){if(null===n){n=document.createElement("div");n.className="spread";e.append(n)}else if(s%2===t){n=n.cloneNode(!1);e.append(n)}n.append(i[s].div)}}}this.hidePagesDependingOnpageViewMode();if(t){this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#Fu(this._currentScaleValue,{noScroll:!0});this._setCurrentPageNumber(t,!0);this.update()}}_getPageAdvance(t,e=!1){if("book"===this.pageViewMode)return 2;switch(this._scrollMode){case y.WRAPPED:{const{views:i}=this._getVisiblePages(),n=new Map;for(const{id:t,y:e,percent:s,widthPercent:a}of i){if(0===s||a<100)continue;let i=n.get(e);i||n.set(e,i||=[]);i.push(t)}for(const i of n.values()){const n=i.indexOf(t);if(-1===n)continue;const s=i.length;if(1===s)break;if(e)for(let e=n-1,s=0;e>=s;e--){const n=i[e],s=i[e+1]-1;if(n<s)return t-s}else for(let e=n+1,a=s;e<a;e++){const n=i[e],s=i[e-1]+1;if(n>s)return s-t}if(e){const e=i[0];if(e<t)return t-e+1}else{const e=i[s-1];if(e>t)return e-t+1}break}break}case y.HORIZONTAL:break;case y.PAGE:case y.VERTICAL:{if(this._spreadMode===A.NONE)break;const i=this._spreadMode-1;if(e&&t%2!==i)break;if(!e&&t%2===i)break;const{views:n}=this._getVisiblePages(),s=e?t-1:t+1;for(const{id:t,percent:e,widthPercent:i}of n)if(t===s){if(e>0&&100===i)return 2;break}break}}return 1}nextPage(){const t=this._currentPageNumber,e=this.pagesCount;if(t>=e)return!1;const i=this._getPageAdvance(t,!1)||1;this.currentPageNumber=Math.min(t+i,e);return!0}previousPage(){const t=this._currentPageNumber;if(t<=1)return!1;const e=this._getPageAdvance(t,!0)||1;this.currentPageNumber=Math.max(t-e,1);return!0}updateScale({drawingDelay:t,scaleFactor:e=null,steps:i=null,origin:n}){if(null===i&&null===e)throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided.");if(!this.pdfDocument)return;let s=this._currentScale;if(e>0&&1!==e)s=Math.round(s*e*100)/100;else if(i){const t=i>0?1.1:1/1.1,e=i>0?Math.ceil:Math.floor;i=Math.abs(i);do{s=e(10*(s*t).toFixed(2))/10}while(--i>0)}const r=Number(this.minZoom)??a;s=Math.max(r,s);const o=Number(this.maxZoom)??10;s=Math.min(o,s);this.#Fu(s,{noScroll:!1,drawingDelay:t,origin:n})}increaseScale(t={}){this.updateScale({...t,steps:t.steps??1})}decreaseScale(t={}){this.updateScale({...t,steps:-(t.steps??1)})}#Du(t=this.container.clientHeight){if(t!==this.#Eu){this.#Eu=t;C.setProperty("--viewer-container-height",`${t}px`)}}#td(t){for(const e of t)if(e.target===this.container){this.#Du(Math.floor(e.borderBoxSize[0].blockSize));this.#fu=null;break}}get containerTopLeft(){return this.#fu||=[this.container.offsetTop,this.container.offsetLeft]}#Vu(){this.#wu?.abort();this.#wu=null;if(null!==this.#vu){clearTimeout(this.#vu);this.#vu=null}}get annotationEditorMode(){return this.#mu?this.#gu:V.AnnotationEditorType.DISABLE}set annotationEditorMode({mode:t,editId:e=null,isFromKeyboard:i=!1}){if(!this.#mu)throw new Error("The AnnotationEditor is not enabled.");if(this.#gu===t)return;if(!isValidAnnotationEditorMode(t))throw new Error(`Invalid AnnotationEditor mode: ${t}`);if(!this.pdfDocument)return;t===V.AnnotationEditorType.STAMP&&this.#gi?.loadModel("altText");const{eventBus:n}=this,updater=()=>{this.#Vu();this.#gu=t;this.#mu.updateMode(t,e,i);n.dispatch("annotationeditormodechanged",{source:this,mode:t})};if(t===V.AnnotationEditorType.NONE||this.#gu===V.AnnotationEditorType.NONE){const e=t!==V.AnnotationEditorType.NONE;e||this.pdfDocument.annotationStorage.resetModifiedIds();for(const t of this._pages)t.toggleEditingMode(e);const i=this.#Wu();if(e&&i){this.#Vu();this.#wu=new AbortController;const t=AbortSignal.any([this.#ed.signal,this.#wu.signal]);n._on("pagerendered",(({pageNumber:t})=>{i.delete(t);0===i.size&&(this.#vu=setTimeout(updater,0))}),{signal:t});return}}updater()}refresh(t=!1,e=Object.create(null)){if(this.pdfDocument){for(const t of this._pages)t.update(e);if(null!==this.#Pu){clearTimeout(this.#Pu);this.#Pu=null}t||this.update()}}getSerializedAnnotations(){const t=this.pdfDocument.annotationStorage.getAll();if(t){return Object.values(t).filter((t=>t.serialize)).map((t=>t.serialize())).filter((t=>void 0!==t?.annotationType))}return null}async addEditorAnnotation(t){try{"string"==typeof t&&(t=JSON.parse(t))}catch(t){n.NgxConsole.error(`Please pass a JSON string or an Array of JSON objects to addEditorAnnotation: "${t.message}".`);return}Array.isArray(t)||(t=[t]);await this.#mu.addSerializedEditor(t,!0,!0,!1)}removeEditorAnnotations(t=()=>!0){this.#mu.removeEditors(t)}destroyBookMode(){if(this.pageFlip){this.pageFlip.destroy();this.pageFlip=null}}stopRendering(){this._cancelRendering()}}class SecondaryToolbar{#Do;constructor(t,e){this.#Do=t;const i=[{element:t.presentationModeButton,eventName:"presentationmode",close:!0},{element:t.printButton,eventName:"print",close:!0},{element:t.downloadButton,eventName:"download",close:!0},{element:t.viewBookmarkButton,eventName:null,close:!0},{element:t.firstPageButton,eventName:"firstpage",close:!0},{element:t.lastPageButton,eventName:"lastpage",close:!0},{element:t.pageRotateCwButton,eventName:"rotatecw",close:!1},{element:t.pageRotateCcwButton,eventName:"rotateccw",close:!1},{element:t.cursorSelectToolButton,eventName:"switchcursortool",eventDetails:{tool:x},close:!0},{element:t.cursorHandToolButton,eventName:"switchcursortool",eventDetails:{tool:E},close:!0},{element:t.scrollPageButton,eventName:"switchscrollmode",eventDetails:{mode:y.PAGE},close:!0},{element:t.scrollVerticalButton,eventName:"switchscrollmode",eventDetails:{mode:y.VERTICAL},close:!0},{element:t.scrollHorizontalButton,eventName:"switchscrollmode",eventDetails:{mode:y.HORIZONTAL},close:!0},{element:t.scrollWrappedButton,eventName:"switchscrollmode",eventDetails:{mode:y.WRAPPED},close:!0},{element:t.spreadNoneButton,eventName:"switchspreadmode",eventDetails:{mode:A.NONE},close:!0},{element:t.spreadOddButton,eventName:"switchspreadmode",eventDetails:{mode:A.ODD},close:!0},{element:t.spreadEvenButton,eventName:"switchspreadmode",eventDetails:{mode:A.EVEN},close:!0},{element:t.imageAltTextSettingsButton,eventName:"imagealttextsettings",close:!0},{element:t.documentPropertiesButton,eventName:"documentproperties",close:!0}];i.push({element:t.openFileButton,eventName:"openfile",close:!0});this.eventBus=e;this.opened=!1;this.#Gl(i);this.reset()}get isOpen(){return this.opened}setPageNumber(t){this.pageNumber=t;this.#Ul()}setPagesCount(t){this.pagesCount=t;this.#Ul()}reset(){this.pageNumber=0;this.pagesCount=0;this.#Ul();this.eventBus.dispatch("switchcursortool",{source:this,reset:!0});this.#$u({mode:y.VERTICAL});this.#Gu({mode:A.NONE})}#Ul(){const{firstPageButton:t,lastPageButton:e,pageRotateCwButton:i,pageRotateCcwButton:n}=this.#Do;t.disabled=this.pageNumber<=1;e.disabled=this.pageNumber>=this.pagesCount;i.disabled=0===this.pagesCount;n.disabled=0===this.pagesCount}#Gl(t){const{eventBus:e}=this,{toggleButton:i}=this.#Do;i.addEventListener("click",this.toggle.bind(this));for(const{element:i,eventName:n,close:s,eventDetails:a}of t)i&&i.addEventListener("click",(t=>{null!==n&&e.dispatch(n,{source:this,...a});s&&this.close();e.dispatch("reporttelemetry",{source:this,details:{type:"buttons",data:{id:i.id}}})}));e._on("cursortoolchanged",this.#qu.bind(this));e._on("scrollmodechanged",this.#$u.bind(this));e._on("spreadmodechanged",this.#Gu.bind(this))}#qu({tool:t,disabled:e}){const{cursorSelectToolButton:i,cursorHandToolButton:n}=this.#Do;toggleCheckedBtn(i,t===x);toggleCheckedBtn(n,t===E);i.disabled=e;n.disabled=e}#$u({mode:t}){const{scrollPageButton:e,scrollVerticalButton:i,scrollHorizontalButton:n,scrollWrappedButton:s,spreadNoneButton:a,spreadOddButton:r,spreadEvenButton:o}=this.#Do;toggleCheckedBtn(e,t===y.PAGE);toggleCheckedBtn(i,t===y.VERTICAL);toggleCheckedBtn(n,t===y.HORIZONTAL);toggleCheckedBtn(s,t===y.WRAPPED);const l=this.pagesCount>Ae;e.disabled=l;i.disabled=l;n.disabled=l;s.disabled=l;const h=t===y.HORIZONTAL;a.disabled=h;r.disabled=h;o.disabled=h}#Gu({mode:t}){const{spreadNoneButton:e,spreadOddButton:i,spreadEvenButton:n}=this.#Do;toggleCheckedBtn(e,t===A.NONE);toggleCheckedBtn(i,t===A.ODD);toggleCheckedBtn(n,t===A.EVEN)}open(){if(this.opened)return;this.opened=!0;const{toggleButton:t,toolbar:e}=this.#Do;toggleExpandedBtn(t,!0,e)}close(){if(!this.opened)return;this.opened=!1;const{toggleButton:t,toolbar:e}=this.#Do;toggleExpandedBtn(t,!1,e)}toggle(){this.opened?this.close():this.open()}}class Toolbar{#Do;#Xu=s;#Mu=10;#Iu=a;constructor(t,e,i,n,s,a=0){this.#Do=t;this.#Xu=i;this.#Mu=s;this.#Iu=n;this.eventBus=e;const r=[{element:t.previous,eventName:"previouspage"},{element:t.next,eventName:"nextpage"},{element:t.zoomIn,eventName:"zoomin"},{element:t.zoomOut,eventName:"zoomout"},{element:t.print,eventName:"print"},{element:t.presentationModeButton,eventName:"presentationmode"},{element:t.download,eventName:"download"},{element:t.editorFreeTextButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:e}=t.editorFreeTextButton;return e.contains("toggled")?V.AnnotationEditorType.NONE:V.AnnotationEditorType.FREETEXT}}},{element:t.editorHighlightButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:e}=t.editorHighlightButton;return e.contains("toggled")?V.AnnotationEditorType.NONE:V.AnnotationEditorType.HIGHLIGHT}}},{element:t.editorInkButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:e}=t.editorInkButton;return e.contains("toggled")?V.AnnotationEditorType.NONE:V.AnnotationEditorType.INK}}},{element:t.editorStampButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:e}=t.editorStampButton;return e.contains("toggled")?V.AnnotationEditorType.NONE:V.AnnotationEditorType.STAMP}},telemetry:{type:"editing",data:{action:"pdfjs.image.icon_click"}}}];this.#Gl(r);this.#Ku({value:a});this.reset()}get maxZoom(){return this.#Mu}set maxZoom(t){this.#Mu=t}get minZoom(){return this.#Iu}set minZoom(t){this.#Iu=t}#Ku({value:t}){let e="normal";switch(t){case 1:e="compact";break;case 2:e="touch"}document.documentElement.setAttribute("data-toolbar-density",e)}#Yu(t,e){const i=new j.ColorPicker({uiManager:t});t.setMainHighlightColorPicker(i);e.append(i.renderMainDropdown())}setPageNumber(t,e){this.pageNumber=t;this.pageLabel=e;this.#Ul(!1)}setPagesCount(t,e){this.pagesCount=t;this.hasPageLabels=e;this.#Ul(!0)}setPageScale(t,e){this.pageScaleValue=(t||e).toString();this.pageScale=e;this.#Ul(!1)}reset(){this.pageNumber=0;this.pageLabel=null;this.hasPageLabels=!1;this.pagesCount=0;const t=this.#Xu||s;this.pageScaleValue=t;Number(t)&&(this.pageScale=Number(t));this.#Ul(!0);this.updateLoadingIndicatorState();this.#Zu({mode:V.AnnotationEditorType.DISABLE})}#Gl(t){const{eventBus:e}=this,{editorHighlightColorPicker:i,editorHighlightButton:n,pageNumber:s,scaleSelect:a}=this.#Do,r=this;for(const{element:i,eventName:n,eventDetails:s,telemetry:a}of t)i&&i.addEventListener("click",(t=>{null!==n&&e.dispatch(n,{source:this,...s,isFromKeyboard:0===t.detail});a&&e.dispatch("reporttelemetry",{source:this,details:a})}));s.addEventListener("click",(function(){this.select()}));s.addEventListener("change",(function(){e.dispatch("pagenumberchanged",{source:r,value:this.value})}));a.addEventListener("change",(function(){"custom"!==this.value&&e.dispatch("scalechanged",{source:r,value:this.value})}));a.addEventListener("click",(function({target:t}){this.value===r.pageScaleValue&&"OPTION"===t.tagName.toUpperCase()&&this.blur()}));a.oncontextmenu=U.noContextMenu;e._on("annotationeditormodechanged",this.#Zu.bind(this));e._on("showannotationeditorui",(({mode:t})=>{if(t===V.AnnotationEditorType.HIGHLIGHT)n.click()}));e._on("toolbardensity",this.#Ku.bind(this));i&&e._on("annotationeditoruimanager",(({uiManager:t})=>{this.#Yu(t,i)}),{once:!0})}#Zu({mode:t}){const{editorFreeTextButton:e,editorFreeTextParamsToolbar:i,editorHighlightButton:n,editorHighlightParamsToolbar:s,editorInkButton:a,editorInkParamsToolbar:r,editorStampButton:o,editorStampParamsToolbar:l}=this.#Do;toggleExpandedBtn(e,t===V.AnnotationEditorType.FREETEXT,i);toggleExpandedBtn(n,t===V.AnnotationEditorType.HIGHLIGHT,s);toggleExpandedBtn(a,t===V.AnnotationEditorType.INK,r);toggleExpandedBtn(o,t===V.AnnotationEditorType.STAMP,l);const h=t===V.AnnotationEditorType.DISABLE;e.disabled=h;n.disabled=h;a.disabled=h;o.disabled=h}#Ul(t=!1){const{pageNumber:e,pagesCount:i,pageScaleValue:n,pageScale:s}=this,r=this.#Do;if(t){if(this.hasPageLabels){r.pageNumber.type="text";r.numPages.setAttribute("data-l10n-id","pdfjs-page-of-pages")}else{r.pageNumber.type="number";r.numPages.setAttribute("data-l10n-id","pdfjs-of-pages");r.numPages.setAttribute("data-l10n-args",JSON.stringify({pagesCount:i}))}r.pageNumber.max=i}if(this.hasPageLabels){r.pageNumber.value=this.pageLabel;r.numPages.setAttribute("data-l10n-args",JSON.stringify({pageNumber:e,pagesCount:i}))}else r.pageNumber.value=e;r.previous.disabled=e<=1;r.next.disabled=e>=i;const o=Number(this.minZoom)??a,l=Number(this.maxZoom)??10;r.zoomOut&&(r.zoomOut.disabled=s<=o);r.zoomIn&&(r.zoomIn.disabled=s>=l);let h=!1;if(r.scaleSelect.options)for(const t of r.scaleSelect.options)if(t.value===n){t.selected=!0;h=!0}else t.selected=!1;if(!h){r.customScaleOption.selected=!0;r.customScaleOption.setAttribute("data-l10n-args",JSON.stringify({scale:Math.round(1e4*s)/100}))}this.eventBus.dispatch("updateuistate",{source:this,widget:"Toolbar",pageNumber:e,pagesCount:i,pageScaleValue:n,pageScale:s})}updateLoadingIndicatorState(t=!1){const{pageNumber:e}=this.#Do;e.classList.toggle("loading",t)}}class ViewHistory{constructor(t,e=20){this.fingerprint=t;this.cacheSize=e;this._initializedPromise=this._readFromStorage().then((t=>{const e=JSON.parse(t||"{}");let i=-1;if(Array.isArray(e.files)){for(;e.files.length>=this.cacheSize;)e.files.shift();for(let t=0,n=e.files.length;t<n;t++){if(e.files[t].fingerprint===this.fingerprint){i=t;break}}}else e.files=[];-1===i&&(i=e.files.push({fingerprint:this.fingerprint})-1);this.file=e.files[i];this.database=e}))}async _writeToStorage(){if(AppOptions.get("disableHistory"))return;const t=JSON.stringify(this.database);try{localStorage.setItem("pdfjs.history",t)}catch(t){}}async _readFromStorage(){if(!AppOptions.get("disableHistory"))try{return localStorage.getItem("pdfjs.history")}catch(t){return}}async set(t,e){await this._initializedPromise;this.file[t]=e;return this._writeToStorage()}async setMultiple(t){await this._initializedPromise;for(const e in t)this.file[e]=t[e];return this._writeToStorage()}async get(t,e){await this._initializedPromise;const i=this.file[t];return void 0!==i?i:e}async getMultiple(t){await this._initializedPromise;const e=Object.create(null);for(const i in t){const n=this.file[i];e[i]=void 0!==n?n:t[i]}return e}}const Se=-1,Pe=1,_e={initialBookmark:document.location.hash.substring(1),_initializedCapability:{...Promise.withResolvers(),settled:!1},appConfig:null,pdfDocument:null,pdfLoadingTask:null,printService:null,pdfViewer:null,pdfThumbnailViewer:null,pdfRenderingQueue:null,pdfPresentationMode:null,pdfDocumentProperties:null,pdfLinkService:null,pdfHistory:null,pdfSidebar:null,pdfOutlineViewer:null,pdfAttachmentViewer:null,pdfLayerViewer:null,pdfCursorTools:null,pdfScriptingManager:null,pdfWorker:null,store:null,downloadManager:null,overlayManager:null,preferences:new class Preferences extends BasePreferences{async _writeToStorage(t){try{localStorage.setItem("pdfjs.preferences",JSON.stringify(t))}catch(t){}}async _readFromStorage(t){try{return{prefs:JSON.parse(localStorage.getItem("pdfjs.preferences"))}}catch(t){return{}}}},toolbar:null,secondaryToolbar:null,eventBus:null,l10n:null,annotationEditorParams:null,imageAltTextSettings:null,isInitialViewSet:!1,isViewerEmbedded:window.parent!==window,url:"",baseUrl:"",mlManager:null,_downloadUrl:"",_eventBusAbortController:null,_windowAbortController:null,_globalAbortController:new AbortController,documentInfo:null,metadata:null,_contentDispositionFilename:null,_contentLength:null,_saveInProgress:!1,_wheelUnusedTicks:0,_wheelUnusedFactor:1,_touchManager:null,_touchUnusedTicks:0,_touchUnusedFactor:1,_PDFBug:null,_hasAnnotationEditors:!1,_title:document.title,_printAnnotationStoragePromise:null,_isCtrlKeyDown:!1,_caretBrowsing:null,_isScrolling:!1,editorUndoBar:null,async initialize(t){this.appConfig=t;this.cspPolicyService=t.cspPolicyService;try{await this.preferences.initializedPromise}catch(t){console.error("initialize:",t)}AppOptions.get("pdfBugEnabled")&&await this._parseHashParams();let e;switch(AppOptions.get("viewerCssTheme")){case 1:e="is-light";break;case 2:e="is-dark"}e&&document.documentElement.classList.add(e);this.l10n=await this.externalServices.createL10n();document.getElementsByTagName("html")[0].dir=this.l10n.getDirection();this.l10n.translate(t.appContainer||document.documentElement);this.isViewerEmbedded&&AppOptions.get("externalLinkTarget")===O.NONE&&AppOptions.set("externalLinkTarget",O.TOP);await this._initializeViewerComponents();this.bindEvents();this.bindWindowEvents();this._initializedCapability.settled=!0;this._initializedCapability.resolve();this.initializeLoadingBar()},async _parseHashParams(){const t=document.location.hash.substring(1);if(!t)return;const{mainContainer:e,viewerContainer:i}=this.appConfig,n=parseQueryString(t),loadPDFBug=async()=>{if(this._PDFBug)return;const{PDFBug:t}=await import(AppOptions.get("debuggerSrc"));this._PDFBug=t};if("true"===n.get("disableworker"))try{j.GlobalWorkerOptions.workerSrc||=AppOptions.get("workerSrc");await import(j.PDFWorker.workerSrc)}catch(t){console.error("_parseHashParams:",t)}if(n.has("textlayer"))switch(n.get("textlayer")){case"off":AppOptions.set("textLayerMode",b);break;case"visible":case"shadow":case"hover":i.classList.add(`textLayer-${n.get("textlayer")}`);try{await loadPDFBug();this._PDFBug.loadCSS()}catch(t){console.error("_parseHashParams:",t)}}if(n.has("pdfbug")){AppOptions.setAll({pdfBug:!0,fontExtraProperties:!0});const t=n.get("pdfbug").split(",");try{await loadPDFBug();this._PDFBug.init(e,t)}catch(t){console.error("_parseHashParams:",t)}}n.has("locale")&&AppOptions.set("localeProperties",{lang:n.get("locale")});const s={disableAutoFetch:t=>"true"===t,disableFontFace:t=>"true"===t,disableHistory:t=>"true"===t,disableRange:t=>"true"===t,disableStream:t=>"true"===t,verbosity:t=>0|t};for(const t in s){const e=s[t],i=t.toLowerCase();n.has(i)&&AppOptions.set(t,e(n.get(i)))}},async _initializeViewerComponents(){const{appConfig:t,externalServices:e,l10n:i}=this,n=new EventBus;this.eventBus=AppOptions.eventBus=n;this.mlManager?.setEventBus(n,this._globalAbortController.signal);this.overlayManager=new OverlayManager;const s=new PDFRenderingQueue;s.onIdle=this._cleanup.bind(this);this.pdfRenderingQueue=s;const a=new PDFLinkService({eventBus:n,externalLinkTarget:AppOptions.get("externalLinkTarget"),externalLinkRel:AppOptions.get("externalLinkRel"),ignoreDestinationZoom:AppOptions.get("ignoreDestinationZoom")});this.pdfLinkService=a;const o=this.downloadManager=new DownloadManager;let l=PDFFindController;AppOptions.get("findController")&&(l=AppOptions.get("findController"));const h=new l({linkService:a,eventBus:n,pageViewMode:AppOptions.get("pageViewMode"),updateMatchesCountOnProgress:!0,listenToEventBus:!1});this.customFindController=h;const d=new l({linkService:a,eventBus:n,pageViewMode:AppOptions.get("pageViewMode"),updateMatchesCountOnProgress:!0,listenToEventBus:!0});this.findController=d;const c=new PDFScriptingManager({eventBus:n,externalServices:e,docProperties:this._scriptingDocProperties.bind(this)});this.pdfScriptingManager=c;const u=t.mainContainer,p=t.viewerContainer,g=AppOptions.get("annotationEditorMode"),m=AppOptions.get("forcePageColors")||window.matchMedia("(forced-colors: active)").matches?{background:AppOptions.get("pageColorsBackground"),foreground:AppOptions.get("pageColorsForeground")}:null;let f;f=AppOptions.get("enableUpdatedAddImage")?t.newAltTextDialog?new NewAltTextManager(t.newAltTextDialog,this.overlayManager,n):null:t.altTextDialog?new AltTextManager(t.altTextDialog,u,this.overlayManager,n):null;t.editorUndoBar&&(this.editorUndoBar=new EditorUndoBar(t.editorUndoBar,n));const b=AppOptions.get("enableHWA"),w=new PDFViewer({container:u,viewer:p,eventBus:n,renderingQueue:s,linkService:a,downloadManager:o,altTextManager:f,editorUndoBar:this.editorUndoBar,findController:d,customFindController:h,scriptingManager:AppOptions.get("enableScripting")&&c,l10n:i,textLayerMode:AppOptions.get("textLayerMode"),annotationMode:AppOptions.get("annotationMode"),annotationEditorMode:g,annotationEditorHighlightColors:AppOptions.get("highlightEditorColors"),enableHighlightFloatingButton:AppOptions.get("enableHighlightFloatingButton"),enableUpdatedAddImage:AppOptions.get("enableUpdatedAddImage"),enableNewAltTextWhenAddingImage:AppOptions.get("enableNewAltTextWhenAddingImage"),imageResourcesPath:AppOptions.get("imageResourcesPath"),removePageBorders:AppOptions.get("removePageBorders"),enablePrintAutoRotate:AppOptions.get("enablePrintAutoRotate"),maxCanvasPixels:AppOptions.get("maxCanvasPixels"),pageViewMode:AppOptions.get("pageViewMode"),enablePermissions:AppOptions.get("enablePermissions"),pageColors:m,mlManager:this.mlManager,abortSignal:this._globalAbortController.signal,enableHWA:b,defaultCacheSize:AppOptions.get("defaultCacheSize"),minZoom:AppOptions.get("minZoom"),maxZoom:AppOptions.get("maxZoom"),cspPolicyService:this.cspPolicyService,supportsPinchToZoom:this.supportsPinchToZoom});this.pdfViewer=w;s.setViewer(w);a.setViewer(w);c.setViewer(w);if(t.sidebar?.thumbnailView){this.pdfThumbnailViewer=new PDFThumbnailViewer({container:t.sidebar.thumbnailView,eventBus:n,renderingQueue:s,linkService:a,pageColors:m,abortSignal:this._globalAbortController.signal,enableHWA:b});s.setThumbnailViewer(this.pdfThumbnailViewer)}if(!this.isViewerEmbedded&&!AppOptions.get("disableHistory")){this.pdfHistory=new PDFHistory({linkService:a,eventBus:n});a.setHistory(this.pdfHistory)}!this.supportsIntegratedFind&&t.findBar&&(this.findBar=new PDFFindBar(t.findBar,t.principalContainer,n));if(t.annotationEditorParams)if("function"==typeof AbortSignal.any&&g!==V.AnnotationEditorType.DISABLE)this.annotationEditorParams=new AnnotationEditorParams(t.annotationEditorParams,n);else for(const t of["editorModeButtons","editorModeSeparator"])document.getElementById(t)?.classList.add("hidden");this.mlManager&&t.secondaryToolbar?.imageAltTextSettingsButton&&(this.imageAltTextSettings=new ImageAltTextSettings(t.altTextSettingsDialog,this.overlayManager,n,this.mlManager));t.documentProperties&&(this.pdfDocumentProperties=new PDFDocumentProperties(t.documentProperties,this.overlayManager,n,i,(()=>this._docFilename)));t.secondaryToolbar?.cursorHandToolButton&&(this.pdfCursorTools=new PDFCursorTools({container:u,eventBus:n,cursorToolOnLoad:AppOptions.get("cursorToolOnLoad")}));t.toolbar&&(this.toolbar=new Toolbar(t.toolbar,n,AppOptions.get("defaultZoomValue"),AppOptions.get("minZoom"),AppOptions.get("maxZoom"),AppOptions.get("toolbarDensity")));if(t.secondaryToolbar){if(AppOptions.get("enableAltText")){t.secondaryToolbar.imageAltTextSettingsButton?.classList.remove("hidden");t.secondaryToolbar.imageAltTextSettingsSeparator?.classList.remove("hidden")}this.secondaryToolbar=new SecondaryToolbar(t.secondaryToolbar,n)}this.supportsFullscreen&&(t.toolbar?.presentationModeButton||t.secondaryToolbar?.presentationModeButton)&&(this.pdfPresentationMode=new PDFPresentationMode({container:u,pdfViewer:w,eventBus:n}));const v=AppOptions.get("passwordPrompt");v?this.passwordPrompt=v:t.passwordOverlay&&(this.passwordPrompt=new PasswordPrompt(t.passwordOverlay,this.overlayManager,this.isViewerEmbedded));t.sidebar?.outlineView&&(this.pdfOutlineViewer=new PDFOutlineViewer({container:t.sidebar.outlineView,eventBus:n,l10n:i,linkService:a,downloadManager:o}));t.sidebar?.attachmentsView&&(this.pdfAttachmentViewer=new PDFAttachmentViewer({container:t.sidebar.attachmentsView,eventBus:n,l10n:i,downloadManager:o}));t.sidebar?.layersView&&(this.pdfLayerViewer=new PDFLayerViewer({container:t.sidebar.layersView,eventBus:n,l10n:i}));if(t.sidebar){this.pdfSidebar=new PDFSidebar({elements:t.sidebar,eventBus:n,l10n:i});this.pdfSidebar.onToggled=this.forceRendering.bind(this);this.pdfSidebar.onUpdateThumbnails=()=>{for(const t of w.getCachedPageViews())t.renderingState===r.FINISHED&&this.pdfThumbnailViewer.getThumbnail(t.id-1)?.setImage(t);this.pdfThumbnailViewer.scrollThumbnailIntoView(w.currentPageNumber)}}},async run(t){await this.initialize(t);const{appConfig:e,eventBus:i}=this;let n;n=parseQueryString(document.location.search.substring(1)).get("file")??AppOptions.get("defaultUrl");validateFileURL(n);const s=this._openFileInput=document.createElement("input");s.id="fileInput";s.className="ngx-extended-pdf-viewer-file-input";s.hidden=!0;s.type="file";s.value=null;s.accept=".pdf,application/pdf";document.body.append(s);s.addEventListener("change",(function(t){const{files:e}=t.target;e&&0!==e.length&&i.dispatch("fileinputchange",{source:this,fileInput:t.target})}));e.mainContainer.addEventListener("dragover",(function(t){if(AppOptions.get("enableDragAndDrop")){if(!t.dataTransfer?.items)return;for(const e of t.dataTransfer.items)if("application/pdf"===e.type){t.dataTransfer.dropEffect="copy"===t.dataTransfer.effectAllowed?"copy":"move";(0,U.stopEvent)(t);return}}}));e.mainContainer.addEventListener("drop",(function(t){if(AppOptions.get("enableDragAndDrop")){const e=t.dataTransfer?.files;if(!e||0===e.length||"application/pdf"!==e[0].type)return;(0,U.stopEvent)(t);i.dispatch("fileinputchange",{source:this,fileInput:t.dataTransfer,dropEvent:t})}}));if(!AppOptions.get("supportsDocumentFonts")){AppOptions.set("disableFontFace",!0);this.l10n.get("pdfjs-web-fonts-disabled").then((t=>{console.warn(t)}))}if(!this.supportsPrinting){e.toolbar?.print?.classList.add("hidden");e.secondaryToolbar?.printButton.classList.add("hidden")}if(!this.supportsFullscreen){e.toolbar.presentationModeButton.classList.add("hidden");e.secondaryToolbar?.presentationModeButton?.classList.add("hidden")}this.supportsIntegratedFind&&e.findBar?.toggleButton?.classList.add("hidden");n?this.open({url:n}):this._hideViewBookmark();const a=new CustomEvent("webviewerinitialized",{bubbles:!0,cancelable:!0,detail:{source:window}});try{document.dispatchEvent(a)}catch(t){console.error(`webviewerinitialized: ${t}`);parent.document.dispatchEvent(a)}},get externalServices(){return(0,V.shadow)(this,"externalServices",new ExternalServices)},get initialized(){return this._initializedCapability.settled},get initializedPromise(){return this._initializedCapability.promise},updateZoom(t,e,i){this.pdfViewer.isInPresentationMode||this.pdfViewer.updateScale({drawingDelay:AppOptions.get("defaultZoomDelay"),steps:t,scaleFactor:e,origin:i})},zoomIn(){this.updateZoom(1)},zoomOut(){this.updateZoom(-1)},zoomReset(){this.pdfViewer.isInPresentationMode||(this.pdfViewer.currentScaleValue=s)},touchPinchCallback(t,e,i){if(this.supportsPinchToZoom){const n=this._accumulateFactor(this.pdfViewer.currentScale,i/e,"_touchUnusedFactor");this.updateZoom(null,n,t)}else{const n=30,s=this._accumulateTicks((i-e)/n,"_touchUnusedTicks");this.updateZoom(s,null,t)}},touchPinchEndCallback(){this._touchUnusedTicks=0;this._touchUnusedFactor=1},get pagesCount(){return this.pdfDocument?this.pdfDocument.numPages:0},get page(){return this.pdfViewer.currentPageNumber},set page(t){this.pdfViewer.currentPageNumber=t},get supportsPrinting(){return PDFPrintServiceFactory.supportsPrinting},get supportsFullscreen(){return(0,V.shadow)(this,"supportsFullscreen",document.fullscreenEnabled)},get supportsPinchToZoom(){return(0,V.shadow)(this,"supportsPinchToZoom",AppOptions.get("supportsPinchToZoom"))},get supportsIntegratedFind(){return(0,V.shadow)(this,"supportsIntegratedFind",AppOptions.get("supportsIntegratedFind"))},initializeLoadingBar(){const t=document.getElementById("loadingBar"),e=t?new ProgressBar(t):null;e?.hide();return(0,V.shadow)(this,"loadingBar",e)},get supportsMouseWheelZoomCtrlKey(){return(0,V.shadow)(this,"supportsMouseWheelZoomCtrlKey",AppOptions.get("supportsMouseWheelZoomCtrlKey"))},get supportsMouseWheelZoomMetaKey(){return(0,V.shadow)(this,"supportsMouseWheelZoomMetaKey",AppOptions.get("supportsMouseWheelZoomMetaKey"))},get supportsCaretBrowsingMode(){return AppOptions.get("supportsCaretBrowsingMode")},moveCaret(t,e){this._caretBrowsing||=new CaretBrowsingMode(this._globalAbortController.signal,this.appConfig.mainContainer,this.appConfig.viewerContainer,this.appConfig.toolbar?.container);this._caretBrowsing.moveCaret(t,e)},setTitleUsingUrl(t="",e=null){},setTitle(t=this._title){this._title=t;if(this.isViewerEmbedded)return;const e=this._hasAnnotationEditors&&!this.pdfRenderingQueue.printing;document.title=`${e?"* ":""}${t}`},get _docFilename(){return this._contentDispositionFilename||(0,U.getPdfFilenameFromUrl)(this.url,_e.appConfig.filenameForDownload)},_hideViewBookmark(){if(!this.appConfig)return;const{secondaryToolbar:t}=this.appConfig;t?.viewBookmarkButton.classList.add("hidden");t?.presentationModeButton?.classList.contains("hidden")&&document.getElementById("viewBookmarkSeparator")?.classList.add("hidden")},async close(){this._unblockDocumentLoadEvent();this._hideViewBookmark();if(!this.pdfLoadingTask)return;if(this.pdfDocument?.annotationStorage.size>0&&this._annotationStorageModified)try{await this.save()}catch{}const t=[];t.push(this.pdfLoadingTask.destroy());this.pdfLoadingTask=null;if(this.pdfDocument){this.pdfDocument=null;this.pdfThumbnailViewer?.setDocument(null);this.pdfViewer.setDocument(null);this.pdfLinkService.setDocument(null);this.pdfDocumentProperties?.setDocument(null)}this.pdfLinkService.externalLinkEnabled=!0;this.store=null;this.isInitialViewSet=!1;this.url="";this.baseUrl="";this._downloadUrl="";this.documentInfo=null;this.metadata=null;this._contentDispositionFilename=null;this._contentLength=null;this._saveInProgress=!1;this._hasAnnotationEditors=!1;t.push(this.pdfScriptingManager.destroyPromise,this.passwordPrompt.close());this.setTitle();this.pdfSidebar?.reset();this.pdfOutlineViewer?.reset();this.pdfAttachmentViewer?.reset();this.pdfLayerViewer?.reset();this.pdfHistory?.reset();this.findBar?.reset();this.toolbar?.reset();this.secondaryToolbar?.reset();this._PDFBug?.cleanup();await Promise.all(t)},async open(t){this.pdfViewer?.destroyBookMode();this.pdfLoadingTask&&await this.close();const e=AppOptions.getAll(k);e.cspPolicyService=t.cspPolicyService;if(t.workerSrc&&t.workerSrc!==e.workerSrc){e.workerSrc=t.workerSrc;this.pdfWorker=null}Object.assign(j.GlobalWorkerOptions,e);e.port=e.port??j.GlobalWorkerOptions.workerPort;e.cspPolicyService=this.cspPolicyService;null===this.pdfWorker&&(this.pdfWorker=e.port?j.PDFWorker.fromPort(e):new j.PDFWorker(e));t.url&&this.setTitleUsingUrl(t.originalUrl||t.url,t.url);const i=AppOptions.getAll(L),n=(0,z.getDocument)({...i,...t,worker:this.pdfWorker,cspPolicyService:t.cspPolicyService});this.pdfLoadingTask=n;n.onPassword=(t,e)=>{this.isViewerEmbedded&&this._unblockDocumentLoadEvent();this.pdfLinkService.externalLinkEnabled=!1;this.passwordPrompt.setUpdateCallback(t,e);this.passwordPrompt.open()};n.onProgress=({loaded:t,total:e})=>{this.progress(t/e);this.eventBus?.dispatch("progress",{source:this,type:"load",total:e,loaded:t,percent:100*t/e})};const s=this.serviceWorkerOptions.showUnverifiedSignatures;return n.promise.then((t=>{t._transport.messageHandler.send("showUnverifiedSignatures",s);this.load(t)}),(t=>{if(n!==this.pdfLoadingTask)return;let e="pdfjs-loading-error";t instanceof V.InvalidPDFException?e="pdfjs-invalid-file-error":t instanceof j.MissingPDFException?e="pdfjs-missing-file-error":t instanceof V.UnexpectedResponseException&&(e="pdfjs-unexpected-response-error");_e.onError&&_e.onError(t);return this._documentError(e,{message:t.message}).then((()=>{throw t}))}))},async download(){let t;try{t=await this.pdfDocument.getData()}catch{}this.downloadManager.download(t,this._downloadUrl,this._docFilename)},async save(){if(!this._saveInProgress){this._saveInProgress=!0;await this.pdfScriptingManager.dispatchWillSave();try{const t=await this.pdfDocument.saveDocument();this.downloadManager.download(t,this._downloadUrl,this._docFilename)}catch(t){n.NgxConsole.error("Error when saving the document:",t);await this.download()}finally{await this.pdfScriptingManager.dispatchDidSave();this._saveInProgress=!1}this._hasAnnotationEditors&&this.externalServices.reportTelemetry({type:"editing",data:{type:"save",stats:this.pdfDocument?.annotationStorage.editorStats}})}},async downloadOrSave(){const{classList:t}=this.appConfig.appContainer;t.add("wait");await(this.pdfDocument?.annotationStorage.size>0?this.save():this.download());t.remove("wait")},async _exportWithAnnotations(){if(this._saveInProgress)throw new Error("Already downloading");this._saveInProgress=!0;await this.pdfScriptingManager.dispatchWillSave();try{this._ensureDownloadComplete();const t=await this.pdfDocument.saveDocument();return new Blob([t],{type:"application/pdf"})}catch(t){throw new Error(`Error when saving the document: ${t.message}`)}finally{await this.pdfScriptingManager.dispatchDidSave();this._saveInProgress=!1}},_ensureDownloadComplete(){if(!this.pdfDocument)throw new Error("PDF document not downloaded.")},async _exportWithoutAnnotations(){try{this._ensureDownloadComplete();const t=await this.pdfDocument.getData();return new Blob([t],{type:"application/pdf"})}catch(t){throw new Error(`Error when saving the document: ${t.message}`)}},async export(){return this.pdfDocument?.annotationStorage.size>0?this._exportWithAnnotations():this._exportWithoutAnnotations()},openInExternalApp(){this.downloadOrSave({openInExternalApp:!0})},async _documentError(t,e=null){this._unblockDocumentLoadEvent();const i=await this._otherError(t||"pdfjs-loading-error",e);this.eventBus.dispatch("documenterror",{source:this,message:i,reason:e?.message??null})},async _otherError(t,e=null){const i=await this.l10n.get(t),n=[`PDF.js v${j.version||"?"} (build: ${z.build||"?"})`];if(e){n.push(`Message: ${e.message}`);if(e.stack)n.push(`Stack: ${e.stack}`);else{e.filename&&n.push(`File: ${e.filename}`);e.lineNumber&&n.push(`Line: ${e.lineNumber}`)}}console.error(`${i}\n\n${n.join("\n")}`);return i},progress(t){const e=Math.round(100*t);if(this.loadingBar&&!(e<=this.loadingBar.percent)){this.loadingBar.percent=e;(this.pdfDocument?.loadingParams.disableAutoFetch??AppOptions.get("disableAutoFetch"))&&this.loadingBar.setDisableAutoFetch()}},load(t){this.pdfDocument=t;t.getDownloadInfo().then((({length:t})=>{this._contentLength=t;this.loadingBar?.hide();r.then((()=>{this.eventBus?.dispatch("documentloaded",{source:this})}))}));const e=t.getPageLayout().catch((()=>{})),i=t.getPageMode().catch((()=>{})),n=t.getOpenAction().catch((()=>{}));this.toolbar?.setPagesCount(t.numPages,!1);this.secondaryToolbar?.setPagesCount(t.numPages);this.pdfLinkService.setDocument(t);this.pdfDocumentProperties?.setDocument(t);const a=this.pdfViewer;a.setDocument(t);const{firstPagePromise:r,onePageRendered:o,pagesPromise:l}=a;this.pdfThumbnailViewer?.setDocument(t);const h=(this.store=new ViewHistory(t.fingerprints[0])).getMultiple({page:null,zoom:s,scrollLeft:"0",scrollTop:"0",rotation:null,sidebarView:c,scrollMode:y.UNKNOWN,spreadMode:A.UNKNOWN}).catch((()=>{}));r.then((s=>{this.loadingBar?.setWidth(this.appConfig.viewerContainer);this._initializeAnnotationStorageCallbacks(t);Promise.all([_,h,e,i,n]).then((async([e,i,n,s,r])=>{const o=AppOptions.get("viewOnLoad");this._initializePdfHistory({fingerprint:t.fingerprints[0],viewOnLoad:o,initialDest:r?.dest});const h=this.initialBookmark;let d=AppOptions.get("defaultZoomValue");if(!d||""===d)try{d=await this.store.get("zoom");"string"==typeof d&&(d=d?.replace("%",""));isNaN(Number(d))||(d=Number(d)/100)}catch(t){}!a.currentScaleValue&&d&&""!==d&&(a.currentScaleValue=d);let b=d?`zoom=${d}`:null,w=null,v=AppOptions.get("sidebarViewOnLoad"),x=AppOptions.get("scrollModeOnLoad"),E=AppOptions.get("spreadModeOnLoad");if(i?.page&&o!==Pe){b=`page=${i.page}&zoom=${d||i.zoom},${i.scrollLeft},${i.scrollTop}`;w=parseInt(i.rotation,10);v===c&&(v=0|i.sidebarView);x===y.UNKNOWN&&(x=0|i.scrollMode);E===A.UNKNOWN&&(E=0|i.spreadMode)}s&&v===c&&(v=function apiPageModeToSidebarView(t){switch(t){case"UseNone":return u;case"UseThumbs":return p;case"UseOutlines":return g;case"UseAttachments":return m;case"UseOC":return f}return u}(s));if(n&&x===y.UNKNOWN&&E===A.UNKNOWN){E=apiPageLayoutToViewerModes(n).spreadMode}this.setInitialView(b,{rotation:w,sidebarView:v,scrollMode:x,spreadMode:E});this.eventBus.dispatch("documentinit",{source:this});this.isViewerEmbedded||a.focus();await Promise.race([l,new Promise((t=>{setTimeout(t,10)}))]);if((h||b)&&!a.hasEqualPageSizes){this.initialBookmark=h;a.currentScaleValue=a.currentScaleValue;this.setInitialView(b)}})).catch((()=>{this.setInitialView()})).then((function(){a.update()}))}));l.then((()=>{this._unblockDocumentLoadEvent();this._initializeAutoPrint(t,n)}),(t=>{_e.onError&&_e.onError(t);this._documentError("pdfjs-loading-error",{message:t.message})}));o.then((e=>{this.externalServices.reportTelemetry({type:"pageInfo",timestamp:e.timestamp});this.pdfOutlineViewer&&t.getOutline().then((e=>{t===this.pdfDocument&&this.pdfOutlineViewer.render({outline:e,pdfDocument:t})}));this.pdfAttachmentViewer&&t.getAttachments().then((e=>{t===this.pdfDocument&&this.pdfAttachmentViewer.render({attachments:e})}));this.pdfLayerViewer&&a.optionalContentConfigPromise.then((e=>{t===this.pdfDocument&&this.pdfLayerViewer.render({optionalContentConfig:e,pdfDocument:t})}))}));this._initializePageLabels(t);this._initializeMetadata(t)},async _scriptingDocProperties(t){if(!this.documentInfo){await new Promise((t=>{this.eventBus._on("metadataloaded",t,{once:!0})}));if(t!==this.pdfDocument)return null}if(!this._contentLength){await new Promise((t=>{this.eventBus._on("documentloaded",t,{once:!0})}));if(t!==this.pdfDocument)return null}return{...this.documentInfo,baseURL:this.baseUrl,filesize:this._contentLength,filename:this._docFilename,metadata:this.metadata?.getRaw(),authors:this.metadata?.get("dc:creator"),numPages:this.pagesCount,URL:this.url}},async _initializeAutoPrint(t,e){const[i,s]=await Promise.all([e,this.pdfViewer.enableScripting?null:t.getJSActions()]);if(t!==this.pdfDocument)return;let a="Print"===i?.action;if(s){n.NgxConsole.warn("Warning: JavaScript support is not enabled");for(const t in s){if(a)break;switch(t){case"WillClose":case"WillSave":case"DidSave":case"WillPrint":case"DidPrint":continue}a=s[t].some((t=>S.test(t)))}}a&&this.triggerPrinting()},async _initializeMetadata(t){const{info:e,metadata:i,contentDispositionFilename:s,contentLength:a}=await t.getMetadata();if(t!==this.pdfDocument)return;this.documentInfo=e;this.metadata=i;this._contentDispositionFilename??=s;this._contentLength??=a;AppOptions?.get("verbosity")>0&&n.NgxConsole.log(`PDF ${t.fingerprints[0]} [${e.PDFFormatVersion} ${(e.Producer||"-").trim()} / ${(e.Creator||"-").trim()}] (PDF.js: ${j.version||"?"} [${z.build||"?"}]) modified by ngx-extended-pdf-viewer 23.0.0-alpha.7`);let r=e.Title;const o=i?.get("dc:title");o&&("Untitled"===o||/[\uFFF0-\uFFFF]/g.test(o)||(r=o));r?this.setTitle(`${r} - ${this._contentDispositionFilename||this._title}`):this._contentDispositionFilename&&this.setTitle(this._contentDispositionFilename);!e.IsXFAPresent||e.IsAcroFormPresent||t.isPureXfa?!e.IsAcroFormPresent&&!e.IsXFAPresent||this.pdfViewer.renderForms||console.warn("Warning: Interactive form support is not enabled"):t.loadingParams.enableXfa?n.NgxConsole.warn("Warning: XFA Foreground documents are not supported"):n.NgxConsole.warn("Warning: XFA support is not enabled");e.IsSignaturesPresent&&console.warn("Warning: Digital signatures validation is not supported");this.eventBus.dispatch("metadataloaded",{source:this})},async _initializePageLabels(t){const e=await t.getPageLabels();if(t!==this.pdfDocument)return;if(!e||AppOptions.get("disablePageLabels"))return;const i=e.length;let n=0,s=0;for(let t=0;t<i;t++){const i=e[t];if(i===(t+1).toString())n++;else{if(""!==i)break;s++}}if(n>=i||s>=i)return;const{pdfViewer:a,pdfThumbnailViewer:r,toolbar:o}=this;a.setPageLabels(e);r?.setPageLabels(e);o?.setPagesCount(i,!0);o?.setPageNumber(a.currentPageNumber,a.currentPageLabel)},_initializePdfHistory({fingerprint:t,viewOnLoad:e,initialDest:i=null}){if(this.pdfHistory){this.pdfHistory.initialize({fingerprint:t,resetHistory:e===Pe,updateUrl:AppOptions.get("historyUpdateUrl")});if(this.pdfHistory.initialBookmark){this.initialBookmark=this.pdfHistory.initialBookmark;this.initialRotation=this.pdfHistory.initialRotation}if(i&&!this.initialBookmark&&e===Se){this.initialBookmark=JSON.stringify(i);this.pdfHistory.push({explicitDest:i,pageNumber:null})}}},_initializeAnnotationStorageCallbacks(t){if(t!==this.pdfDocument)return;const{annotationStorage:e}=t;e.onSetModified=()=>{window.addEventListener("beforeunload",beforeUnload);this._annotationStorageModified=!0};e.onResetModified=()=>{window.removeEventListener("beforeunload",beforeUnload);delete this._annotationStorageModified};e.onAnnotationEditor=t=>{this._hasAnnotationEditors=!!t;this.setTitle()}},setInitialView(t,{rotation:e,sidebarView:i,scrollMode:n,spreadMode:s}={}){const setRotation=t=>{isValidRotation(t)&&(this.pdfViewer.pagesRotation=t)};this.isInitialViewSet=!0;this.pdfSidebar?.setInitialView(i);((t,e)=>{isValidScrollMode(t)&&(this.pdfViewer.scrollMode=t);isValidSpreadMode(e)&&(this.pdfViewer.spreadMode=e)})(n,s);if(this.initialBookmark){setRotation(this.initialRotation);delete this.initialRotation;this.pdfLinkService.setHash&&this.pdfLinkService.setHash(this.initialBookmark);this.initialBookmark=null}else if(t){setRotation(e);this.pdfLinkService.setHash&&this.pdfLinkService.setHash(t)}this.toolbar?.setPageNumber(this.pdfViewer.currentPageNumber,this.pdfViewer.currentPageLabel);this.secondaryToolbar?.setPageNumber(this.pdfViewer.currentPageNumber);if(!this.pdfViewer.currentScaleValue){const t=AppOptions?.get("defaultZoomValue");t&&(this.pdfViewer.currentScaleValue=t)}},_cleanup(){if(this.resizeObserver){this.resizeObserver.disconnect();this.resizeObserver=null}if(this.pdfDocument){this.pdfViewer.cleanup();this.pdfThumbnailViewer?.cleanup();this.pdfDocument.cleanup(AppOptions.get("fontExtraProperties"))}},forceRendering(){this.pdfRenderingQueue.printing=!!this.printService;this.pdfRenderingQueue.isThumbnailViewEnabled=this.pdfSidebar?.visibleView===p;this.pdfRenderingQueue.renderHighestPriority()},beforePrint(){this._printAnnotationStoragePromise=this.pdfScriptingManager.dispatchWillPrint().catch((()=>{})).then((()=>this.pdfDocument?.annotationStorage.print));if(!this.printService)if(this.supportsPrinting)if(this.pdfViewer.pageViewsReady){this.printService=PDFPrintServiceFactory.createPrintService({pdfDocument:this.pdfDocument,pagesOverview:this.pdfViewer.getPagesOverview(),printResolution:AppOptions.get("printResolution"),printAnnotationStoragePromise:this._printAnnotationStoragePromise,eventBus:this.pdfViewer.eventBus,cspPolicyService:this.cspPolicyService});this.forceRendering();this.setTitle();this.printService.layout();this._hasAnnotationEditors&&this.externalServices.reportTelemetry({type:"editing",data:{type:"print",stats:this.pdfDocument?.annotationStorage.editorStats}})}else this.l10n.get("pdfjs-printing-not-ready").then((t=>{window.alert(t)}));else this._otherError("pdfjs-printing-not-supported")},afterPrint(){if(this._printAnnotationStoragePromise){this._printAnnotationStoragePromise.then((()=>{this.pdfScriptingManager.dispatchDidPrint()}));this._printAnnotationStoragePromise=null}if(this.printService){this.printService.destroy();this.printService=null;this.pdfDocument?.annotationStorage.resetModified()}this.forceRendering();this.setTitle()},rotatePages(t){this.pdfViewer.pagesRotation+=t},requestPresentationMode(){this.pdfPresentationMode?.request()},triggerPrinting(){this.supportsPrinting&&this.printPdf()},bindEvents(){if(this._eventBusAbortController)return;const t={signal:(this._eventBusAbortController=new AbortController).signal},{eventBus:e,externalServices:i,pdfDocumentProperties:n,pdfViewer:s,preferences:a}=this;e._on("resize",onResize.bind(this),t);e._on("hashchange",onHashchange.bind(this),t);e._on("beforeprint",this.beforePrint.bind(this),t);e._on("afterprint",this.afterPrint.bind(this),t);e._on("pagerender",onPageRender.bind(this),t);e._on("pagerendered",onPageRendered.bind(this),t);e._on("updateviewarea",onUpdateViewarea.bind(this),t);e._on("pagechanging",onPageChanging.bind(this),t);e._on("scalechanging",onScaleChanging.bind(this),t);e._on("rotationchanging",onRotationChanging.bind(this),t);e._on("sidebarviewchanged",onSidebarViewChanged.bind(this),t);e._on("pagemode",onPageMode.bind(this),t);e._on("namedaction",onNamedAction.bind(this),t);e._on("presentationmodechanged",(t=>s.presentationModeState=t.state),t);e._on("presentationmode",this.requestPresentationMode.bind(this),t);e._on("switchannotationeditormode",(t=>s.annotationEditorMode=t),t);e._on("print",this.triggerPrinting.bind(this),t);e._on("download",this.downloadOrSave.bind(this),t);e._on("firstpage",(()=>this.page=1),t);e._on("lastpage",(()=>this.page=this.pagesCount),t);e._on("nextpage",(()=>s.nextPage()),t);e._on("previouspage",(()=>s.previousPage()),t);e._on("zoomin",this.zoomIn.bind(this),t);e._on("zoomout",this.zoomOut.bind(this),t);e._on("zoomreset",this.zoomReset.bind(this),t);e._on("pagenumberchanged",onPageNumberChanged.bind(this),t);e._on("scalechanged",(t=>s.currentScaleValue=t.value),t);e._on("rotatecw",this.rotatePages.bind(this,90),t);e._on("rotateccw",this.rotatePages.bind(this,-90),t);e._on("optionalcontentconfig",(t=>s.optionalContentConfigPromise=t.promise),t);e._on("switchscrollmode",(t=>s.scrollMode=t.mode),t);e._on("scrollmodechanged",onViewerModesChanged.bind(this,"scrollMode"),t);e._on("switchspreadmode",(t=>s.spreadMode=t.mode),t);e._on("spreadmodechanged",onViewerModesChanged.bind(this,"spreadMode"),t);e._on("imagealttextsettings",onImageAltTextSettings.bind(this),t);e._on("documentproperties",(()=>n?.open()),t);e._on("findfromurlhash",onFindFromUrlHash.bind(this),t);e._on("updatefindmatchescount",onUpdateFindMatchesCount.bind(this),t);e._on("updatefindcontrolstate",onUpdateFindControlState.bind(this),t);e._on("fileinputchange",onFileInputChange.bind(this),t);e._on("openfile",onOpenFile.bind(this),t)},bindWindowEvents(){if(this._windowAbortController)return;this._windowAbortController=new AbortController;const{eventBus:t,appConfig:{mainContainer:e},pdfViewer:i,_windowAbortController:{signal:n}}=this;"function"==typeof AbortSignal.any&&(this._touchManager=new H.TouchManager({container:window,isPinchingDisabled:()=>i.isInPresentationMode,isPinchingStopped:()=>this.overlayManager?.active,onPinching:this.touchPinchCallback.bind(this),onPinchEnd:this.touchPinchEndCallback.bind(this),signal:n}));!function addWindowResolutionChange(t=null){t&&i.refresh();window.matchMedia(`(resolution: ${window.devicePixelRatio||1}dppx)`).addEventListener("change",addWindowResolutionChange,{once:!0,signal:n})}();const s=document.getElementById("viewerContainer");s?.addEventListener("wheel",onWheel.bind(this),{passive:!1,signal:n});window.addEventListener("wheel",onWheel.bind(this),{passive:!1,signal:n});window.addEventListener("click",onClick.bind(this),{signal:n});window.addEventListener("keydown",onKeyDown.bind(this),{signal:n});window.addEventListener("keyup",onKeyUp.bind(this),{signal:n});if(s){let i,n=e.clientWidth,s=e.clientHeight;this.resizeObserver=new ResizeObserver((a=>{const r=e.clientWidth,o=e.clientHeight;if(r!==n||o!==s){clearTimeout(i);i=setTimeout((()=>{e.offsetParent&&t.dispatch("resize",{source:e})}),50);n=r;s=o}}));this.resizeObserver.observe(e)}else window.addEventListener("resize",(()=>t.dispatch("resize",{source:window})),{signal:n});window.addEventListener("hashchange",(()=>{t.dispatch("hashchange",{source:window,hash:document.location.hash.substring(1)})}),{signal:n});window.addEventListener("beforeprint",(()=>t.dispatch("beforeprint",{source:window})),{signal:n});window.addEventListener("afterprint",(()=>t.dispatch("afterprint",{source:window})),{signal:n});window.addEventListener("updatefromsandbox",(e=>{t.dispatch("updatefromsandbox",{source:window,detail:e.detail})}),{signal:n});if(!("onscrollend"in document.documentElement))return;({scrollTop:this._lastScrollTop,scrollLeft:this._lastScrollLeft}=e);const scrollend=()=>{({scrollTop:this._lastScrollTop,scrollLeft:this._lastScrollLeft}=e);this._isScrolling=!1;e.addEventListener("scroll",scroll,{passive:!0,signal:n});e.removeEventListener("scrollend",scrollend);e.removeEventListener("blur",scrollend)},scroll=()=>{if(!this._isCtrlKeyDown&&(this._lastScrollTop!==e.scrollTop||this._lastScrollLeft!==e.scrollLeft)){e.removeEventListener("scroll",scroll);this._isScrolling=!0;e.addEventListener("scrollend",scrollend,{signal:n});e.addEventListener("blur",scrollend,{signal:n})}};e.addEventListener("scroll",scroll,{passive:!0,signal:n})},unbindEvents(){this._eventBusAbortController?.abort();this._eventBusAbortController=null},unbindWindowEvents(){this._windowAbortController?.abort();this._windowAbortController=null;this._touchManager=null},async testingClose(){this.unbindEvents();this.unbindWindowEvents();this._globalAbortController?.abort();this._globalAbortController=null;this.findBar?.close();await Promise.all([this.l10n?.destroy(),this.close()])},_accumulateTicks(t,e){(this[e]>0&&t<0||this[e]<0&&t>0)&&(this[e]=0);this[e]+=t;const i=Math.trunc(this[e]);this[e]-=i;return i},_accumulateFactor(t,e,i){if(1===e)return 1;(this[i]>1&&e<1||this[i]<1&&e>1)&&(this[i]=1);const n=Math.floor(t*e*this[i]*100)/(100*t);this[i]=e/n;return n},_unblockDocumentLoadEvent(){document.blockUnblockOnload?.(!1);this._unblockDocumentLoadEvent=()=>{}},get scriptingReady(){return this.pdfScriptingManager.ready}};PDFPrintServiceFactory.initGlobals(_e);{const t=["null","http://mozilla.github.io","https://mozilla.github.io"];var validateFileURL=function(e){if(e)try{const i=new URL(window.location.href).origin||"null";if(t.includes(i))return;if(new URL(e,window.location.href).origin!==i)throw new Error("file origin does not match viewer's")}catch(t){_e.onError&&_e.onError(t);_e._documentError("pdfjs-loading-error",{message:t.message});throw t}},onFileInputChange=function(t){if(this.pdfViewer?.isInPresentationMode)return;const e=t.fileInput.files[0];this.open({url:URL.createObjectURL(e),originalUrl:e.name})},onOpenFile=function(t){this._openFileInput?.click()}}function onPageRender({pageNumber:t}){t===this.page&&this.toolbar?.updateLoadingIndicatorState(!0)}function onPageRendered({pageNumber:t,error:e}){t===this.page&&this.toolbar?.updateLoadingIndicatorState(!1);if(this.pdfSidebar?.visibleView===p){const e=this.pdfViewer.getPageView(t-1),i=this.pdfThumbnailViewer?.getThumbnail(t-1);e&&i?.setImage(e)}e&&this._otherError("pdfjs-rendering-error",e)}function onPageMode({mode:t}){let e;switch(t){case"thumbs":e=p;break;case"bookmarks":case"outline":e=g;break;case"attachments":e=m;break;case"layers":e=f;break;case"none":e=u;break;default:n.NgxConsole.error('Invalid "pagemode" hash parameter: '+t);return}this.pdfSidebar?.switchView(e,!0)}function onNamedAction(t){switch(t.action){case"GoToPage":this.appConfig.toolbar?.pageNumber.select();break;case"Find":this.supportsIntegratedFind||this.findBar?.toggle();break;case"Print":this.triggerPrinting();break;case"SaveAs":this.downloadOrSave()}}function onSidebarViewChanged({view:t}){this.pdfRenderingQueue.isThumbnailViewEnabled=t===p;this.isInitialViewSet&&this.store?.set("sidebarView",t).catch((()=>{}))}function onUpdateViewarea({location:t}){if(this.isInitialViewSet){const e={};void 0===t.pageNumber&&null===t.pageNumber||(e.page=t.pageNumber);t.scale&&(e.zoom=t.scale);t.left&&(e.scrollLeft=t.left);t.top&&(e.scrollTop=t.top);void 0===t.rotation&&null===t.rotation||(e.rotation=t.rotation);_e.store?.setMultiple(e).catch((()=>{}))}this.appConfig.secondaryToolbar&&(this.appConfig.secondaryToolbar.viewBookmarkButton.href=this.pdfLinkService.getAnchorUrl(t.pdfOpenParams))}function onViewerModesChanged(t,e){this.isInitialViewSet&&!this.pdfViewer.isInPresentationMode&&this.store?.set(t,e.mode).catch((()=>{}))}function onResize(){const{pdfDocument:t,pdfViewer:e,pdfRenderingQueue:i}=this;if(i.printing&&window.matchMedia("print").matches)return;if(!t)return;const n=e.currentScaleValue;"auto"!==n&&"page-fit"!==n&&"page-width"!==n||(e.currentScaleValue=n);e.update()}function onHashchange(t){const e=t.hash;e&&(this.isInitialViewSet?this.pdfHistory?.popStateInProgress||this.pdfLinkService.setHash&&this.pdfLinkService.setHash(e):this.initialBookmark=e)}function onPageNumberChanged(t){const{pdfViewer:e}=this;""!==t.value&&this.pdfLinkService.goToPage(t.value);t.value!==e.currentPageNumber.toString()&&t.value!==e.currentPageLabel&&this.toolbar?.setPageNumber(e.currentPageNumber,e.currentPageLabel)}function onImageAltTextSettings(){this.imageAltTextSettings?.open({enableGuessAltText:AppOptions.get("enableGuessAltText"),enableNewAltTextWhenAddingImage:AppOptions.get("enableNewAltTextWhenAddingImage")})}function onFindFromUrlHash(t){this.eventBus.dispatch("find",{source:t.source,type:"",query:t.query,caseSensitive:!1,entireWord:!1,highlightAll:!0,findPrevious:!1,matchDiacritics:!0})}function onUpdateFindMatchesCount({matchesCount:t}){this.supportsIntegratedFind?this.externalServices.updateFindMatchesCount(t):this.findBar?.updateResultsCount(t)}function onUpdateFindControlState({state:t,previous:e,entireWord:i,matchesCount:n,rawQuery:s}){this.supportsIntegratedFind?this.externalServices.updateFindControlState({result:t,findPrevious:e,entireWord:i,matchesCount:n,rawQuery:s}):this.findBar?.updateUIState(t,e,n)}function onScaleChanging(t){this.toolbar?.setPageScale(t.presetValue,t.scale);this.pdfViewer.update(t.noScroll)}function onRotationChanging(t){this.pdfThumbnailViewer&&(this.pdfThumbnailViewer.pagesRotation=t.pagesRotation);this.forceRendering();this.pdfViewer.currentPageNumber=t.pageNumber}function onPageChanging({pageNumber:t,pageLabel:e}){this.toolbar?.setPageNumber(t,e);this.secondaryToolbar?.setPageNumber(t);this.pdfSidebar?.visibleView===p&&this.pdfThumbnailViewer?.scrollThumbnailIntoView(t);const i=this.pdfViewer.getPageView(t-1);this.toolbar?.updateLoadingIndicatorState(i?.renderingState===r.RUNNING);const n=document.getElementById("pageNumber");if(n){const t=new CustomEvent("page-change");n.dispatchEvent(t)}}function onWheel(t){const e=document.getElementById("viewerContainer");if(e.parentNode.querySelector(":hover")!==e)return;const{pdfViewer:i,supportsMouseWheelZoomCtrlKey:n,supportsMouseWheelZoomMetaKey:s,supportsPinchToZoom:a}=this;if(i.isInPresentationMode)return;const r=(t.ctrlKey?1:0)|(t.altKey?2:0)|(t.shiftKey?4:0)|(t.metaKey?8:0);if(_e?.isKeyIgnored&&_e.isKeyIgnored(r,"WHEEL"))return;const o=t.deltaMode;let l=Math.exp(-t.deltaY/100);const h=t.ctrlKey&&!this._isCtrlKeyDown&&o===WheelEvent.DOM_DELTA_PIXEL&&0===t.deltaX&&(Math.abs(l-1)<.05||!1)&&0===t.deltaZ,d=[t.clientX,t.clientY];if(h||t.ctrlKey&&n||t.metaKey&&s){t.preventDefault();if(this._isScrolling||"hidden"===document.visibilityState||this.overlayManager.active)return;if(h&&a){l=this._accumulateFactor(i.currentScale,l,"_wheelUnusedFactor");this.updateZoom(null,l,d)}else{const e=normalizeWheelEventDirection(t);let i=0;if(o===WheelEvent.DOM_DELTA_LINE||o===WheelEvent.DOM_DELTA_PAGE)i=Math.abs(e)>=1?Math.sign(e):this._accumulateTicks(e,"_wheelUnusedTicks");else{const t=30;i=this._accumulateTicks(e/t,"_wheelUnusedTicks")}this.updateZoom(i,null,d)}}}function closeSecondaryToolbar(t){if(!this.secondaryToolbar?.isOpen)return;const e=this.appConfig;if(this.pdfViewer.containsElement(t.target)||e.toolbar?.container.contains(t.target)&&!e.secondaryToolbar?.toggleButton.contains(t.target)){if(t.target&&t.target.parentElement===e.secondaryToolbar.toggleButton)return;if(t.target&&t.target.parentElement&&t.target.parentElement.parentElement===e.secondaryToolbar.toggleButton)return;this.secondaryToolbar.close()}}function closeEditorUndoBar(t){this.editorUndoBar?.isOpen&&this.appConfig.secondaryToolbar?.toolbar.contains(t.target)&&this.editorUndoBar.hide()}function onClick(t){closeSecondaryToolbar.call(this,t);closeEditorUndoBar.call(this,t)}function onKeyUp(t){"Control"===t.key&&(this._isCtrlKeyDown=!1)}function onKeyDown(t){this._isCtrlKeyDown="Control"===t.key;this.editorUndoBar?.isOpen&&9!==t.keyCode&&16!==t.keyCode&&(13!==t.keyCode&&32!==t.keyCode||getActiveOrFocusedElement()!==this.appConfig.editorUndoBar.undoButton)&&this.editorUndoBar.hide();if(this.overlayManager.active)return;const{eventBus:e,pdfViewer:i}=this,n=i.isInPresentationMode;let s=!1,a=!1;const r=(t.ctrlKey?1:0)|(t.altKey?2:0)|(t.shiftKey?4:0)|(t.metaKey?8:0);if(_e.ngxKeyboardManager&&_e.ngxKeyboardManager.isKeyIgnored.bind(_e.ngxKeyboardManager)(r,t.keyCode))return;if(1===r||8===r||5===r||12===r)switch(t.keyCode){case 70:if(!this.supportsIntegratedFind&&!t.shiftKey){if(AppOptions.get("textLayerMode")!==b){let t=!1;const e=this.pdfViewer.viewer.closest("#outerContainer")?.querySelector("#primaryViewFind");e&&(t||=!e?.classList.contains("dummy-component"));const i=this.pdfViewer.viewer.closest("#outerContainer")?.querySelector("#secondaryToolbarToggle");if(!i.hidden){const e=this.pdfViewer.viewer.closest("#outerContainer")?.querySelector("#secondaryViewFind");e&&(t||=!e?.classList.contains("dummy-component"))}t&&this.findBar?.open()}s=!0}break;case 71:if(!this.supportsIntegratedFind){const{state:t}=this.findController;if(t){const i={source:window,type:"again",findPrevious:5===r||12===r};e.dispatch("find",{...t,...i})}s=!0}break;case 61:case 107:case 187:case 171:this.zoomIn();s=!0;break;case 173:case 109:case 189:this.zoomOut();s=!0;break;case 48:case 96:if(!n){setTimeout((()=>{this.zoomReset()}));s=!1}break;case 38:if(n||this.page>1){this.page=1;s=!0;a=!0}break;case 40:if(n||this.page<this.pagesCount){this.page=this.pagesCount;s=!0;a=!0}}if(1===r||8===r)switch(t.keyCode){case 83:e.dispatch("download",{source:window});s=!0;break;case 79:e.dispatch("openfile",{source:window});s=!0}if(3===r||10===r)switch(t.keyCode){case 80:this.requestPresentationMode();s=!0;this.externalServices.reportTelemetry({type:"buttons",data:{id:"presentationModeKeyboard"}});break;case 71:if(this.appConfig.toolbar){this.appConfig.toolbar.pageNumber.select();s=!0}}if(s){a&&!n&&i.focus();t.preventDefault();return}const o=getActiveOrFocusedElement(),l=o?.tagName.toUpperCase();if("INPUT"!==l&&"TEXTAREA"!==l&&"SELECT"!==l&&("BUTTON"!==l||13!==t.keyCode&&32!==t.keyCode)&&!o?.isContentEditable||27===t.keyCode){if(0===r){let e=0,r=!1;switch(t.keyCode){case 38:if(this.supportsCaretBrowsingMode){this.moveCaret(!0,!1);s=!0;break}case 33:i.isVerticalScrollbarEnabled&&(r=!0);e=-1;break;case 8:n||(r=!0);e=-1;break;case 37:if(this.supportsCaretBrowsingMode)return;i.isHorizontalScrollbarEnabled&&(r=!0);case 75:case 80:e=-1;break;case 27:if(this.secondaryToolbar?.isOpen){this.secondaryToolbar.close();s=!0}if(!this.supportsIntegratedFind&&this.findBar?.opened){this.findBar.close();s=!0}break;case 40:if(this.supportsCaretBrowsingMode){this.moveCaret(!1,!1);s=!0;break}case 34:i.isVerticalScrollbarEnabled&&(r=!0);e=1;break;case 13:case 32:n||(r=!0);e=1;break;case 39:if(this.supportsCaretBrowsingMode)return;i.isHorizontalScrollbarEnabled&&(r=!0);case 74:case 78:e=1;break;case 36:if(n||this.page>1){this.page=1;s=!0;a=!0}break;case 35:if(n||this.page<this.pagesCount){this.page=this.pagesCount;s=!0;a=!0}break;case 83:this.pdfCursorTools?.switchTool(x);break;case 72:this.pdfCursorTools?.switchTool(E);break;case 82:this.rotatePages(90);break;case 115:this.pdfSidebar?.toggle()}if(0!==e&&(!r||"page-fit"===i.currentScaleValue)){const{mainContainer:t}=this.appConfig;(function viewerIsAllowedToCaptureKeyEvent(t){let e=document.activeElement;const i=t.closest("ngx-extended-pdf-viewer");for(;e&&e!==document.body;){if(e===i)return!0;if(-1!==e.tabIndex)return!1;e=e.parentElement}return!0})(t)&&(e>0?i.nextPage():i.previousPage());s=!0}}if(4===r)switch(t.keyCode){case 13:case 32:if(!n&&"page-fit"!==i.currentScaleValue)break;i.previousPage();s=!0;break;case 38:this.moveCaret(!0,!0);s=!0;break;case 40:this.moveCaret(!1,!0);s=!0;break;case 82:this.rotatePages(-90)}a&&!i.containsElement(o)&&i.focus();s&&t.preventDefault()}}function beforeUnload(t){t.preventDefault();t.returnValue="";return!1}_e.printPdf=function printPdf(){if(this.enablePrint)if(he)n.NgxConsole.warn("Ignored this.printPDF() because of a pending print job.");else{ensureOverlay().then((function(){he&&ce.open(de)}));try{dispatchEvent("beforeprint")}finally{if(!he){n.NgxConsole.error("Expected print service to be initialized.");ensureOverlay().then((function(){ce.active===de&&ce.close(de)}));return}const t=he,e=document.createElement("div");e.id="printContainer";document.body.append(e);t.printContainer=e;he.renderPages().then((function(){const e=document.getElementById("printServiceDialog");e&&e.classList.add("hidden");return t.performPrint()})).catch((function(){})).then((function(){t.active&&abort()}))}}};_e.PDFPrintServiceFactory=PDFPrintServiceFactory;_e.ngxConsole=new n.NgxConsole;_e.serviceWorkerOptions={showUnverifiedSignatures:!1};const Ce={LinkTarget:O,RenderingStates:r,ScrollMode:y,SpreadMode:A};HTMLCollection.prototype[Symbol.iterator]||(HTMLCollection.prototype[Symbol.iterator]=Array.prototype[Symbol.iterator]);"function"!=typeof window.CustomEvent&&(window.CustomEvent=function CustomEvent(t,e){e=e||{bubbles:!1,cancelable:!1,detail:null};const i=document.createEvent("CustomEvent");i.initCustomEvent(t,e.bubbles,e.cancelable,e.detail);return i});function webViewerLoad(t){const e=function getViewerConfiguration(){return{appContainer:document.getElementsByClassName("body")[0],principalContainer:document.getElementById("mainContainer"),mainContainer:document.getElementById("viewerContainer"),viewerContainer:document.getElementById("viewer"),toolbar:{container:document.getElementById("toolbarContainer"),numPages:document.getElementById("numPages"),pageNumber:document.getElementById("pageNumber"),scaleSelect:document.getElementById("scaleSelect"),customScaleOption:document.getElementById("customScaleOption"),previous:document.getElementById("previous"),next:document.getElementById("next"),zoomIn:document.getElementById("primaryZoomIn")??document.getElementById("zoomInButton"),zoomOut:document.getElementById("primaryZoomOut")??document.getElementById("zoomOutButton"),print:document.getElementById("printButton"),editorFreeTextButton:document.getElementById("primaryEditorFreeText")??document.getElementById("editorFreeTextButton"),editorFreeTextParamsToolbar:document.getElementById("editorFreeTextParamsToolbar"),editorHighlightButton:document.getElementById("primaryEditorHighlight")??document.getElementById("editorHighlightButton"),editorHighlightParamsToolbar:document.getElementById("editorHighlightParamsToolbar"),editorHighlightColorPicker:document.getElementById("editorHighlightColorPicker"),editorInkButton:document.getElementById("primaryEditorInk")??document.getElementById("editorInkButton"),editorInkParamsToolbar:document.getElementById("editorInkParamsToolbar"),editorStampButton:document.getElementById("primaryEditorStamp")??document.getElementById("editorStampButton"),presentationModeButton:document.getElementById("presentationMode"),editorStampParamsToolbar:document.getElementById("editorStampParamsToolbar"),download:document.getElementById("downloadButton")},secondaryToolbar:{toolbar:document.getElementById("secondaryToolbar"),toggleButton:document.getElementById("secondaryToolbarToggle"),presentationModeButton:document.getElementById("secondaryPresentationMode"),openFileButton:document.getElementById("secondaryOpenFile"),printButton:document.getElementById("secondaryPrintButton"),downloadButton:document.getElementById("secondaryDownload"),viewBookmarkButton:document.getElementById("viewBookmark"),firstPageButton:document.getElementById("firstPage"),lastPageButton:document.getElementById("lastPage"),pageRotateCwButton:document.getElementById("pageRotateCw"),pageRotateCcwButton:document.getElementById("pageRotateCcw"),cursorSelectToolButton:document.getElementById("cursorSelectTool"),cursorHandToolButton:document.getElementById("cursorHandTool"),scrollPageButton:document.getElementById("scrollPage"),scrollVerticalButton:document.getElementById("scrollVertical"),scrollHorizontalButton:document.getElementById("scrollHorizontal"),scrollWrappedButton:document.getElementById("scrollWrapped"),spreadNoneButton:document.getElementById("spreadNone"),spreadOddButton:document.getElementById("spreadOdd"),spreadEvenButton:document.getElementById("spreadEven"),imageAltTextSettingsButton:document.getElementById("imageAltTextSettings"),imageAltTextSettingsSeparator:document.getElementById("imageAltTextSettingsSeparator"),documentPropertiesButton:document.getElementById("documentProperties")},sidebar:{outerContainer:document.getElementById("outerContainer"),sidebarContainer:document.getElementById("sidebarContainer"),toggleButton:document.getElementById("primarySidebarToggle")??document.getElementById("sidebarToggleButton"),resizer:document.getElementById("sidebarResizer"),thumbnailButton:document.getElementById("viewThumbnail"),outlineButton:document.getElementById("viewOutline"),attachmentsButton:document.getElementById("viewAttachments"),layersButton:document.getElementById("viewLayers"),thumbnailView:document.getElementById("thumbnailView"),outlineView:document.getElementById("outlineView"),attachmentsView:document.getElementById("attachmentsView"),layersView:document.getElementById("layersView"),currentOutlineItemButton:document.getElementById("currentOutlineItem")},findBar:{bar:document.getElementById("findbar"),toggleButton:document.getElementById("primaryViewFind")??document.getElementById("viewFindButton"),findField:document.getElementById("findInput"),highlightAllCheckbox:document.getElementById("findHighlightAll"),caseSensitiveCheckbox:document.getElementById("findMatchCase"),findMultipleCheckbox:document.getElementById("findMultiple"),matchRegExpCheckbox:document.getElementById("matchRegExp"),matchDiacriticsCheckbox:document.getElementById("findMatchDiacritics"),entireWordCheckbox:document.getElementById("findEntireWord"),findMsg:document.getElementById("findMsg"),findResultsCount:document.getElementById("findResultsCount"),findPreviousButton:document.getElementById("findPreviousButton")??document.getElementById("findPrevious"),findNextButton:document.getElementById("findNextButton")??document.getElementById("findNext")},passwordOverlay:{dialog:document.getElementById("passwordDialog"),label:document.getElementById("passwordText"),input:document.getElementById("password"),submitButton:document.getElementById("passwordSubmit"),cancelButton:document.getElementById("passwordCancel")},documentProperties:{dialog:document.getElementById("documentPropertiesDialog"),closeButton:document.getElementById("documentPropertiesClose"),fields:{fileName:document.getElementById("fileNameField"),fileSize:document.getElementById("fileSizeField"),title:document.getElementById("titleField"),author:document.getElementById("authorField"),subject:document.getElementById("subjectField"),keywords:document.getElementById("keywordsField"),creationDate:document.getElementById("creationDateField"),modificationDate:document.getElementById("modificationDateField"),creator:document.getElementById("creatorField"),producer:document.getElementById("producerField"),version:document.getElementById("versionField"),pageCount:document.getElementById("pageCountField"),pageSize:document.getElementById("pageSizeField"),linearized:document.getElementById("linearizedField")}},altTextDialog:{dialog:document.getElementById("altTextDialog"),optionDescription:document.getElementById("descriptionButton"),optionDecorative:document.getElementById("decorativeButton"),textarea:document.getElementById("descriptionTextarea"),cancelButton:document.getElementById("altTextCancel"),saveButton:document.getElementById("altTextSave")},newAltTextDialog:{dialog:document.getElementById("newAltTextDialog"),title:document.getElementById("newAltTextTitle"),descriptionContainer:document.getElementById("newAltTextDescriptionContainer"),textarea:document.getElementById("newAltTextDescriptionTextarea"),disclaimer:document.getElementById("newAltTextDisclaimer"),learnMore:document.getElementById("newAltTextLearnMore"),imagePreview:document.getElementById("newAltTextImagePreview"),createAutomatically:document.getElementById("newAltTextCreateAutomatically"),createAutomaticallyButton:document.getElementById("newAltTextCreateAutomaticallyButton"),downloadModel:document.getElementById("newAltTextDownloadModel"),downloadModelDescription:document.getElementById("newAltTextDownloadModelDescription"),error:document.getElementById("newAltTextError"),errorCloseButton:document.getElementById("newAltTextCloseButton"),cancelButton:document.getElementById("newAltTextCancel"),notNowButton:document.getElementById("newAltTextNotNow"),saveButton:document.getElementById("newAltTextSave")},altTextSettingsDialog:{dialog:document.getElementById("altTextSettingsDialog"),createModelButton:document.getElementById("createModelButton"),aiModelSettings:document.getElementById("aiModelSettings"),learnMore:document.getElementById("altTextSettingsLearnMore"),deleteModelButton:document.getElementById("deleteModelButton"),downloadModelButton:document.getElementById("downloadModelButton"),showAltTextDialogButton:document.getElementById("showAltTextDialogButton"),altTextSettingsCloseButton:document.getElementById("altTextSettingsCloseButton"),closeButton:document.getElementById("altTextSettingsCloseButton")},annotationEditorParams:{editorFreeTextFontSize:document.getElementById("editorFreeTextFontSize"),editorFreeTextColor:document.getElementById("editorFreeTextColor"),editorInkColor:document.getElementById("editorInkColor"),editorInkThickness:document.getElementById("editorInkThickness"),editorInkOpacity:document.getElementById("editorInkOpacity"),editorStampAddImage:document.getElementById("editorStampAddImage"),editorFreeHighlightThickness:document.getElementById("editorFreeHighlightThickness"),editorHighlightShowAll:document.getElementById("editorHighlightShowAll")},editorUndoBar:{container:document.getElementById("editorUndoBar"),message:document.getElementById("editorUndoBarMessage"),undoButton:document.getElementById("editorUndoBarUndoButton"),closeButton:document.getElementById("editorUndoBarCloseButton")}}}(),i=new CustomEvent("webviewerloaded",{bubbles:!0,cancelable:!0,detail:{source:window}});try{parent.document.dispatchEvent(i)}catch(t){NgxConsole.error("webviewerloaded:",t);document.dispatchEvent(i)}e.cspPolicyService=t;_e.run(e)}document.blockUnblockOnload?.(!0);globalThis.STANDALONE_VIEWER&&("interactive"===document.readyState||"complete"===document.readyState?webViewerLoad():document.addEventListener("DOMContentLoaded",webViewerLoad,!0));const Te=new CustomEvent("ngxViewerFileHasBeenLoaded",{detail:{PDFViewerApplication:_e,PDFViewerApplicationConstants:Ce,PDFViewerApplicationOptions:AppOptions,webViewerLoad}});document.dispatchEvent(Te)}},e={};function __webpack_require__(i){var n=e[i];if(void 0!==n)return n.exports;var s=e[i]={exports:{}};t[i](s,s.exports,__webpack_require__);return s.exports}__webpack_require__.d=(t,e)=>{for(var i in e)__webpack_require__.o(e,i)&&!__webpack_require__.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})};__webpack_require__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);__webpack_require__(276);var __webpack_exports__=__webpack_require__(909),i=__webpack_exports__.AbortException,n=__webpack_exports__.AnnotationEditorLayer,s=__webpack_exports__.AnnotationEditorParamsType,a=__webpack_exports__.AnnotationEditorType,r=__webpack_exports__.AnnotationEditorUIManager,o=__webpack_exports__.AnnotationLayer,l=__webpack_exports__.AnnotationMode,h=__webpack_exports__.ColorPicker,d=__webpack_exports__.DOMSVGFactory,c=__webpack_exports__.DrawLayer,u=__webpack_exports__.FeatureTest,p=__webpack_exports__.GlobalWorkerOptions,g=__webpack_exports__.ImageKind,m=__webpack_exports__.InvalidPDFException,f=__webpack_exports__.MissingPDFException,b=__webpack_exports__.OPS,w=__webpack_exports__.OutputScale,v=__webpack_exports__.PDFDataRangeTransport,y=__webpack_exports__.PDFDateString,A=__webpack_exports__.PDFWorker,x=__webpack_exports__.PasswordResponses,E=__webpack_exports__.PermissionFlag,S=__webpack_exports__.PixelsPerInch,P=__webpack_exports__.RenderingCancelledException,_=__webpack_exports__.TextLayer,C=__webpack_exports__.TouchManager,T=__webpack_exports__.UnexpectedResponseException,M=__webpack_exports__.Util,I=__webpack_exports__.VerbosityLevel,D=__webpack_exports__.XfaLayer,L=__webpack_exports__.build,k=__webpack_exports__.createValidAbsoluteUrl,F=__webpack_exports__.fetchData,R=__webpack_exports__.getDocument,N=__webpack_exports__.getFilenameFromUrl,B=__webpack_exports__.getPdfFilenameFromUrl,O=__webpack_exports__.getXfaPageViewport,V=__webpack_exports__.isDataScheme,H=__webpack_exports__.isPdfFile,z=__webpack_exports__.noContextMenu,U=__webpack_exports__.normalizeUnicode,j=__webpack_exports__.setLayerDimensions,W=__webpack_exports__.shadow,$=__webpack_exports__.stopEvent,G=__webpack_exports__.version;export{i as AbortException,n as AnnotationEditorLayer,s as AnnotationEditorParamsType,a as AnnotationEditorType,r as AnnotationEditorUIManager,o as AnnotationLayer,l as AnnotationMode,h as ColorPicker,d as DOMSVGFactory,c as DrawLayer,u as FeatureTest,p as GlobalWorkerOptions,g as ImageKind,m as InvalidPDFException,f as MissingPDFException,b as OPS,w as OutputScale,v as PDFDataRangeTransport,y as PDFDateString,A as PDFWorker,x as PasswordResponses,E as PermissionFlag,S as PixelsPerInch,P as RenderingCancelledException,_ as TextLayer,C as TouchManager,T as UnexpectedResponseException,M as Util,I as VerbosityLevel,D as XfaLayer,L as build,k as createValidAbsoluteUrl,F as fetchData,R as getDocument,N as getFilenameFromUrl,B as getPdfFilenameFromUrl,O as getXfaPageViewport,V as isDataScheme,H as isPdfFile,z as noContextMenu,U as normalizeUnicode,j as setLayerDimensions,W as shadow,$ as stopEvent,G as version};