pdfjs-viewer-element 2.7.4 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ const e = '/**\n * @licstart The following is the entire license notice for the\n * JavaScript code in this page\n *\n * Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @licend The above is the entire license notice for the\n * JavaScript code in this page\n */var __webpack_require__={d:(e,t)=>{for(var i in t)__webpack_require__.o(t,i)&&!__webpack_require__.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__={};const{AbortException:AbortException,AnnotationEditorLayer:AnnotationEditorLayer,AnnotationEditorParamsType:AnnotationEditorParamsType,AnnotationEditorType:AnnotationEditorType,AnnotationEditorUIManager:AnnotationEditorUIManager,AnnotationLayer:AnnotationLayer,AnnotationMode:AnnotationMode,AnnotationType:AnnotationType,applyOpacity:applyOpacity,build:build,ColorPicker:ColorPicker,createValidAbsoluteUrl:createValidAbsoluteUrl,CSSConstants:CSSConstants,DOMSVGFactory:DOMSVGFactory,DrawLayer:DrawLayer,FeatureTest:FeatureTest,fetchData:fetchData,findContrastColor:findContrastColor,getDocument:getDocument,getFilenameFromUrl:getFilenameFromUrl,getPdfFilenameFromUrl:pdfjs_getPdfFilenameFromUrl,getRGB:getRGB,getUuid:getUuid,getXfaPageViewport:getXfaPageViewport,GlobalWorkerOptions:GlobalWorkerOptions,ImageKind:ImageKind,InvalidPDFException:InvalidPDFException,isDataScheme:isDataScheme,isPdfFile:isPdfFile,isValidExplicitDest:isValidExplicitDest,MathClamp:MathClamp,noContextMenu:noContextMenu,normalizeUnicode:normalizeUnicode,OPS:OPS,OutputScale:OutputScale,PagesMapper:PagesMapper,PasswordResponses:PasswordResponses,PDFDataRangeTransport:PDFDataRangeTransport,PDFDateString:PDFDateString,PDFWorker:PDFWorker,PermissionFlag:PermissionFlag,PixelsPerInch:PixelsPerInch,RenderingCancelledException:RenderingCancelledException,renderRichText:renderRichText,ResponseException:ResponseException,setLayerDimensions:setLayerDimensions,shadow:shadow,SignatureExtractor:SignatureExtractor,stopEvent:stopEvent,SupportedImageMimeTypes:SupportedImageMimeTypes,TextLayer:TextLayer,TouchManager:TouchManager,updateUrlHash:updateUrlHash,Util:Util,VerbosityLevel:VerbosityLevel,version:version,XfaLayer:XfaLayer}=globalThis.pdfjsLib,DEFAULT_SCALE_VALUE="auto",DEFAULT_SCALE=1,DEFAULT_SCALE_DELTA=1.1,MIN_SCALE=.1,MAX_SCALE=10,UNKNOWN_SCALE=0,MAX_AUTO_SCALE=1.25,SCROLLBAR_PADDING=40,VERTICAL_PADDING=5,RenderingStates={INITIAL:0,RUNNING:1,PAUSED:2,FINISHED:3},PresentationModeState={UNKNOWN:0,NORMAL:1,CHANGING:2,FULLSCREEN:3},SidebarView={UNKNOWN:-1,NONE:0,THUMBS:1,OUTLINE:2,ATTACHMENTS:3,LAYERS:4},TextLayerMode={DISABLE:0,ENABLE:1,ENABLE_PERMISSIONS:2},ScrollMode={UNKNOWN:-1,VERTICAL:0,HORIZONTAL:1,WRAPPED:2,PAGE:3},SpreadMode={UNKNOWN:-1,NONE:0,ODD:1,EVEN:2},CursorTool={SELECT:0,HAND:1,ZOOM:2},AutoPrintRegExp=/\\bprint\\s*\\(/;function scrollIntoView(e,t,i=!1){let n=e.offsetParent;if(!n)return void console.error("offsetParent is not set -- cannot scroll");let s=e.offsetTop+e.clientTop,a=e.offsetLeft+e.clientLeft;for(;n.clientHeight===n.scrollHeight&&n.clientWidth===n.scrollWidth||i&&(n.classList.contains("markedContent")||"hidden"===getComputedStyle(n).overflow);)if(s+=n.offsetTop,a+=n.offsetLeft,n=n.offsetParent,!n)return;if(t&&(void 0!==t.top&&(s+=t.top),void 0!==t.left)){if(i){const i=e.getBoundingClientRect().width,s=MathClamp((n.clientWidth-i)/2,20,400);a+=t.left-s}else a+=t.left;n.scrollLeft=a}n.scrollTop=s}function watchScroll(e,t,i=void 0){const n=function(i){a||(a=window.requestAnimationFrame((function(){a=null;const i=e.scrollLeft,n=s.lastX;i!==n&&(s.right=i>n),s.lastX=i;const o=e.scrollTop,r=s.lastY;o!==r&&(s.down=o>r),s.lastY=o,t(s)})))},s={right:!0,down:!0,lastX:e.scrollLeft,lastY:e.scrollTop,_eventHandler:n};let a=null;return e.addEventListener("scroll",n,{useCapture:!0,signal:i}),i?.addEventListener("abort",(()=>window.cancelAnimationFrame(a)),{once:!0}),s}function parseQueryString(e){const t=new Map;for(const[i,n]of new URLSearchParams(e))t.set(i.toLowerCase(),n);return t}const InvisibleCharsRegExp=/[\\x00-\\x1F]/g;function removeNullCharacters(e,t=!1){return InvisibleCharsRegExp.test(e)?t?e.replaceAll(InvisibleCharsRegExp,(e=>"\\0"===e?"":" ")):e.replaceAll("\\0",""):e}function binarySearchFirstItem(e,t,i=0){let n=i,s=e.length-1;if(s<0||!t(e[s]))return e.length;if(t(e[n]))return n;for(;n<s;){const i=n+s>>1;t(e[i])?s=i:n=i+1}return n}function approximateFraction(e){if(Math.floor(e)===e)return[e,1];const t=1/e;if(t>8)return[1,8];if(Math.floor(t)===t)return[1,t];const i=e>1?t:e;let n,s=0,a=1,o=1,r=1;for(;;){const e=s+o,t=a+r;if(t>8)break;i<=e/t?(o=e,r=t):(s=e,a=t)}return n=i-s/a<o/r-i?i===e?[s,a]:[a,s]:i===e?[o,r]:[r,o],n}function floorToDivide(e,t){return e-e%t}function getPageSizeInches({view:e,userUnit:t,rotate:i}){const[n,s,a,o]=e,r=i%180!=0,l=(a-n)/72*t,d=(o-s)/72*t;return{width:r?d:l,height:r?l:d}}function backtrackBeforeAllVisibleElements(e,t,i){if(e<2)return e;let n=t[e].div,s=n.offsetTop+n.clientTop;s>=i&&(n=t[e-1].div,s=n.offsetTop+n.clientTop);for(let i=e-2;i>=0&&(n=t[i].div,!(n.offsetTop+n.clientTop+n.clientHeight<=s));--i)e=i;return e}function getVisibleElements({scrollEl:e,views:t,sortByVisibility:i=!1,horizontal:n=!1,rtl:s=!1}){const a=e.scrollTop,o=a+e.clientHeight,r=e.scrollLeft,l=r+e.clientWidth;const d=[],h=new Set,c=t.length;let u=binarySearchFirstItem(t,n?function(e){const t=e.div,i=t.offsetLeft+t.clientLeft,n=i+t.clientWidth;return s?i<l:n>r}:function(e){const t=e.div;return t.offsetTop+t.clientTop+t.clientHeight>a});u>0&&u<c&&!n&&(u=backtrackBeforeAllVisibleElements(u,t,a));let g=n?l:-1;for(let e=u;e<c;e++){const i=t[e],s=i.div,c=s.offsetLeft+s.clientLeft,u=s.offsetTop+s.clientTop,p=s.clientWidth,m=s.clientHeight,f=c+p,b=u+m;if(-1===g)b>=o&&(g=b);else if((n?c:u)>g)break;if(b<=a||u>=o||f<=r||c>=l)continue;const v=Math.max(0,a-u),w=Math.max(0,r-c),E=v+Math.max(0,b-o),y=(p-(w+Math.max(0,f-l)))/p,S=(m-E)/m*y*100|0;d.push({id:i.id,x:c,y:u,visibleArea:100===S?null:{minX:w,minY:v,maxX:Math.min(f,l)-c,maxY:Math.min(b,o)-u},view:i,percent:S,widthPercent:100*y|0}),h.add(i.id)}const p=d[0],m=d.at(-1);return i&&d.sort((function(e,t){const i=e.percent-t.percent;return Math.abs(i)>.001?-i:e.id-t.id})),{first:p,last:m,views:d,ids:h}}function normalizeWheelEventDirection(e){let t=Math.hypot(e.deltaX,e.deltaY);const i=Math.atan2(e.deltaY,e.deltaX);return-.25*Math.PI<i&&i<.75*Math.PI&&(t=-t),t}function normalizeWheelEventDelta(e){const t=e.deltaMode;let i=normalizeWheelEventDirection(e);return t===WheelEvent.DOM_DELTA_PIXEL?i/=900:t===WheelEvent.DOM_DELTA_LINE&&(i/=30),i}function isValidRotation(e){return Number.isInteger(e)&&e%90==0}function isValidScrollMode(e){return Number.isInteger(e)&&Object.values(ScrollMode).includes(e)&&e!==ScrollMode.UNKNOWN}function isValidSpreadMode(e){return Number.isInteger(e)&&Object.values(SpreadMode).includes(e)&&e!==SpreadMode.UNKNOWN}function isPortraitOrientation(e){return e.width<=e.height}const animationStarted=new Promise((function(e){window.requestAnimationFrame(e)})),docStyle=document.documentElement.style;class ProgressBar{#e=null;#t=null;#i=0;#n=null;#s=!0;constructor(e){this.#e=e.classList,this.#n=e.style}get percent(){return this.#i}set percent(e){this.#i=e,isNaN(e)?this.#e.add("indeterminate"):(this.#e.remove("indeterminate"),this.#n.setProperty("--progressBar-percent",`${this.#i}%`))}setWidth(e){if(!e)return;const t=e.parentNode.offsetWidth-e.offsetWidth;t>0&&this.#n.setProperty("--progressBar-end-offset",`${t}px`)}setDisableAutoFetch(e=5e3){100===this.#i||isNaN(this.#i)||(this.#t&&clearTimeout(this.#t),this.show(),this.#t=setTimeout((()=>{this.#t=null,this.hide()}),e))}hide(){this.#s&&(this.#s=!1,this.#e.add("hidden"))}show(){this.#s||(this.#s=!0,this.#e.remove("hidden"))}}function getActiveOrFocusedElement(){let e=document,t=e.activeElement||e.querySelector(":focus");for(;t?.shadowRoot;)e=t.shadowRoot,t=e.activeElement||e.querySelector(":focus");return t}function apiPageLayoutToViewerModes(e){let t=ScrollMode.VERTICAL,i=SpreadMode.NONE;switch(e){case"SinglePage":t=ScrollMode.PAGE;break;case"OneColumn":break;case"TwoPageLeft":t=ScrollMode.PAGE;case"TwoColumnLeft":i=SpreadMode.ODD;break;case"TwoPageRight":t=ScrollMode.PAGE;case"TwoColumnRight":i=SpreadMode.EVEN}return{scrollMode:t,spreadMode:i}}function apiPageModeToSidebarView(e){switch(e){case"UseNone":return SidebarView.NONE;case"UseThumbs":return SidebarView.THUMBS;case"UseOutlines":return SidebarView.OUTLINE;case"UseAttachments":return SidebarView.ATTACHMENTS;case"UseOC":return SidebarView.LAYERS}return SidebarView.NONE}function toggleCheckedBtn(e,t,i=null){e.classList.toggle("toggled",t),e.setAttribute("aria-checked",t),i?.classList.toggle("hidden",!t)}function toggleSelectedBtn(e,t,i=null){e.classList.toggle("selected",t),e.setAttribute("aria-selected",t),i?.classList.toggle("hidden",!t)}function toggleExpandedBtn(e,t,i=null){e.classList.toggle("toggled",t),e.setAttribute("aria-expanded",t),i?.classList.toggle("hidden",!t)}const calcRound=function(){const e=document.createElement("div");return e.style.width="round(down, calc(1.6666666666666665 * 792px), 1px)","calc(1320px)"===e.style.width?Math.fround:e=>e}();{var compatParams=new Map;const{maxTouchPoints:e,platform:t,userAgent:i}=navigator,n=/Android/.test(i);(/\\b(iPad|iPhone|iPod)(?=;)/.test(i)||"MacIntel"===t&&e>1||n)&&compatParams.set("maxCanvasPixels",5242880),n&&compatParams.set("useSystemFonts",!1)}const OptionKind={BROWSER:1,VIEWER:2,API:4,WORKER:8,EVENT_DISPATCH:16,PREFERENCE:128},Type={BOOLEAN:1,NUMBER:2,OBJECT:4,STRING:8,UNDEFINED:16},defaultOptions={allowedGlobalEvents:{value:null,kind:OptionKind.BROWSER},canvasMaxAreaInBytes:{value:-1,kind:OptionKind.BROWSER+OptionKind.API},isInAutomation:{value:!1,kind:OptionKind.BROWSER},localeProperties:{value:{lang:navigator.language||"en-US"},kind:OptionKind.BROWSER},maxCanvasDim:{value:32767,kind:OptionKind.BROWSER+OptionKind.VIEWER},nimbusDataStr:{value:"",kind:OptionKind.BROWSER},supportsCaretBrowsingMode:{value:!1,kind:OptionKind.BROWSER},supportsDocumentFonts:{value:!0,kind:OptionKind.BROWSER},supportsIntegratedFind:{value:!1,kind:OptionKind.BROWSER},supportsMouseWheelZoomCtrlKey:{value:!0,kind:OptionKind.BROWSER},supportsMouseWheelZoomMetaKey:{value:!0,kind:OptionKind.BROWSER},supportsPinchToZoom:{value:!0,kind:OptionKind.BROWSER},supportsPrinting:{value:!0,kind:OptionKind.BROWSER},toolbarDensity:{value:0,kind:OptionKind.BROWSER+OptionKind.EVENT_DISPATCH},altTextLearnMoreUrl:{value:"",kind:OptionKind.VIEWER+OptionKind.PREFERENCE},annotationEditorMode:{value:0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},annotationMode:{value:2,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},capCanvasAreaFactor:{value:200,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},commentLearnMoreUrl:{value:"",kind:OptionKind.VIEWER+OptionKind.PREFERENCE},cursorToolOnLoad:{value:0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},debuggerSrc:{value:"./debugger.mjs",kind:OptionKind.VIEWER},defaultZoomDelay:{value:400,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},defaultZoomValue:{value:"",kind:OptionKind.VIEWER+OptionKind.PREFERENCE},disableHistory:{value:!1,kind:OptionKind.VIEWER},disablePageLabels:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableAltText:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableAltTextModelDownload:{value:!0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE+OptionKind.EVENT_DISPATCH},enableAutoLinking:{value:!0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableComment:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableDetailCanvas:{value:!0,kind:OptionKind.VIEWER},enableGuessAltText:{value:!0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE+OptionKind.EVENT_DISPATCH},enableHighlightFloatingButton:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableNewAltTextWhenAddingImage:{value:!0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableOptimizedPartialRendering:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enablePermissions:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enablePrintAutoRotate:{value:!0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableScripting:{value:!0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableSignatureEditor:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableSplitMerge:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},enableUpdatedAddImage:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},externalLinkRel:{value:"noopener noreferrer nofollow",kind:OptionKind.VIEWER},externalLinkTarget:{value:0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},highlightEditorColors:{value:"yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F,yellow_HCM=#FFFFCC,green_HCM=#53FFBC,blue_HCM=#80EBFF,pink_HCM=#F6B8FF,red_HCM=#C50043",kind:OptionKind.VIEWER+OptionKind.PREFERENCE},historyUpdateUrl:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},ignoreDestinationZoom:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},imageResourcesPath:{value:"./images/",kind:OptionKind.VIEWER},maxCanvasPixels:{value:2**25,kind:OptionKind.VIEWER},minDurationToUpdateCanvas:{value:500,kind:OptionKind.VIEWER},forcePageColors:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},pageColorsBackground:{value:"Canvas",kind:OptionKind.VIEWER+OptionKind.PREFERENCE},pageColorsForeground:{value:"CanvasText",kind:OptionKind.VIEWER+OptionKind.PREFERENCE},pdfBugEnabled:{value:!1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},printResolution:{value:150,kind:OptionKind.VIEWER},sidebarViewOnLoad:{value:-1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},scrollModeOnLoad:{value:-1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},spreadModeOnLoad:{value:-1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},textLayerMode:{value:1,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},viewerCssTheme:{value:0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},viewOnLoad:{value:0,kind:OptionKind.VIEWER+OptionKind.PREFERENCE},cMapPacked:{value:!0,kind:OptionKind.API},cMapUrl:{value:"../web/cmaps/",kind:OptionKind.API},disableAutoFetch:{value:!1,kind:OptionKind.API+OptionKind.PREFERENCE},disableFontFace:{value:!1,kind:OptionKind.API+OptionKind.PREFERENCE},disableRange:{value:!1,kind:OptionKind.API+OptionKind.PREFERENCE},disableStream:{value:!1,kind:OptionKind.API+OptionKind.PREFERENCE},docBaseUrl:{value:"",kind:OptionKind.API},enableHWA:{value:!0,kind:OptionKind.API+OptionKind.VIEWER+OptionKind.PREFERENCE},enableXfa:{value:!0,kind:OptionKind.API+OptionKind.PREFERENCE},fontExtraProperties:{value:!1,kind:OptionKind.API},iccUrl:{value:"../web/iccs/",kind:OptionKind.API},isEvalSupported:{value:!0,kind:OptionKind.API},isOffscreenCanvasSupported:{value:!0,kind:OptionKind.API},maxImageSize:{value:-1,kind:OptionKind.API},pdfBug:{value:!1,kind:OptionKind.API},standardFontDataUrl:{value:"../web/standard_fonts/",kind:OptionKind.API},useSystemFonts:{value:void 0,kind:OptionKind.API,type:Type.BOOLEAN+Type.UNDEFINED},verbosity:{value:1,kind:OptionKind.API},wasmUrl:{value:"../web/wasm/",kind:OptionKind.API},workerPort:{value:null,kind:OptionKind.WORKER},workerSrc:{value:"../build/pdf.worker.mjs",kind:OptionKind.WORKER}};defaultOptions.defaultUrl={value:"compressed.tracemonkey-pldi-09.pdf",kind:OptionKind.VIEWER},defaultOptions.sandboxBundleSrc={value:"../build/pdf.sandbox.mjs",kind:OptionKind.VIEWER},defaultOptions.enableFakeMLManager={value:!0,kind:OptionKind.VIEWER},defaultOptions.disablePreferences={value:!1,kind:OptionKind.VIEWER};class AppOptions{static eventBus;static#a=new Map;static{for(const e in defaultOptions)this.#a.set(e,defaultOptions[e].value);for(const[e,t]of compatParams)this.#a.set(e,t);this._hasInvokedSet=!1,this._checkDisablePreferences=()=>!!this.get("disablePreferences")||(this._hasInvokedSet&&console.warn(\'The Preferences may override manually set AppOptions; please use the "disablePreferences"-option to prevent that.\'),!1)}static get(e){return this.#a.get(e)}static getAll(e=null,t=!1){const i=Object.create(null);for(const n in defaultOptions){const s=defaultOptions[n];(!e||e&s.kind)&&(i[n]=t?s.value:this.#a.get(n))}return i}static set(e,t){this.setAll({[e]:t})}static setAll(e,t=!1){let i;this._hasInvokedSet||=!0;for(const n in e){const s=defaultOptions[n],a=e[n];if(!s||!(typeof a==typeof s.value||Type[(typeof a).toUpperCase()]&s.type))continue;const{kind:o}=s;(!t||o&OptionKind.BROWSER||o&OptionKind.PREFERENCE)&&(this.eventBus&&o&OptionKind.EVENT_DISPATCH&&(i||=new Map).set(n,a),this.#a.set(n,a))}if(i)for(const[e,t]of i)this.eventBus.dispatch(e.toLowerCase(),{source:this,value:t})}}const DEFAULT_LINK_REL="noopener noreferrer nofollow",LinkTarget={NONE:0,SELF:1,BLANK:2,PARENT:3,TOP:4};class PDFLinkService{externalLinkEnabled=!0;constructor({eventBus:e,externalLinkTarget:t=null,externalLinkRel:i=null,ignoreDestinationZoom:n=!1}={}){this.eventBus=e,this.externalLinkTarget=t,this.externalLinkRel=i,this._ignoreDestinationZoom=n,this.baseUrl=null,this.pdfDocument=null,this.pdfViewer=null,this.pdfHistory=null}setDocument(e,t=null){this.baseUrl=t,this.pdfDocument=e}setViewer(e){this.pdfViewer=e}setHistory(e){this.pdfHistory=e}get pagesCount(){return this.pdfDocument?this.pdfDocument.numPages:0}get page(){return this.pdfDocument?this.pdfViewer.currentPageNumber:1}set page(e){this.pdfDocument&&(this.pdfViewer.currentPageNumber=e)}get rotation(){return this.pdfDocument?this.pdfViewer.pagesRotation:0}set rotation(e){this.pdfDocument&&(this.pdfViewer.pagesRotation=e)}get isInPresentationMode(){return!!this.pdfDocument&&this.pdfViewer.isInPresentationMode}async goToDestination(e){if(!this.pdfDocument)return;let t,i,n;if("string"==typeof e?(t=e,i=await this.pdfDocument.getDestination(e)):(t=null,i=await e),!Array.isArray(i))return void console.error(`goToDestination: "${i}" is not a valid destination array, for dest="${e}".`);const[s]=i;if(s&&"object"==typeof s){if(n=this.pdfDocument.cachedPageNumber(s),!n)try{n=await this.pdfDocument.getPageIndex(s)+1}catch{return void console.error(`goToDestination: "${s}" is not a valid page reference, for dest="${e}".`)}}else Number.isInteger(s)&&(n=s+1);if(!n||n<1||n>this.pagesCount)return void console.error(`goToDestination: "${n}" is not a valid page number, for dest="${e}".`);this.pdfHistory&&(this.pdfHistory.pushCurrentPosition(),this.pdfHistory.push({namedDest:t,explicitDest:i,pageNumber:n})),this.pdfViewer.scrollPageIntoView({pageNumber:n,destArray:i,ignoreDestinationZoom:this._ignoreDestinationZoom});const a=new AbortController;this.eventBus._on("textlayerrendered",(e=>{e.pageNumber===n&&(e.source.textLayer.div.focus(),a.abort())}),{signal:a.signal})}goToPage(e){if(!this.pdfDocument)return;const t="string"==typeof e&&this.pdfViewer.pageLabelToPageNumber(e)||0|e;Number.isInteger(t)&&t>0&&t<=this.pagesCount?(this.pdfHistory&&(this.pdfHistory.pushCurrentPosition(),this.pdfHistory.pushPage(t)),this.pdfViewer.scrollPageIntoView({pageNumber:t})):console.error(`PDFLinkService.goToPage: "${e}" is not a valid page.`)}goToXY(e,t,i,n={}){this.pdfViewer.scrollPageIntoView({pageNumber:e,destArray:[null,{name:"XYZ"},t,i],ignoreDestinationZoom:!0,...n})}addLinkAttributes(e,t,i=!1){if(!t||"string"!=typeof t)throw new Error(\'A valid "url" parameter must provided.\');const n=i?LinkTarget.BLANK:this.externalLinkTarget,s=this.externalLinkRel;this.externalLinkEnabled?e.href=e.title=t:(e.href="",e.title=`Disabled: ${t}`,e.onclick=()=>!1);let a="";switch(n){case LinkTarget.NONE:break;case LinkTarget.SELF:a="_self";break;case LinkTarget.BLANK:a="_blank";break;case LinkTarget.PARENT:a="_parent";break;case LinkTarget.TOP:a="_top"}e.target=a,e.rel="string"==typeof s?s:DEFAULT_LINK_REL}getDestinationHash(e){if("string"==typeof e){if(e.length>0)return this.getAnchorUrl("#"+escape(e))}else if(Array.isArray(e)){const t=JSON.stringify(e);if(t.length>0)return this.getAnchorUrl("#"+escape(t))}return this.getAnchorUrl("")}getAnchorUrl(e){return this.baseUrl?this.baseUrl+e:e}setHash(e){if(!this.pdfDocument)return;let t,i;if(e.includes("=")){const n=parseQueryString(e);if(n.has("search")){const e=n.get("search").replaceAll(\'"\',""),t="true"===n.get("phrase");this.eventBus.dispatch("findfromurlhash",{source:this,query:t?e:e.match(/\\S+/g)})}if(n.has("page")&&(t=0|n.get("page")||1),n.has("zoom")){const e=n.get("zoom").split(","),t=e[0],s=parseFloat(t);t.includes("Fit")?"Fit"===t||"FitB"===t?i=[null,{name:t}]:"FitH"===t||"FitBH"===t||"FitV"===t||"FitBV"===t?i=[null,{name:t},e.length>1?0|e[1]:null]:"FitR"===t?5!==e.length?console.error(\'PDFLinkService.setHash: Not enough parameters for "FitR".\'):i=[null,{name:t},0|e[1],0|e[2],0|e[3],0|e[4]]:console.error(`PDFLinkService.setHash: "${t}" is not a valid zoom value.`):i=[null,{name:"XYZ"},e.length>1?0|e[1]:null,e.length>2?0|e[2]:null,s?s/100:t]}return i?this.pdfViewer.scrollPageIntoView({pageNumber:t||this.page,destArray:i,allowNegativeOffset:!0}):t&&(this.page=t),n.has("pagemode")&&this.eventBus.dispatch("pagemode",{source:this,mode:n.get("pagemode")}),void(n.has("nameddest")&&this.goToDestination(n.get("nameddest")))}i=unescape(e);try{i=JSON.parse(i),Array.isArray(i)||(i=i.toString())}catch{}"string"==typeof i||isValidExplicitDest(i)?this.goToDestination(i):console.error(`PDFLinkService.setHash: "${unescape(e)}" is not a valid destination.`)}executeNamedAction(e){if(this.pdfDocument){switch(e){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:e})}}async executeSetOCGState(e){if(!this.pdfDocument)return;const t=this.pdfDocument,i=await this.pdfViewer.optionalContentConfigPromise;t===this.pdfDocument&&(i.setOCGState(e),this.pdfViewer.optionalContentConfigPromise=Promise.resolve(i))}}class SimpleLinkService extends PDFLinkService{setDocument(e,t=null){}}const WaitOnType={EVENT:"event",TIMEOUT:"timeout"};async function waitOnEventOrTimeout({target:e,name:t,delay:i=0}){if("object"!=typeof e||!t||"string"!=typeof t||!(Number.isInteger(i)&&i>=0))throw new Error("waitOnEventOrTimeout - invalid parameters.");const{promise:n,resolve:s}=Promise.withResolvers(),a=new AbortController;function o(e){a.abort(),clearTimeout(r),s(e)}e[e instanceof EventBus?"_on":"addEventListener"](t,o.bind(null,WaitOnType.EVENT),{signal:a.signal});const r=setTimeout(o.bind(null,WaitOnType.TIMEOUT),i);return n}class EventBus{#o=Object.create(null);on(e,t,i=null){this._on(e,t,{external:!0,once:i?.once,signal:i?.signal})}off(e,t,i=null){this._off(e,t)}dispatch(e,t){const i=this.#o[e];if(!i||0===i.length)return;let n;for(const{listener:s,external:a,once:o}of i.slice(0))o&&this._off(e,s),a?(n||=[]).push(s):s(t);if(n){for(const e of n)e(t);n=null}}_on(e,t,i=null){let n=null;if(i?.signal instanceof AbortSignal){const{signal:s}=i;if(s.aborted)return void console.error("Cannot use an `aborted` signal.");const a=()=>this._off(e,t);n=()=>s.removeEventListener("abort",a),s.addEventListener("abort",a)}(this.#o[e]||=[]).push({listener:t,external:!0===i?.external,once:!0===i?.once,rmAbort:n})}_off(e,t,i=null){const n=this.#o[e];if(n)for(let e=0,i=n.length;e<i;e++){const i=n[e];if(i.listener===t)return i.rmAbort?.(),void n.splice(e,1)}}}class FirefoxEventBus extends EventBus{#r;#l;#d;constructor(e,t,i){super(),this.#l=e,this.#r=t,this.#d=i}dispatch(e,t){throw new Error("Not implemented: FirefoxEventBus.dispatch")}}class BaseExternalServices{updateFindControlState(e){}updateFindMatchesCount(e){}initPassiveLoading(){}reportTelemetry(e){}reportText(e){}async createL10n(){throw new Error("Not implemented: createL10n")}createScripting(){throw new Error("Not implemented: createScripting")}createSignatureStorage(){throw new Error("Not implemented: createSignatureStorage")}updateEditorStates(e){throw new Error("Not implemented: updateEditorStates")}dispatchGlobalEvent(e){}}class BasePreferences{#h=Object.freeze(AppOptions.getAll(OptionKind.PREFERENCE,!0));#c=null;constructor(){this.#c=this._readFromStorage(this.#h).then((({browserPrefs:e,prefs:t})=>{AppOptions._checkDisablePreferences()||AppOptions.setAll({...e,...t},!0)}))}async _writeToStorage(e){throw new Error("Not implemented: _writeToStorage")}async _readFromStorage(e){throw new Error("Not implemented: _readFromStorage")}async reset(){await this.#c,AppOptions.setAll(this.#h,!0),await this._writeToStorage(this.#h)}async set(e,t){await this.#c,AppOptions.setAll({[e]:t},!0),await this._writeToStorage(AppOptions.getAll(OptionKind.PREFERENCE))}async get(e){return await this.#c,AppOptions.get(e)}get defaults(){return this.#h}get initializedPromise(){return this.#c}}class FluentType{constructor(e){this.value=e}valueOf(){return this.value}}class FluentNone extends FluentType{constructor(e="???"){super(e)}toString(e){return`{${this.value}}`}}class FluentNumber extends FluentType{constructor(e,t={}){super(e),this.opts=t}toString(e){if(e)try{return e.memoizeIntlObject(Intl.NumberFormat,this.opts).format(this.value)}catch(t){e.reportError(t)}return this.value.toString(10)}}class FluentDateTime extends FluentType{static supportsValue(e){if("number"==typeof e)return!0;if(e instanceof Date)return!0;if(e instanceof FluentType)return FluentDateTime.supportsValue(e.valueOf());if("Temporal"in globalThis){const t=globalThis.Temporal;if(e instanceof t.Instant||e instanceof t.PlainDateTime||e instanceof t.PlainDate||e instanceof t.PlainMonthDay||e instanceof t.PlainTime||e instanceof t.PlainYearMonth)return!0}return!1}constructor(e,t={}){e instanceof FluentDateTime?(t={...e.opts,...t},e=e.value):e instanceof FluentType&&(e=e.valueOf()),"object"==typeof e&&"calendarId"in e&&void 0===t.calendar&&(t={...t,calendar:e.calendarId}),super(e),this.opts=t}[Symbol.toPrimitive](e){return"string"===e?this.toString():this.toNumber()}toNumber(){const e=this.value;if("number"==typeof e)return e;if(e instanceof Date)return e.getTime();if("epochMilliseconds"in e)return e.epochMilliseconds;if("toZonedDateTime"in e)return e.toZonedDateTime("UTC").epochMilliseconds;throw new TypeError("Unwrapping a non-number value as a number")}toString(e){if(e)try{return e.memoizeIntlObject(Intl.DateTimeFormat,this.opts).format(this.value)}catch(t){e.reportError(t)}return"number"==typeof this.value||this.value instanceof Date?new Date(this.value).toISOString():this.value.toString()}}const MAX_PLACEABLES=100,FSI="⁨",PDI="⁩";function match(e,t,i){if(i===t)return!0;if(i instanceof FluentNumber&&t instanceof FluentNumber&&i.value===t.value)return!0;if(t instanceof FluentNumber&&"string"==typeof i){if(i===e.memoizeIntlObject(Intl.PluralRules,t.opts).select(t.value))return!0}return!1}function getDefault(e,t,i){return t[i]?resolvePattern(e,t[i].value):(e.reportError(new RangeError("No default")),new FluentNone)}function getArguments(e,t){const i=[],n=Object.create(null);for(const s of t)"narg"===s.type?n[s.name]=resolveExpression(e,s.value):i.push(resolveExpression(e,s));return{positional:i,named:n}}function resolveExpression(e,t){switch(t.type){case"str":return t.value;case"num":return new FluentNumber(t.value,{minimumFractionDigits:t.precision});case"var":return resolveVariableReference(e,t);case"mesg":return resolveMessageReference(e,t);case"term":return resolveTermReference(e,t);case"func":return resolveFunctionReference(e,t);case"select":return resolveSelectExpression(e,t);default:return new FluentNone}}function resolveVariableReference(e,{name:t}){let i;if(e.params){if(!Object.prototype.hasOwnProperty.call(e.params,t))return new FluentNone(`$${t}`);i=e.params[t]}else{if(!e.args||!Object.prototype.hasOwnProperty.call(e.args,t))return e.reportError(new ReferenceError(`Unknown variable: $${t}`)),new FluentNone(`$${t}`);i=e.args[t]}if(i instanceof FluentType)return i;switch(typeof i){case"string":return i;case"number":return new FluentNumber(i);case"object":if(FluentDateTime.supportsValue(i))return new FluentDateTime(i);default:return e.reportError(new TypeError(`Variable type not supported: $${t}, ${typeof i}`)),new FluentNone(`$${t}`)}}function resolveMessageReference(e,{name:t,attr:i}){const n=e.bundle._messages.get(t);if(!n)return e.reportError(new ReferenceError(`Unknown message: ${t}`)),new FluentNone(t);if(i){const s=n.attributes[i];return s?resolvePattern(e,s):(e.reportError(new ReferenceError(`Unknown attribute: ${i}`)),new FluentNone(`${t}.${i}`))}return n.value?resolvePattern(e,n.value):(e.reportError(new ReferenceError(`No value: ${t}`)),new FluentNone(t))}function resolveTermReference(e,{name:t,attr:i,args:n}){const s=`-${t}`,a=e.bundle._terms.get(s);if(!a)return e.reportError(new ReferenceError(`Unknown term: ${s}`)),new FluentNone(s);if(i){const t=a.attributes[i];if(t){e.params=getArguments(e,n).named;const i=resolvePattern(e,t);return e.params=null,i}return e.reportError(new ReferenceError(`Unknown attribute: ${i}`)),new FluentNone(`${s}.${i}`)}e.params=getArguments(e,n).named;const o=resolvePattern(e,a.value);return e.params=null,o}function resolveFunctionReference(e,{name:t,args:i}){let n=e.bundle._functions[t];if(!n)return e.reportError(new ReferenceError(`Unknown function: ${t}()`)),new FluentNone(`${t}()`);if("function"!=typeof n)return e.reportError(new TypeError(`Function ${t}() is not callable`)),new FluentNone(`${t}()`);try{let t=getArguments(e,i);return n(t.positional,t.named)}catch(i){return e.reportError(i),new FluentNone(`${t}()`)}}function resolveSelectExpression(e,{selector:t,variants:i,star:n}){let s=resolveExpression(e,t);if(s instanceof FluentNone)return getDefault(e,i,n);for(const t of i){if(match(e,s,resolveExpression(e,t.key)))return resolvePattern(e,t.value)}return getDefault(e,i,n)}function resolveComplexPattern(e,t){if(e.dirty.has(t))return e.reportError(new RangeError("Cyclic reference")),new FluentNone;e.dirty.add(t);const i=[],n=e.bundle._useIsolating&&t.length>1;for(const s of t)if("string"!=typeof s){if(e.placeables++,e.placeables>MAX_PLACEABLES)throw e.dirty.delete(t),new RangeError(`Too many placeables expanded: ${e.placeables}, max allowed is ${MAX_PLACEABLES}`);n&&i.push(FSI),i.push(resolveExpression(e,s).toString(e)),n&&i.push(PDI)}else i.push(e.bundle._transform(s));return e.dirty.delete(t),i.join("")}function resolvePattern(e,t){return"string"==typeof t?e.bundle._transform(t):resolveComplexPattern(e,t)}class Scope{constructor(e,t,i){this.dirty=new WeakSet,this.params=null,this.placeables=0,this.bundle=e,this.errors=t,this.args=i}reportError(e){if(!(this.errors&&e instanceof Error))throw e;this.errors.push(e)}memoizeIntlObject(e,t){let i=this.bundle._intls.get(e);i||(i={},this.bundle._intls.set(e,i));let n=JSON.stringify(t);return i[n]||(i[n]=new e(this.bundle.locales,t)),i[n]}}function values(e,t){const i=Object.create(null);for(const[n,s]of Object.entries(e))t.includes(n)&&(i[n]=s.valueOf());return i}const NUMBER_ALLOWED=["unitDisplay","currencyDisplay","useGrouping","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits"];function NUMBER(e,t){let i=e[0];if(i instanceof FluentNone)return new FluentNone(`NUMBER(${i.valueOf()})`);if(i instanceof FluentNumber)return new FluentNumber(i.valueOf(),{...i.opts,...values(t,NUMBER_ALLOWED)});if(i instanceof FluentDateTime)return new FluentNumber(i.toNumber(),{...values(t,NUMBER_ALLOWED)});throw new TypeError("Invalid argument to NUMBER")}const DATETIME_ALLOWED=["dateStyle","timeStyle","fractionalSecondDigits","dayPeriod","hour12","weekday","era","year","month","day","hour","minute","second","timeZoneName"];function DATETIME(e,t){let i=e[0];if(i instanceof FluentNone)return new FluentNone(`DATETIME(${i.valueOf()})`);if(i instanceof FluentDateTime||i instanceof FluentNumber)return new FluentDateTime(i,values(t,DATETIME_ALLOWED));throw new TypeError("Invalid argument to DATETIME")}const cache=new Map;function getMemoizerForLocale(e){const t=Array.isArray(e)?e.join(" "):e;let i=cache.get(t);return void 0===i&&(i=new Map,cache.set(t,i)),i}class FluentBundle{constructor(e,{functions:t,useIsolating:i=!0,transform:n=(e=>e)}={}){this._terms=new Map,this._messages=new Map,this.locales=Array.isArray(e)?e:[e],this._functions={NUMBER:NUMBER,DATETIME:DATETIME,...t},this._useIsolating=i,this._transform=n,this._intls=getMemoizerForLocale(e)}hasMessage(e){return this._messages.has(e)}getMessage(e){return this._messages.get(e)}addResource(e,{allowOverrides:t=!1}={}){const i=[];for(let n=0;n<e.body.length;n++){let s=e.body[n];if(s.id.startsWith("-")){if(!1===t&&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===t&&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(e,t=null,i=null){if("string"==typeof e)return this._transform(e);let n=new Scope(this,i,t);try{return resolveComplexPattern(n,e).toString(n)}catch(e){if(n.errors&&e instanceof Error)return n.errors.push(e),(new FluentNone).toString(n);throw e}}}const RE_MESSAGE_START=/^(-?[a-zA-Z][\\w-]*) *= */gm,RE_ATTRIBUTE_START=/\\.([a-zA-Z][\\w-]*) *= */y,RE_VARIANT_START=/\\*?\\[/y,RE_NUMBER_LITERAL=/(-?[0-9]+(?:\\.([0-9]+))?)/y,RE_IDENTIFIER=/([a-zA-Z][\\w-]*)/y,RE_REFERENCE=/([$-])?([a-zA-Z][\\w-]*)(?:\\.([a-zA-Z][\\w-]*))?/y,RE_FUNCTION_NAME=/^[A-Z][A-Z0-9_-]*$/,RE_TEXT_RUN=/([^{}\\n\\r]+)/y,RE_STRING_RUN=/([^\\\\"\\n\\r]*)/y,RE_STRING_ESCAPE=/\\\\([\\\\"])/y,RE_UNICODE_ESCAPE=/\\\\u([a-fA-F0-9]{4})|\\\\U([a-fA-F0-9]{6})/y,RE_LEADING_NEWLINES=/^\\n+/,RE_TRAILING_SPACES=/ +$/,RE_BLANK_LINES=/ *\\r?\\n/g,RE_INDENT=/( *)$/,TOKEN_BRACE_OPEN=/{\\s*/y,TOKEN_BRACE_CLOSE=/\\s*}/y,TOKEN_BRACKET_OPEN=/\\[\\s*/y,TOKEN_BRACKET_CLOSE=/\\s*] */y,TOKEN_PAREN_OPEN=/\\s*\\(\\s*/y,TOKEN_ARROW=/\\s*->\\s*/y,TOKEN_COLON=/\\s*:\\s*/y,TOKEN_COMMA=/\\s*,?\\s*/y,TOKEN_BLANK=/\\s+/y;class FluentResource{constructor(e){this.body=[],RE_MESSAGE_START.lastIndex=0;let t=0;for(;;){let i=RE_MESSAGE_START.exec(e);if(null===i)break;t=RE_MESSAGE_START.lastIndex;try{this.body.push(r(i[1]))}catch(e){if(e instanceof SyntaxError)continue;throw e}}function i(i){return i.lastIndex=t,i.test(e)}function n(i,n){if(e[t]===i)return t++,!0;if(n)throw new n(`Expected ${i}`);return!1}function s(e,n){if(i(e))return t=e.lastIndex,!0;if(n)throw new n(`Expected ${e.toString()}`);return!1}function a(i){i.lastIndex=t;let n=i.exec(e);if(null===n)throw new SyntaxError(`Expected ${i.toString()}`);return t=i.lastIndex,n}function o(e){return a(e)[1]}function r(e){let t=l(),n=function(){let e=Object.create(null);for(;i(RE_ATTRIBUTE_START);){let t=o(RE_ATTRIBUTE_START),i=l();if(null===i)throw new SyntaxError("Expected attribute value");e[t]=i}return e}();if(null===t&&0===Object.keys(n).length)throw new SyntaxError("Expected message value or attributes");return{id:e,value:t,attributes:n}}function l(){let n;if(i(RE_TEXT_RUN)&&(n=o(RE_TEXT_RUN)),"{"===e[t]||"}"===e[t])return d(n?[n]:[],1/0);let s=b();return s?n?d([n,s],s.length):(s.value=v(s.value,RE_LEADING_NEWLINES),d([s],s.length)):n?v(n,RE_TRAILING_SPACES):null}function d(n=[],s){for(;;){if(i(RE_TEXT_RUN)){n.push(o(RE_TEXT_RUN));continue}if("{"===e[t]){n.push(h());continue}if("}"===e[t])throw new SyntaxError("Unbalanced closing brace");let a=b();if(!a)break;n.push(a),s=Math.min(s,a.length)}let a=n.length-1,r=n[a];"string"==typeof r&&(n[a]=v(r,RE_TRAILING_SPACES));let l=[];for(let e of n)e instanceof Indent&&(e=e.value.slice(0,e.value.length-s)),e&&l.push(e);return l}function h(){s(TOKEN_BRACE_OPEN,SyntaxError);let e=c();if(s(TOKEN_BRACE_CLOSE))return e;if(s(TOKEN_ARROW)){let t=function(){let e,t=[],s=0;for(;i(RE_VARIANT_START);){n("*")&&(e=s);let i=g(),a=l();if(null===a)throw new SyntaxError("Expected variant value");t[s++]={key:i,value:a}}if(0===s)return null;if(void 0===e)throw new SyntaxError("Expected default variant");return{variants:t,star:e}}();return s(TOKEN_BRACE_CLOSE,SyntaxError),{type:"select",selector:e,...t}}throw new SyntaxError("Unclosed placeable")}function c(){if("{"===e[t])return h();if(i(RE_REFERENCE)){let[,i,n,o=null]=a(RE_REFERENCE);if("$"===i)return{type:"var",name:n};if(s(TOKEN_PAREN_OPEN)){let a=function(){let i=[];for(;;){switch(e[t]){case")":return t++,i;case void 0:throw new SyntaxError("Unclosed argument list")}i.push(u()),s(TOKEN_COMMA)}}();if("-"===i)return{type:"term",name:n,attr:o,args:a};if(RE_FUNCTION_NAME.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:o,args:[]}:{type:"mesg",name:n,attr:o}}return p()}function u(){let e=c();return"mesg"!==e.type?e:s(TOKEN_COLON)?{type:"narg",name:e.name,value:p()}:e}function g(){let e;return s(TOKEN_BRACKET_OPEN,SyntaxError),e=i(RE_NUMBER_LITERAL)?m():{type:"str",value:o(RE_IDENTIFIER)},s(TOKEN_BRACKET_CLOSE,SyntaxError),e}function p(){if(i(RE_NUMBER_LITERAL))return m();if(\'"\'===e[t])return function(){n(\'"\',SyntaxError);let i="";for(;;){if(i+=o(RE_STRING_RUN),"\\\\"!==e[t]){if(n(\'"\'))return{type:"str",value:i};throw new SyntaxError("Unclosed string literal")}i+=f()}}();throw new SyntaxError("Invalid expression")}function m(){let[,e,t=""]=a(RE_NUMBER_LITERAL),i=t.length;return{type:"num",value:parseFloat(e),precision:i}}function f(){if(i(RE_STRING_ESCAPE))return o(RE_STRING_ESCAPE);if(i(RE_UNICODE_ESCAPE)){let[,e,t]=a(RE_UNICODE_ESCAPE),i=parseInt(e||t,16);return i<=55295||57344<=i?String.fromCodePoint(i):"�"}throw new SyntaxError("Unknown escape sequence")}function b(){let i=t;switch(s(TOKEN_BLANK),e[t]){case".":case"[":case"*":case"}":case void 0:return!1;case"{":return w(e.slice(i,t))}return" "===e[t-1]&&w(e.slice(i,t))}function v(e,t){return e.replace(t,"")}function w(e){let t=e.replace(RE_BLANK_LINES,"\\n"),i=RE_INDENT.exec(e)[1].length;return new Indent(t,i)}}}class Indent{constructor(e,t){this.value=e,this.length=t}}const reOverlay=/<|&#?\\w+;/,TEXT_LEVEL_ELEMENTS={"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"]},LOCALIZABLE_ATTRIBUTES={"http://www.w3.org/1999/xhtml":{global:["title","aria-description","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(e,t){const{value:i}=t;if("string"==typeof i)if("title"===e.localName&&"http://www.w3.org/1999/xhtml"===e.namespaceURI)e.textContent=i;else if(reOverlay.test(i)){const t=e.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","template");t.innerHTML=i,overlayChildNodes(t.content,e)}else e.textContent=i;overlayAttributes(t,e)}function overlayChildNodes(e,t){for(const i of e.childNodes)if(i.nodeType!==i.TEXT_NODE)if(i.hasAttribute("data-l10n-name")){const n=getNodeForNamedElement(t,i);e.replaceChild(n,i)}else if(isElementAllowed(i)){const t=createSanitizedElement(i);e.replaceChild(t,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.`),e.replaceChild(createTextNodeFromTextContent(i),i);t.textContent="",t.appendChild(e)}function hasAttribute(e,t){if(!e)return!1;for(let i of e)if(i.name===t)return!0;return!1}function overlayAttributes(e,t){const i=t.hasAttribute("data-l10n-attrs")?t.getAttribute("data-l10n-attrs").split(",").map((e=>e.trim())):null;for(const n of Array.from(t.attributes))isAttrNameLocalizable(n.name,t,i)&&!hasAttribute(e.attributes,n.name)&&t.removeAttribute(n.name);if(e.attributes)for(const n of Array.from(e.attributes))isAttrNameLocalizable(n.name,t,i)&&t.getAttribute(n.name)!==n.value&&t.setAttribute(n.name,n.value)}function getNodeForNamedElement(e,t){const i=t.getAttribute("data-l10n-name"),n=e.querySelector(`[data-l10n-name="${i}"]`);if(!n)return console.warn(`An element named "${i}" wasn\'t found in the source.`),createTextNodeFromTextContent(t);if(n.localName!==t.localName)return console.warn(`An element named "${i}" was found in the translation but its type ${t.localName} didn\'t match the element found in the source (${n.localName}).`),createTextNodeFromTextContent(t);e.removeChild(n);return shallowPopulateUsing(t,n.cloneNode(!1))}function createSanitizedElement(e){const t=e.ownerDocument.createElement(e.localName);return shallowPopulateUsing(e,t)}function createTextNodeFromTextContent(e){return e.ownerDocument.createTextNode(e.textContent)}function isElementAllowed(e){const t=TEXT_LEVEL_ELEMENTS[e.namespaceURI];return t&&t.includes(e.localName)}function isAttrNameLocalizable(e,t,i=null){if(i&&i.includes(e))return!0;const n=LOCALIZABLE_ATTRIBUTES[t.namespaceURI];if(!n)return!1;const s=e.toLowerCase(),a=t.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"===t.namespaceURI&&"input"===a&&"value"===s){const e=t.type.toLowerCase();if("submit"===e||"button"===e||"reset"===e)return!0}return!1}function shallowPopulateUsing(e,t){return t.textContent=e.textContent,overlayAttributes(e,t),t}class CachedIterable extends Array{static from(e){return e instanceof this?e:new this(e)}}class CachedSyncIterable extends CachedIterable{constructor(e){if(super(),!(Symbol.iterator in Object(e)))throw new TypeError("Argument must implement the iteration protocol.");this.iterator=e[Symbol.iterator]()}[Symbol.iterator](){const e=this;let t=0;return{next:()=>(e.length<=t&&e.push(e.iterator.next()),e[t++])}}touchNext(e=1){let t=0;for(;t++<e;){const e=this[this.length-1];if(e&&e.done)break;this.push(this.iterator.next())}return this[this.length-1]}}class CachedAsyncIterable extends CachedIterable{constructor(e){if(super(),Symbol.asyncIterator in Object(e))this.iterator=e[Symbol.asyncIterator]();else{if(!(Symbol.iterator in Object(e)))throw new TypeError("Argument must implement the iteration protocol.");this.iterator=e[Symbol.iterator]()}}[Symbol.asyncIterator](){const e=this;let t=0;return{next:async()=>(e.length<=t&&e.push(e.iterator.next()),e[t++])}}async touchNext(e=1){let t=0;for(;t++<e;){const e=this[this.length-1];if(e&&(await e).done)break;this.push(this.iterator.next())}return this[this.length-1]}}class Localization{constructor(e=[],t){this.resourceIds=e,this.generateBundles=t,this.onChange(!0)}addResourceIds(e,t=!1){return this.resourceIds.push(...e),this.onChange(t),this.resourceIds.length}removeResourceIds(e){return this.resourceIds=this.resourceIds.filter((t=>!e.includes(t))),this.onChange(),this.resourceIds.length}async formatWithFallback(e,t){const i=[];let n=!1;for await(const s of this.bundles){n=!0;const a=keysFromBundle(t,s,e,i);if(0===a.size)break;if("undefined"!=typeof console){const e=s.locales[0],t=Array.from(a).join(", ");console.warn(`[fluent] Missing translations in ${e}: ${t}`)}}return n||"undefined"==typeof console||console.warn(`[fluent] Request for keys failed because no resource bundles got generated.\\n keys: ${JSON.stringify(e)}.\\n resourceIds: ${JSON.stringify(this.resourceIds)}.`),i}formatMessages(e){return this.formatWithFallback(e,messageFromBundle)}formatValues(e){return this.formatWithFallback(e,valueFromBundle)}async formatValue(e,t){const[i]=await this.formatValues([{id:e,args:t}]);return i}handleEvent(){this.onChange()}onChange(e=!1){this.bundles=CachedAsyncIterable.from(this.generateBundles(this.resourceIds)),e&&this.bundles.touchNext(2)}}function valueFromBundle(e,t,i,n){return i.value?e.formatPattern(i.value,n,t):null}function messageFromBundle(e,t,i,n){const s={value:null,attributes:null};i.value&&(s.value=e.formatPattern(i.value,n,t));let a=Object.keys(i.attributes);if(a.length>0){s.attributes=new Array(a.length);for(let[o,r]of a.entries()){let a=e.formatPattern(i.attributes[r],n,t);s.attributes[o]={name:r,value:a}}}return s}function keysFromBundle(e,t,i,n){const s=[],a=new Set;return i.forEach((({id:i,args:o},r)=>{if(void 0!==n[r])return;let l=t.getMessage(i);if(l){if(s.length=0,n[r]=e(t,s,l,o),s.length>0&&"undefined"!=typeof console){const e=t.locales[0],n=s.join(", ");console.warn(`[fluent][resolver] errors in ${e}/${i}: ${n}.`)}}else a.add(i)})),a}const L10NID_ATTR_NAME="data-l10n-id",L10NARGS_ATTR_NAME="data-l10n-args",L10N_ELEMENT_QUERY="[data-l10n-id]";class DOMLocalization extends Localization{constructor(e,t){super(e,t),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:["data-l10n-id","data-l10n-args"]}}onChange(e=!1){super.onChange(e),this.roots&&this.translateRoots()}setAttributes(e,t,i){return e.setAttribute("data-l10n-id",t),i?e.setAttribute("data-l10n-args",JSON.stringify(i)):e.removeAttribute("data-l10n-args"),e}getAttributes(e){return{id:e.getAttribute("data-l10n-id"),args:JSON.parse(e.getAttribute("data-l10n-args")||null)}}connectRoot(e){for(const t of this.roots)if(t===e||t.contains(e)||e.contains(t))throw new Error("Cannot add a root that overlaps with existing root.");if(this.windowElement){if(this.windowElement!==e.ownerDocument.defaultView)throw new Error("Cannot connect a root:\\n DOMLocalization already has a root from a different window.")}else this.windowElement=e.ownerDocument.defaultView,this.mutationObserver=new this.windowElement.MutationObserver((e=>this.translateMutations(e)));this.roots.add(e),this.mutationObserver.observe(e,this.observerConfig)}disconnectRoot(e){return this.roots.delete(e),this.pauseObserving(),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(),!0):(this.resumeObserving(),!1)}translateRoots(){const e=Array.from(this.roots);return Promise.all(e.map((e=>this.translateFragment(e))))}pauseObserving(){this.mutationObserver&&(this.translateMutations(this.mutationObserver.takeRecords()),this.mutationObserver.disconnect())}resumeObserving(){if(this.mutationObserver)for(const e of this.roots)this.mutationObserver.observe(e,this.observerConfig)}translateMutations(e){for(const t of e)switch(t.type){case"attributes":t.target.hasAttribute("data-l10n-id")&&this.pendingElements.add(t.target);break;case"childList":for(const e of t.addedNodes)if(e.nodeType===e.ELEMENT_NODE)if(e.childElementCount)for(const t of this.getTranslatables(e))this.pendingElements.add(t);else e.hasAttribute("data-l10n-id")&&this.pendingElements.add(e)}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(e){return this.translateElements(this.getTranslatables(e))}async translateElements(e){if(!e.length)return;const t=e.map(this.getKeysForElement),i=await this.formatMessages(t);return this.applyTranslations(e,i)}applyTranslations(e,t){this.pauseObserving();for(let i=0;i<e.length;i++)void 0!==t[i]&&translateElement(e[i],t[i]);this.resumeObserving()}getTranslatables(e){const t=Array.from(e.querySelectorAll("[data-l10n-id]"));return"function"==typeof e.hasAttribute&&e.hasAttribute("data-l10n-id")&&t.push(e),t}getKeysForElement(e){return{id:e.getAttribute("data-l10n-id"),args:JSON.parse(e.getAttribute("data-l10n-args")||null)}}}class L10n{#u;#g;#p;#m;constructor({lang:e,isRTL:t},i=null){this.#p=L10n.#f(e),this.#m=i,this.#u=t??L10n.#b(this.#p)?"rtl":"ltr"}_setL10n(e){this.#m=e}getLanguage(){return this.#p}getDirection(){return this.#u}async get(e,t=null,i){if(Array.isArray(e)){e=e.map((e=>({id:e})));return(await this.#m.formatMessages(e)).map((e=>e.value))}const n=await this.#m.formatMessages([{id:e,args:t}]);return n[0]?.value||i}async translate(e){(this.#g||=new Set).add(e);try{this.#m.connectRoot(e),await this.#m.translateRoots()}catch{}}async translateOnce(e){try{await this.#m.translateElements([e])}catch(e){console.error("translateOnce:",e)}}async destroy(){if(this.#g){for(const e of this.#g)this.#m.disconnectRoot(e);this.#g.clear(),this.#g=null}this.#m.pauseObserving()}pause(){this.#m.pauseObserving()}resume(){this.#m.resumeObserving()}static#f(e){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"}[e=e?.toLowerCase()||"en-us"]||e}static#b(e){const t=e.split("-",1)[0];return["ar","he","fa","ps","ur"].includes(t)}}const GenericL10n=null;function PLATFORM(){const{isAndroid:e,isLinux:t,isMac:i,isWindows:n}=FeatureTest.platform;return t?"linux":n?"windows":i?"macos":e?"android":"other"}function createBundle(e,t){const i=new FluentResource(t),n=new FluentBundle(e,{functions:{PLATFORM:PLATFORM}}),s=n.addResource(i);return s.length&&console.error("L10n errors",s),n}class genericl10n_GenericL10n extends L10n{constructor(e){super({lang:e});const t=e?genericl10n_GenericL10n.#v.bind(genericl10n_GenericL10n,"en-us",this.getLanguage()):genericl10n_GenericL10n.#w.bind(genericl10n_GenericL10n,this.getLanguage());this._setL10n(new DOMLocalization([],t))}static async*#v(e,t){const{baseURL:i,paths:n}=await this.#E(),s=[t];if(e!==t){const i=t.split("-",1)[0];i!==t&&s.push(i),s.push(e)}const a=s.map((e=>[e,this.#y(e,i,n)]));for(const[e,t]of a){const i=await t;i?yield i:"en-us"===e&&(yield this.#S(e))}}static async#y(e,t,i){const n=i[e];if(!n)return null;const s=new URL(n,t);return createBundle(e,await fetchData(s,"text"))}static async#E(){try{const{href:e}=document.querySelector(\'link[type="application/l10n"]\'),t=await fetchData(e,"json");return{baseURL:e.substring(0,e.lastIndexOf("/")+1)||"./",paths:t}}catch{}return{baseURL:"./",paths:Object.create(null)}}static async*#w(e){yield this.#S(e)}static async#S(e){return createBundle(e,\'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-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-color-picker-free-text-input =\\n .title = Change text color\\npdfjs-editor-free-text-button-label = Text\\npdfjs-editor-ink-button =\\n .title = Draw\\npdfjs-editor-color-picker-ink-input =\\n .title = Change drawing color\\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-comment-floating-button =\\n .title = Comment\\n .aria-label = Comment\\npdfjs-comment-floating-button-label = Comment\\npdfjs-editor-comment-button =\\n .title = Comment\\n .aria-label = Comment\\npdfjs-editor-comment-button-label = Comment\\npdfjs-editor-signature-button =\\n .title = Add signature\\npdfjs-editor-signature-button-label = Add signature\\npdfjs-editor-highlight-editor =\\n .aria-label = Highlight editor\\npdfjs-editor-ink-editor =\\n .aria-label = Drawing editor\\npdfjs-editor-signature-editor1 =\\n .aria-description = Signature editor: { $description }\\npdfjs-editor-stamp-editor =\\n .aria-label = Image editor\\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-remove-signature-button =\\n .title = Remove signature\\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-editor-add-signature-container =\\n .aria-label = Signature controls and saved signatures\\npdfjs-editor-signature-add-signature-button =\\n .title = Add new signature\\npdfjs-editor-signature-add-signature-button-label = Add new signature\\npdfjs-editor-add-saved-signature-button =\\n .title = Saved signature: { $description }\\npdfjs-free-text2 =\\n .aria-label = Text Editor\\n .default-content = Start typing…\\npdfjs-editor-comments-sidebar-title =\\n { $count ->\\n [one] Comment\\n *[other] Comments\\n }\\npdfjs-editor-comments-sidebar-close-button =\\n .title = Close the sidebar\\n .aria-label = Close the sidebar\\npdfjs-editor-comments-sidebar-close-button-label = Close the sidebar\\npdfjs-editor-comments-sidebar-no-comments1 = See something noteworthy? Highlight it and leave a comment.\\npdfjs-editor-comments-sidebar-no-comments-link = Learn more\\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-highlight-added-alert = Highlight added\\npdfjs-editor-freetext-added-alert = Text added\\npdfjs-editor-ink-added-alert = Drawing added\\npdfjs-editor-stamp-added-alert = Image added\\npdfjs-editor-signature-added-alert = Signature added\\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-signature = Signature removed\\npdfjs-editor-undo-bar-message-comment = Comment 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\\npdfjs-editor-add-signature-dialog-label = This modal allows the user to create a signature to add to a PDF document. The user can edit the name (which also serves as the alt text), and optionally save the signature for repeated use.\\npdfjs-editor-add-signature-dialog-title = Add a signature\\npdfjs-editor-add-signature-type-button = Type\\n .title = Type\\npdfjs-editor-add-signature-draw-button = Draw\\n .title = Draw\\npdfjs-editor-add-signature-image-button = Image\\n .title = Image\\npdfjs-editor-add-signature-type-input =\\n .aria-label = Type your signature\\n .placeholder = Type your signature\\npdfjs-editor-add-signature-draw-placeholder = Draw your signature\\npdfjs-editor-add-signature-draw-thickness-range-label = Thickness\\npdfjs-editor-add-signature-draw-thickness-range =\\n .title = Drawing thickness: { $thickness }\\npdfjs-editor-add-signature-image-placeholder = Drag a file here to upload\\npdfjs-editor-add-signature-image-browse-link =\\n { PLATFORM() ->\\n [macos] Or choose image files\\n *[other] Or browse image files\\n }\\npdfjs-editor-add-signature-description-label = Description (alt text)\\npdfjs-editor-add-signature-description-input =\\n .title = Description (alt text)\\npdfjs-editor-add-signature-description-default-when-drawing = Signature\\npdfjs-editor-add-signature-clear-button-label = Clear signature\\npdfjs-editor-add-signature-clear-button =\\n .title = Clear signature\\npdfjs-editor-add-signature-save-checkbox = Save signature\\npdfjs-editor-add-signature-save-warning-message = You’ve reached the limit of 5 saved signatures. Remove one to save more.\\npdfjs-editor-add-signature-image-upload-error-title = Couldn’t upload image\\npdfjs-editor-add-signature-image-upload-error-description = Check your network connection or try another image.\\npdfjs-editor-add-signature-image-no-data-error-title = Can’t convert this image into a signature\\npdfjs-editor-add-signature-image-no-data-error-description = Please try uploading a different image.\\npdfjs-editor-add-signature-error-close-button = Close\\npdfjs-editor-add-signature-cancel-button = Cancel\\npdfjs-editor-add-signature-add-button = Add\\npdfjs-editor-delete-signature-button1 =\\n .title = Remove saved signature\\npdfjs-editor-delete-signature-button-label1 = Remove saved signature\\npdfjs-editor-add-signature-edit-button-label = Edit description\\npdfjs-editor-edit-signature-dialog-title = Edit description\\npdfjs-editor-edit-signature-update-button = Update\\npdfjs-show-comment-button =\\n .title = Show comment\\npdfjs-editor-edit-comment-popup-button-label = Edit comment\\npdfjs-editor-edit-comment-popup-button =\\n .title = Edit comment\\npdfjs-editor-delete-comment-popup-button-label = Remove comment\\npdfjs-editor-delete-comment-popup-button =\\n .title = Remove comment\\npdfjs-editor-edit-comment-dialog-title-when-editing = Edit comment\\npdfjs-editor-edit-comment-dialog-save-button-when-editing = Update\\npdfjs-editor-edit-comment-dialog-title-when-adding = Add comment\\npdfjs-editor-edit-comment-dialog-save-button-when-adding = Add\\npdfjs-editor-edit-comment-dialog-text-input =\\n .placeholder = Start typing…\\npdfjs-editor-edit-comment-dialog-cancel-button = Cancel\\npdfjs-editor-add-comment-button =\\n .title = Add comment\\npdfjs-toggle-views-manager-button =\\n .title = Toggle Sidebar\\npdfjs-toggle-views-manager-notification-button =\\n .title = Toggle Sidebar (document contains thumbnails/outline/attachments/layers)\\npdfjs-toggle-views-manager-button-label = Toggle Sidebar\\npdfjs-views-manager-sidebar =\\n .aria-label = Sidebar\\npdfjs-views-manager-view-selector-button =\\n .title = Views\\npdfjs-views-manager-view-selector-button-label = Views\\npdfjs-views-manager-pages-title = Pages\\npdfjs-views-manager-outlines-title = Document outline\\npdfjs-views-manager-attachments-title = Attachments\\npdfjs-views-manager-layers-title = Layers\\npdfjs-views-manager-pages-option-label = Pages\\npdfjs-views-manager-outlines-option-label = Document outline\\npdfjs-views-manager-attachments-option-label = Attachments\\npdfjs-views-manager-layers-option-label = Layers\\npdfjs-views-manager-add-file-button =\\n .title = Add file\\npdfjs-views-manager-add-file-button-label = Add file\\npdfjs-views-manager-pages-status-action-label =\\n { $count ->\\n [one] { $count } selected\\n *[other] { $count } selected\\n }\\npdfjs-views-manager-pages-status-none-action-label = Select pages\\npdfjs-views-manager-pages-status-action-button-label = Manage\\npdfjs-views-manager-pages-status-copy-button-label = Copy\\npdfjs-views-manager-pages-status-cut-button-label = Cut\\npdfjs-views-manager-pages-status-delete-button-label = Delete\\npdfjs-views-manager-pages-status-save-as-button-label = Save as…\\npdfjs-views-manager-status-undo-cut-label =\\n { $count ->\\n [one] 1 page cut\\n *[other] { $count } pages cut\\n }\\npdfjs-views-manager-pages-status-undo-copy-label =\\n { $count ->\\n [one] 1 page copied\\n *[other] { $count } pages copied\\n }\\npdfjs-views-manager-pages-status-undo-delete-label =\\n { $count ->\\n [one] 1 page deleted\\n *[other] { $count } pages deleted\\n }\\npdfjs-views-manager-pages-status-waiting-ready-label = Getting your file ready…\\npdfjs-views-manager-pages-status-waiting-uploading-label = Uploading file…\\npdfjs-views-manager-status-warning-cut-label = Couldn’t cut. Refresh page and try again.\\npdfjs-views-manager-status-warning-copy-label = Couldn’t copy. Refresh page and try again.\\npdfjs-views-manager-status-warning-delete-label = Couldn’t delete. Refresh page and try again.\\npdfjs-views-manager-status-warning-save-label = Couldn’t save. Refresh page and try again.\\npdfjs-views-manager-status-undo-button-label = Undo\\npdfjs-views-manager-status-close-button =\\n .title = Close\\npdfjs-views-manager-status-close-button-label = Close\')}}async function docProperties(e){const{info:t,metadata:i,contentDispositionFilename:n,contentLength:s}=await e.getMetadata();return{...t,baseURL:"",filesize:s||(await e.getDownloadInfo()).length,filename:n||getPdfFilenameFromUrl(""),metadata:i?.getRaw(),authors:i?.get("dc:creator"),numPages:e.numPages,URL:""}}class GenericScripting{constructor(e){this._ready=new Promise(((t,i)=>{import(e).then((e=>{t(e.QuickJSSandbox())})).catch(i)}))}async createSandbox(e){(await this._ready).create(e)}async dispatchEventInSandbox(e){const t=await this._ready;setTimeout((()=>t.dispatchEvent(e)),0)}async destroySandbox(){(await this._ready).nukeSandbox()}}const KEY_STORAGE="pdfjs.signature";class SignatureStorage{#C;#T=null;#P=null;constructor(e,t){this.#C=e,this.#P=t}#A(){localStorage.setItem(KEY_STORAGE,JSON.stringify(Object.fromEntries(this.#T)))}async getAll(){if(this.#P&&(window.addEventListener("storage",(({key:e})=>{e===KEY_STORAGE&&(this.#T=null,this.#C?.dispatch("storedsignatureschanged",{source:this}))}),{signal:this.#P}),this.#P=null),!this.#T){this.#T=new Map;const e=localStorage.getItem(KEY_STORAGE);if(e)for(const[t,i]of Object.entries(JSON.parse(e)))this.#T.set(t,i)}return this.#T}async isFull(){return 5===await this.size()}async size(){return(await this.getAll()).size}async create(e){if(await this.isFull())return null;const t=getUuid();return this.#T.set(t,e),this.#A(),t}async delete(e){const t=await this.getAll();return!!t.has(e)&&(t.delete(e),this.#A(),!0)}}function initCom(e){}class Preferences extends BasePreferences{async _writeToStorage(e){localStorage.setItem("pdfjs.preferences",JSON.stringify(e))}async _readFromStorage(e){return{prefs:JSON.parse(localStorage.getItem("pdfjs.preferences"))}}}class ExternalServices extends BaseExternalServices{async createL10n(){return new genericl10n_GenericL10n(AppOptions.get("localeProperties")?.lang)}createScripting(){return new GenericScripting(AppOptions.get("sandboxBundleSrc"))}createSignatureStorage(e,t){return new SignatureStorage(e,t)}}class MLManager{async isEnabledFor(e){return!1}async deleteModel(e){return null}isReady(e){return!1}guess(e){}toggleService(e,t){}}class NewAltTextManager{#_=this.#L.bind(this);#I;#x=null;#M;#N;#D;#B;#R;#O;#C;#k=!1;#F;#V=null;#j=null;#U;#H;#z=!1;#W=!1;#K;#$;#G;#X;#Y;#Z;#q=null;constructor({descriptionContainer:e,dialog:t,imagePreview:i,cancelButton:n,disclaimer:s,notNowButton:a,saveButton:o,textarea:r,learnMore:l,errorCloseButton:d,createAutomaticallyButton:h,downloadModel:c,downloadModelDescription:u,title:g},p,m){this.#M=n,this.#I=h,this.#N=e,this.#D=t,this.#B=s,this.#$=a,this.#U=i,this.#X=r,this.#K=l,this.#Y=g,this.#R=c,this.#O=u,this.#G=p,this.#C=m,t.addEventListener("close",this.#Q.bind(this)),t.addEventListener("contextmenu",(e=>{e.target!==this.#X&&e.preventDefault()})),n.addEventListener("click",this.#_),a.addEventListener("click",this.#_),o.addEventListener("click",this.#A.bind(this)),d.addEventListener("click",(()=>{this.#J(!1)})),h.addEventListener("click",(async()=>{const e="true"!==h.getAttribute("aria-pressed");this.#x._reportTelemetry({action:"pdfjs.image.alt_text.ai_generation_check",data:{status:e}}),this.#Z&&(this.#Z.setPreference("enableGuessAltText",e),await this.#Z.mlManager.toggleService("altText",e)),this.#ee(e,!1)})),r.addEventListener("focus",(()=>{this.#W=this.#z,this.#te(!1),this.#ie()})),r.addEventListener("blur",(()=>{r.value||this.#te(this.#W),this.#ie()})),r.addEventListener("input",(()=>{this.#ie()})),r.addEventListener("keydown",(e=>{!e.ctrlKey&&!e.metaKey||"Enter"!==e.key||o.disabled||this.#A()})),m._on("enableguessalttext",(({value:e})=>{this.#ee(e,!1)})),this.#G.register(t),this.#K.addEventListener("click",(()=>{this.#x._reportTelemetry({action:"pdfjs.image.alt_text.info",data:{topic:"alt_text"}})}))}#te(e){this.#Z&&this.#z!==e&&(this.#z=e,this.#N.classList.toggle("loading",e))}#J(e){this.#Z&&this.#D.classList.toggle("error",e)}async#ee(e,t=!1){if(this.#Z)if(this.#D.classList.toggle("aiDisabled",!e),this.#I.setAttribute("aria-pressed",e),e){const{altTextLearnMoreUrl:e}=this.#Z.mlManager;e&&(this.#K.href=e),this.#ne(t)}else this.#te(!1),this.#z=!1,this.#ie()}#se(){this.#$.classList.toggle("hidden",!this.#k),this.#M.classList.toggle("hidden",this.#k)}#ae(e){this.#Z&&this.#V!==e&&(this.#V=e,this.#D.classList.toggle("noAi",!e),this.#ie())}#ie(){const e=this.#z||this.#F&&this.#F===this.#X.value;this.#B.hidden=!e;const t=this.#z||!!this.#X.value;this.#j!==t&&(this.#j=t,this.#Y.setAttribute("data-l10n-id",t?"pdfjs-editor-new-alt-text-dialog-edit-label":"pdfjs-editor-new-alt-text-dialog-add-label"))}async#ne(e){if(this.#z)return;if(this.#X.value)return;if(e&&null!==this.#q)return;if(this.#F=this.#x.guessedAltText,null===this.#q&&this.#F)return void this.#oe(this.#F);this.#te(!0),this.#ie();let t=!1;try{const e=await this.#x.mlGuessAltText(this.#H,!1);e&&(this.#F=e,this.#W=this.#z,this.#z&&this.#oe(e))}catch(e){console.error(e),t=!0}this.#te(!1),this.#ie(),t&&this.#Z&&this.#J(!0)}#oe(e){this.#Z&&!this.#X.value&&(this.#X.value=e,this.#ie())}#re(){this.#R.classList.toggle("hidden",!1);const e=async({detail:{finished:t,total:i,totalLoaded:n}})=>{const s=1e6;n=Math.min(.99*i,n);const a=this.#O.ariaValueMax=Math.round(i/s),o=this.#O.ariaValueNow=Math.round(n/s);if(this.#O.setAttribute("data-l10n-args",JSON.stringify({totalSize:a,downloadedSize:o})),!t)return;if(this.#C._off("loadaiengineprogress",e),this.#R.classList.toggle("hidden",!0),this.#ae(!0),!this.#Z)return;const{mlManager:r}=this.#Z;r.toggleService("altText",!0),this.#ee(await r.isEnabledFor("altText"),!0)};this.#C._on("loadaiengineprogress",e)}async editAltText(e,t,i){if(this.#x||!t)return;if(i&&t.hasAltTextData())return void t.altTextFinish();this.#k=i;let{mlManager:n}=e,s=!!n;this.#ie(),n&&!n.isReady("altText")?(s=!1,n.hasProgress?this.#re():n=null):this.#R.classList.toggle("hidden",!0);const a=n?.isEnabledFor("altText");this.#x=t,this.#Z=e,this.#Z.removeEditListeners(),({altText:this.#q}=t.altTextData),this.#X.value=this.#q??"";let o,r,l;n?(({canvas:o,width:r,height:l,imageData:this.#H}=t.copyCanvas(224,180,!0)),s&&this.#ee(await a,!0)):({canvas:o,width:r,height:l}=t.copyCanvas(224,180,!1)),o.setAttribute("role","presentation");const{style:d}=o;d.width=`${r}px`,d.height=`${l}px`,this.#U.append(o),this.#se(),this.#ae(s),this.#J(!1);try{await this.#G.open(this.#D)}catch(e){throw this.#Q(),e}}#L(){this.#x.altTextData={cancel:!0};const e=this.#X.value.trim();this.#x._reportTelemetry({action:"pdfjs.image.alt_text.dismiss",data:{alt_text_type:e?"present":"empty",flow:this.#k?"image_add":"alt_text_edit"}}),this.#x._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!0,alt_text_type:"skipped"}}),this.#le()}#le(){this.#G.closeIfActive(this.#D)}#Q(){const e=this.#U.firstElementChild;e.remove(),e.width=e.height=0,this.#H=null,this.#te(!1),this.#Z?.addEditListeners(),this.#x.altTextFinish(),this.#Z?.setSelected(this.#x),this.#x=null,this.#Z=null}#de(e){return new Set(e.toLowerCase().split(/[^\\p{L}\\p{N}]+/gu).filter((e=>!!e)))}#A(){const e=this.#X.value.trim();if(this.#x.altTextData={altText:e,decorative:!1},this.#x.altTextData.guessedAltText=this.#F,this.#F&&this.#F!==e){const t=this.#de(this.#F),i=this.#de(e);this.#x._reportTelemetry({action:"pdfjs.image.alt_text.user_edit",data:{total_words:t.size,words_removed:t.difference(i).size,words_added:i.difference(t).size}})}this.#x._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!0,alt_text_type:e?"present":"empty"}}),this.#x._reportTelemetry({action:"pdfjs.image.alt_text.save",data:{alt_text_type:e?"present":"empty",flow:this.#k?"image_add":"alt_text_edit"}}),this.#le()}destroy(){this.#Z=null,this.#le()}}class ImageAltTextSettings{#he;#ce;#ue;#D;#C;#ge;#G;#pe;constructor({dialog:e,createModelButton:t,aiModelSettings:i,learnMore:n,closeButton:s,deleteModelButton:a,downloadModelButton:o,showAltTextDialogButton:r},l,d,h){this.#D=e,this.#he=i,this.#ce=t,this.#ue=o,this.#pe=r,this.#G=l,this.#C=d,this.#ge=h;const{altTextLearnMoreUrl:c}=h;c&&(n.href=c),e.addEventListener("contextmenu",noContextMenu),t.addEventListener("click",(async e=>{const t=this.#me("enableGuessAltText",e);await h.toggleService("altText",t),this.#fe({type:"stamp",action:"pdfjs.image.alt_text.settings_ai_generation_check",data:{status:t}})})),r.addEventListener("click",(e=>{const t=this.#me("enableNewAltTextWhenAddingImage",e);this.#fe({type:"stamp",action:"pdfjs.image.alt_text.settings_edit_alt_text_check",data:{status:t}})})),a.addEventListener("click",this.#be.bind(this,!0)),o.addEventListener("click",this.#ve.bind(this,!0)),s.addEventListener("click",this.#le.bind(this)),n.addEventListener("click",(()=>{this.#fe({type:"stamp",action:"pdfjs.image.alt_text.info",data:{topic:"ai_generation"}})})),d._on("enablealttextmodeldownload",(({value:e})=>{e?this.#ve(!1):this.#be(!1)})),this.#G.register(e)}#fe(e){this.#C.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}async#ve(e=!1){if(e){this.#ue.disabled=!0;const e=this.#ue.firstElementChild;e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-settings-downloading-model-button"),await this.#ge.downloadModel("altText"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-settings-download-model-button"),this.#ce.disabled=!1,this.#we("enableGuessAltText",!0),this.#ge.toggleService("altText",!0),this.#we("enableAltTextModelDownload",!0),this.#ue.disabled=!1}this.#he.classList.toggle("download",!1),this.#ce.setAttribute("aria-pressed",!0)}async#be(e=!1){e&&(await this.#ge.deleteModel("altText"),this.#we("enableGuessAltText",!1),this.#we("enableAltTextModelDownload",!1)),this.#he.classList.toggle("download",!0),this.#ce.disabled=!0,this.#ce.setAttribute("aria-pressed",!1)}async open({enableGuessAltText:e,enableNewAltTextWhenAddingImage:t}){const{enableAltTextModelDownload:i}=this.#ge;this.#ce.disabled=!i,this.#ce.setAttribute("aria-pressed",i&&e),this.#pe.setAttribute("aria-pressed",t),this.#he.classList.toggle("download",!i),await this.#G.open(this.#D),this.#fe({type:"stamp",action:"pdfjs.image.alt_text.settings_displayed"})}#me(e,{target:t}){const i="true"!==t.getAttribute("aria-pressed");return this.#we(e,i),t.setAttribute("aria-pressed",i),i}#we(e,t){this.#C.dispatch("setpreference",{source:this,name:e,value:t})}#le(){this.#G.closeIfActive(this.#D)}}class AltTextManager{#Ee=null;#x=null;#M;#D;#C;#ye=!1;#Se;#Ce;#G;#Te;#X;#Z;#q=null;#Pe=null;#Ae=null;#_e=null;#Le;#Ie=null;constructor({dialog:e,optionDescription:t,optionDecorative:i,textarea:n,cancelButton:s,saveButton:a},o,r,l){this.#D=e,this.#Se=t,this.#Ce=i,this.#X=n,this.#M=s,this.#Te=a,this.#G=r,this.#C=l,this.#Le=o;const d=this.#xe.bind(this);e.addEventListener("close",this.#Q.bind(this)),e.addEventListener("contextmenu",(e=>{e.target!==this.#X&&e.preventDefault()})),s.addEventListener("click",this.#le.bind(this)),a.addEventListener("click",this.#A.bind(this)),t.addEventListener("change",d),i.addEventListener("change",d),n.addEventListener("keydown",(e=>{!e.ctrlKey&&!e.metaKey||"Enter"!==e.key||a.disabled||this.#A()})),this.#G.register(e)}#Me(){if(this.#Ae)return;const e=new DOMSVGFactory,t=this.#Ae=e.createElement("svg");t.setAttribute("width","0"),t.setAttribute("height","0");const i=e.createElement("defs");t.append(i);const n=e.createElement("mask");i.append(n),n.setAttribute("id","alttext-manager-mask"),n.setAttribute("maskContentUnits","objectBoundingBox");let s=e.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.#_e=e.createElement("rect"),n.append(s),s.setAttribute("fill","black"),this.#D.append(t)}async editAltText(e,t){if(this.#x||!t)return;this.#Me(),this.#ye=!1,this.#Ee=new AbortController;const i={signal:this.#Ee.signal},n=this.#Ne.bind(this);for(const e of[this.#Se,this.#Ce,this.#X,this.#Te,this.#M])e.addEventListener("click",n,i);const{altText:s,decorative:a}=t.altTextData;!0===a?(this.#Ce.checked=!0,this.#Se.checked=!1):(this.#Ce.checked=!1,this.#Se.checked=!0),this.#q=this.#X.value=s?.trim()||"",this.#xe(),this.#x=t,this.#Z=e,this.#Z.removeEditListeners(),this.#Pe=new AbortController,this.#C._on("resize",this.#De.bind(this),{signal:this.#Pe.signal});try{await this.#G.open(this.#D),this.#De()}catch(e){throw this.#Q(),e}}#De(){if(!this.#x)return;const e=this.#D,{style:t}=e,{x:i,y:n,width:s,height:a}=this.#Le.getBoundingClientRect(),{innerWidth:o,innerHeight:r}=window,{width:l,height:d}=e.getBoundingClientRect(),{x:h,y:c,width:u,height:g}=this.#x.getClientDimensions(),p=10,m="ltr"===this.#Z.direction,f=Math.max(h,i),b=Math.min(h+u,i+s),v=Math.max(c,n),w=Math.min(c+g,n+a);this.#_e.setAttribute("width",""+(b-f)/o),this.#_e.setAttribute("height",""+(w-v)/r),this.#_e.setAttribute("x",""+f/o),this.#_e.setAttribute("y",""+v/r);let E=null,y=Math.max(c,0);y+=Math.min(r-(y+d),0),m?h+u+p+l<o?E=h+u+p:h>l+p&&(E=h-l-p):h>l+p?E=h-l-p:h+u+p+l<o&&(E=h+u+p),null===E&&(y=null,E=Math.max(h,0),E+=Math.min(o-(E+l),0),c>d+p?y=c-d-p:c+g+p+d<r&&(y=c+g+p)),null!==y?(e.classList.add("positioned"),m?t.left=`${E}px`:t.right=o-E-l+"px",t.top=`${y}px`):(e.classList.remove("positioned"),t.left="",t.top="")}#le(){this.#G.closeIfActive(this.#D)}#Q(){this.#x._reportTelemetry(this.#Ie||{action:"alt_text_cancel",alt_text_keyboard:!this.#ye}),this.#Ie=null,this.#Be(),this.#Z?.addEditListeners(),this.#Pe?.abort(),this.#Pe=null,this.#x.altTextFinish(),this.#x=null,this.#Z=null}#xe(){this.#X.disabled=this.#Ce.checked}#A(){const e=this.#X.value.trim(),t=this.#Ce.checked;this.#x.altTextData={altText:e,decorative:t},this.#Ie={action:"alt_text_save",alt_text_description:!!e,alt_text_edit:!!this.#q&&this.#q!==e,alt_text_decorative:t,alt_text_keyboard:!this.#ye},this.#le()}#Ne(e){0!==e.detail&&(this.#ye=!0,this.#Be())}#Be(){this.#Ee?.abort(),this.#Ee=null}destroy(){this.#Z=null,this.#le(),this.#Ae?.remove(),this.#Ae=this.#_e=null}}class AnnotationEditorParams{constructor(e,t){this.eventBus=t,this.#Re(e)}#Re({editorFreeTextFontSize:e,editorFreeTextColor:t,editorInkColor:i,editorInkThickness:n,editorInkOpacity:s,editorStampAddImage:a,editorFreeHighlightThickness:o,editorHighlightShowAll:r,editorSignatureAddSignature:l}){const{eventBus:d}=this,h=(e,t)=>{d.dispatch("switchannotationeditorparams",{source:this,type:AnnotationEditorParamsType[e],value:t})};e.addEventListener("input",(function(){h("FREETEXT_SIZE",this.valueAsNumber)})),t.addEventListener("input",(function(){h("FREETEXT_COLOR",this.value)})),i.addEventListener("input",(function(){h("INK_COLOR",this.value)})),n.addEventListener("input",(function(){h("INK_THICKNESS",this.valueAsNumber)})),s.addEventListener("input",(function(){h("INK_OPACITY",this.valueAsNumber)})),a.addEventListener("click",(()=>{d.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{action:"pdfjs.image.add_image_click"}}}),h("CREATE")})),o.addEventListener("input",(function(){h("HIGHLIGHT_THICKNESS",this.valueAsNumber)})),r.addEventListener("click",(function(){const e="true"===this.getAttribute("aria-pressed");this.setAttribute("aria-pressed",!e),h("HIGHLIGHT_SHOW_ALL",!e)})),l.addEventListener("click",(()=>{h("CREATE")})),d._on("annotationeditorparamschanged",(a=>{for(const[l,h]of a.details)switch(l){case AnnotationEditorParamsType.FREETEXT_SIZE:e.value=h;break;case AnnotationEditorParamsType.FREETEXT_COLOR:t.value=h;break;case AnnotationEditorParamsType.INK_COLOR:i.value=h;break;case AnnotationEditorParamsType.INK_THICKNESS:n.value=h;break;case AnnotationEditorParamsType.INK_OPACITY:s.value=h;break;case AnnotationEditorParamsType.HIGHLIGHT_COLOR:d.dispatch("mainhighlightcolorpickerupdatecolor",{source:this,value:h});break;case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:o.value=h;break;case AnnotationEditorParamsType.HIGHLIGHT_FREE:o.disabled=!h;break;case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:r.setAttribute("aria-pressed",h)}}))}}const PRECISION=.1;class CaretBrowsingMode{#Oe;#ke=0;#Fe;constructor(e,t,i,n){if(this.#Oe=t,this.#Fe=i,!n)return;this.#ke=n.getBoundingClientRect().height;const s=new ResizeObserver((e=>{for(const t of e)if(t.target===n){this.#ke=Math.floor(t.borderBoxSize[0].blockSize);break}}));s.observe(n),e.addEventListener("abort",(()=>s.disconnect()),{once:!0})}#Ve(e,t){const i=e.y,n=e.bottom,s=e.y+e.height/2,a=t.y,o=t.bottom,r=t.y+t.height/2;return i<=r&&r<=n||a<=s&&s<=o}#je(e,t,i,n){const s=e.y+e.height/2;return(n?i>=s:i<=s)&&e.x-.1<=t&&t<=e.right+.1}#Ue(e){return e.top>=this.#ke&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}#He(e,t){const{focusNode:i,focusOffset:n}=e,s=document.createRange();s.setStart(i,n),s.setEnd(i,n);const a=s.getBoundingClientRect();return[a.x,t?a.top:a.bottom]}static#ze(e,t){if(!document.caretPositionFromPoint){const{startContainer:i,startOffset:n}=document.caretRangeFromPoint(e,t);return{offsetNode:i,offset:n}}return document.caretPositionFromPoint(e,t)}#We(e,t,i,n,s){if(s||=n.getBoundingClientRect(),t<=s.x+.1)return void(i?e.extend(n.firstChild,0):e.setPosition(n.firstChild,0));if(s.right-.1<=t){const{lastChild:t}=n;return void(i?e.extend(t,t.length):e.setPosition(t,t.length))}const a=s.y+s.height/2;let o=CaretBrowsingMode.#ze(t,a),r=o.offsetNode?.parentElement;if(r&&r!==n){const e=document.elementsFromPoint(t,a),i=[];for(const t of e){if(t===n)break;const{style:e}=t;i.push([t,e.visibility]),e.visibility="hidden"}o=CaretBrowsingMode.#ze(t,a),r=o.offsetNode?.parentElement;for(const[e,t]of i)e.style.visibility=t}r===n?i?e.extend(o.offsetNode,o.offset):e.setPosition(o.offsetNode,o.offset):i?e.extend(n.firstChild,0):e.setPosition(n.firstChild,0)}#Ke(e,t,i,n,s){this.#Ue(n)?this.#We(t,s,e,i,n):(this.#Oe.addEventListener("scrollend",this.#We.bind(this,t,s,e,i,null),{once:!0}),i.scrollIntoView())}#$e(e,t){for(;;){const i=e.closest(".page"),n=parseInt(i.getAttribute("data-page-number")),s=t?n-1:n+1;if(!(e=this.#Fe.querySelector(`.page[data-page-number="${s}"] .textLayer`)))return null;const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),o=t?a.lastChild():a.firstChild();if(o)return o}}moveCaret(e,t){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 o=document.createTreeWalker(a,NodeFilter.SHOW_TEXT);o.currentNode=n;const r=s.getBoundingClientRect();let l=null;const d=(e?o.previousSibling:o.nextSibling).bind(o);for(;d();){const e=o.currentNode.parentElement;if(!this.#Ve(r,e.getBoundingClientRect())){l=e;break}}if(!l){const s=this.#$e(a,e);if(!s)return;if(t){const t=(e?o.firstChild():o.lastChild())||n;i.extend(t,e?0:t.length);const a=document.createRange();return a.setStart(s,e?s.length:0),a.setEnd(s,e?s.length:0),void i.addRange(a)}const[r]=this.#He(i,e),{parentElement:l}=s;return void this.#Ke(t,i,l,l.getBoundingClientRect(),r)}const[h,c]=this.#He(i,e),u=l.getBoundingClientRect();if(this.#je(u,h,c,e))this.#Ke(t,i,l,u,h);else{for(;d();){const n=o.currentNode.parentElement,s=n.getBoundingClientRect();if(!this.#Ve(u,s))break;if(this.#je(s,h,c,e))return void this.#Ke(t,i,n,s,h)}this.#Ke(t,i,l,u,h)}}}const RESIZE_TIMEOUT=400;class Sidebar{#Ge=0;#Xe=0;#Ye;#Ze=null;#qe;#Qe;#Je=!1;#et;#tt=0;constructor({sidebar:e,resizer:t,toggleButton:i},n,s){this._sidebar=e,this.#Ye=n===s?-1:1,this.#qe=t,this.#Qe=s;const a=window.getComputedStyle(e);this.#Ge=this.#Xe=parseFloat(a.getPropertyValue("--sidebar-width")),t.ariaValueMin=parseFloat(a.getPropertyValue("--sidebar-min-width"))||0,t.ariaValueMax=parseFloat(a.getPropertyValue("--sidebar-max-width"))||1/0,t.ariaValueNow=this.#Xe,this.#it(),i.addEventListener("click",this.toggle.bind(this)),this._isOpen=!1,e.hidden=!0,this.#et=new ResizeObserver((([{borderBoxSize:[{inlineSize:e}]}])=>{isNaN(this.#tt)||(this.#tt+=this.#Ye*(e-this.#Xe)),this.#nt(e)})),this.#et.observe(e)}#it(){const e=this._sidebar.style;let t;const i=()=>{this.#Ze=null,this._sidebar.classList.remove("resizing"),t?.abort(),t=null,this.#Je=!1,this.onStopResizing(),this.#tt=NaN};this.#qe.addEventListener("pointerdown",(n=>{if(t)return void i();this.onStartResizing();const{clientX:s}=n;stopEvent(n),this.#tt=s,t=new AbortController;const{signal:a}=t,o=this._sidebar;o.classList.add("resizing");o.parentElement.style.minWidth=0,window.addEventListener("contextmenu",noContextMenu,{signal:a}),window.addEventListener("pointermove",(i=>{!t||Math.abs(i.clientX-this.#tt)<1||(stopEvent(i),e.width=`${Math.round(this.#Xe+this.#Ye*(i.clientX-this.#tt))}px`)}),{signal:a,capture:!0}),window.addEventListener("blur",i,{signal:a}),window.addEventListener("pointerup",(e=>{t&&(i(),stopEvent(e))}),{signal:a})})),this.#qe.addEventListener("keydown",(t=>{const{key:n}=t,s="ArrowLeft"===n;if(s||"ArrowRight"===n){this.#Je||(this._sidebar.classList.add("resizing"),this.#Je=!0,this.onStartResizing());const n=(t.ctrlKey||t.metaKey?10:1)*(s?-1:1);clearTimeout(this.#Ze),this.#Ze=setTimeout(i,400),e.width=`${Math.round(this.#Xe+this.#Ye*n)}px`,stopEvent(t)}}))}#nt(e){this.#Xe=e,this.#qe.ariaValueNow=Math.round(e),this.#Qe&&(this._sidebar.parentElement.style.insetInlineStart=`${(this.#Ge-e).toFixed(3)}px`),this.onResizing(e)}get width(){return this.#Xe}set width(e){this._sidebar.style.width=`${e}px`}onStartResizing(){}onStopResizing(){}onResizing(e){}toggle(e=!this._isOpen){this._sidebar.hidden=!(this._isOpen=e)}destroy(){this.#et?.disconnect(),this.#et=null}}class CommentManager{#D;#st;#at;static#ot=null;constructor(e,t,i,n,s,a,o){const r=new Intl.DateTimeFormat(void 0,{dateStyle:"long"});this.dialogElement=e.dialog,this.#D=new CommentDialog(e,s,i,a),this.#st=new CommentPopup(i,r,a,this.dialogElement),this.#at=new CommentSidebar(t,i,n,this.#st,r,a),this.#st.sidebar=this.#at,CommentManager.#ot=o}setSidebarUiManager(e){this.#at.setUIManager(e)}showSidebar(e){this.#at.show(e)}hideSidebar(){this.#at.hide()}removeComments(e){this.#at.removeComments(e)}selectComment(e){this.#at.selectComment(null,e)}addComment(e){this.#at.addComment(e)}updateComment(e){this.#at.updateComment(e)}toggleCommentPopup(e,t,i,n){t&&this.selectComment(e.uid),this.#st.toggle(e,t,i,n)}destroyPopup(){this.#st.destroy()}updatePopupColor(e){this.#st.updateColor(e)}showDialog(e,t,i,n,s){return this.#D.open(e,t,i,n,s)}makeCommentColor(e,t){return CommentManager._makeCommentColor(e,t)}static _makeCommentColor(e,t){return this.#ot?null:findContrastColor(applyOpacity(...e,t??1),CSSConstants.commentForegroundColor)}destroy(){this.#D.destroy(),this.#at.hide(),this.#st.destroy()}}class CommentSidebar extends Sidebar{#rt=null;#C;#lt=this.#dt.bind(this);#ht=this.#ct.bind(this);#ut;#gt;#pt;#mt;#ft;#bt;#vt;#st;#wt=null;#Et=null;#Z=null;constructor({learnMoreUrl:e,sidebar:t,sidebarResizer:i,commentsList:n,commentCount:s,sidebarTitle:a,closeButton:o,commentToolbarButton:r},l,d,h,c,u){super({sidebar:t,resizer:i,toggleButton:r},u,!0),this.#ft=a,this.#gt=n,this.#pt=s,this.#bt=e,this.#vt=d,this.#ut=o,this.#st=h,this.#mt=c,this.#C=l,o.addEventListener("click",(()=>{l.dispatch("switchannotationeditormode",{source:this,mode:AnnotationEditorType.NONE})}));const g=e=>{"ArrowDown"===e.key||"Home"===e.key||"F6"===e.key?(this.#gt.firstElementChild.focus(),stopEvent(e)):"ArrowUp"!==e.key&&"End"!==e.key||(this.#gt.lastElementChild.focus(),stopEvent(e))};r.addEventListener("keydown",g),t.addEventListener("keydown",g)}setUIManager(e){this.#Z=e}show(e){if(this.#wt=new WeakMap,this.#Et=new Map,this.#rt=e,e.sort(this.#yt.bind(this)),0!==e.length){const t=document.createDocumentFragment();for(const i of e)t.append(this.#St(i));this.#Ct(t),this.#gt.append(t)}else this.#Ct();this._sidebar.hidden=!1,this.#C.dispatch("reporttelemetry",{source:this,details:{type:"commentSidebar",data:{numberOfAnnotations:e.length}}})}hide(){this._sidebar.hidden=!0,this.#gt.replaceChildren(),this.#wt=null,this.#Et=null,this.#rt=null}removeComments(e){if(0!==e.length&&this.#Et)if(0!==new Set(this.#Et.keys()).difference(new Set(e)).size)for(const t of e)this.#Tt(t);else this.#Pt()}focusComment(e){const t=this.#Et.get(e);if(t){this._sidebar.scrollTop=t.offsetTop-this._sidebar.offsetTop;for(const e of this.#gt.children)e.classList.toggle("selected",e===t)}}updateComment(e){if(!this.#Et)return;const{id:t,creationDate:i,modificationDate:n,richText:s,contentsObj:a,popupRef:o}=e;o&&(s||a?.str)||this.#Tt(t);const r=this.#Et.get(t);if(!r)return;const l=this.#wt.get(r);let d=binarySearchFirstItem(this.#rt,(e=>this.#yt(e,l)>=0));d>=this.#rt.length||(this.#At(r.firstElementChild,n||i),this.#_t(r.lastElementChild,s,a),this.#rt.splice(d,1),d=binarySearchFirstItem(this.#rt,(t=>this.#yt(t,e)>=0)),this.#rt.splice(d,0,e),d>=this.#gt.children.length?this.#gt.append(r):this.#gt.insertBefore(r,this.#gt.children[d]))}#Tt(e){const t=this.#Et?.get(e);if(!t)return;const i=this.#wt.get(t),n=binarySearchFirstItem(this.#rt,(e=>this.#yt(e,i)>=0));n>=this.#rt.length||(this.#rt.splice(n,1),t.remove(),this.#Et.delete(e),this.#Ct())}#Pt(){this.#gt.replaceChildren(),this.#wt=new WeakMap,this.#Et.clear(),this.#rt.length=0,this.#Ct()}selectComment(e,t=null){if(!this.#Et)return;const i=!e;e||=this.#Et.get(t);for(const t of this.#gt.children)t.classList.toggle("selected",t===e);i&&e?.scrollIntoView({behavior:"instant",block:"center"})}addComment(e){if(this.#Et?.has(e.id))return;const{popupRef:t,contentsObj:i}=e;if(!t||!i?.str)return;const n=this.#St(e);if(0===this.#rt.length)return this.#gt.replaceChildren(n),this.#rt.push(e),void this.#Ct();const s=binarySearchFirstItem(this.#rt,(t=>this.#yt(t,e)>=0));this.#rt.splice(s,0,e),s>=this.#gt.children.length?this.#gt.append(n):this.#gt.insertBefore(n,this.#gt.children[s]),this.#Ct()}#Ct(e=this.#gt){const t=this.#Et.size;this.#ft.setAttribute("data-l10n-args",JSON.stringify({count:t})),this.#pt.textContent=t,0===t&&e.append(this.#Lt())}#Lt(){const e=document.createElement("li");e.classList.add("sidebarComment","noComments");const t=document.createElement("div");if(t.className="sidebarCommentText",t.setAttribute("data-l10n-id","pdfjs-editor-comments-sidebar-no-comments1"),e.append(t),this.#bt){const t=document.createElement("a");t.setAttribute("data-l10n-id","pdfjs-editor-comments-sidebar-no-comments-link"),t.href=this.#bt,t.target="_blank",t.rel="noopener noreferrer",e.append(t)}return e}#At(e,t){t=PDFDateString.toDateObject(t),e.dateTime=t.toISOString(),e.textContent=this.#mt.format(t)}#_t(e,t,i){e.replaceChildren();const n=!t?.str||i?.str&&t.str!==i.str?i?.str:t.html;renderRichText({html:n,dir:i?.dir||"auto",className:"richText"},e)}#St(e){const{id:t,creationDate:i,modificationDate:n,richText:s,contentsObj:a,color:o,opacity:r}=e,l=document.createElement("li");l.role="button",l.className="sidebarComment",l.tabIndex=-1,l.style.backgroundColor=o&&CommentManager._makeCommentColor(o,r)||"";const d=document.createElement("time");this.#At(d,n||i);const h=document.createElement("div");return h.className="sidebarCommentText",this.#_t(h,s,a),l.append(d,h),l.addEventListener("click",this.#lt),l.addEventListener("keydown",this.#ht),this.#wt.set(l,e),this.#Et.set(t,l),l}async#dt({currentTarget:e}){if(e.classList.contains("selected"))return e.classList.remove("selected"),void this.#st._hide();const t=this.#wt.get(e);if(!t)return;this.#st._hide();const{id:i,pageIndex:n,rect:s}=t,a=n+1,o=this.#Z?.waitForEditorsRendered(a);this.#vt?.goToXY(a,s[0],s[3],{center:"both"}),this.selectComment(e),await o,this.#Z?.selectComment(n,i)}#ct(e){const{key:t,currentTarget:i}=e;switch(t){case"ArrowDown":(i.nextElementSibling||this.#gt.firstElementChild).focus(),stopEvent(e);break;case"ArrowUp":(i.previousElementSibling||this.#gt.lastElementChild).focus(),stopEvent(e);break;case"Home":this.#gt.firstElementChild.focus(),stopEvent(e);break;case"End":this.#gt.lastElementChild.focus(),stopEvent(e);break;case"Enter":case" ":this.#dt(e),stopEvent(e);break;case"ShiftTab":this.#ut.focus(),stopEvent(e)}}#yt(e,t){const i=PDFDateString.toDateObject(e.modificationDate||e.creationDate),n=PDFDateString.toDateObject(t.modificationDate||t.creationDate);return i!==n?null!==i&&null!==n?n-i:null!==i?-1:1:e.pageIndex!==t.pageIndex?e.pageIndex-t.pageIndex:e.rect[3]!==t.rect[3]?t.rect[3]-e.rect[3]:e.rect[0]!==t.rect[0]?e.rect[0]-t.rect[0]:e.rect[1]!==t.rect[1]?t.rect[1]-e.rect[1]:e.rect[2]!==t.rect[2]?e.rect[2]-t.rect[2]:e.id.localeCompare(t.id)}}class CommentDialog{#D;#It;#G;#xt="";#Mt="";#Nt;#Y;#Te;#Z;#Dt=0;#Bt=0;#Rt=0;#Ot=0;#kt;#C;constructor({dialog:e,toolbar:t,title:i,textInput:n,cancelButton:s,saveButton:a},o,r,l){this.#D=e,this.#Nt=n,this.#G=o,this.#C=r,this.#Te=a,this.#Y=i,this.#kt=l;const d=this.#le.bind(this);let h;e.addEventListener("close",d),e.addEventListener("contextmenu",(e=>{e.target!==this.#Nt&&e.preventDefault()})),s.addEventListener("click",d),a.addEventListener("click",this.#A.bind(this)),n.addEventListener("input",(()=>{a.disabled=n.value===this.#xt})),n.addEventListener("keydown",(e=>{!e.ctrlKey&&!e.metaKey||"Enter"!==e.key||a.disabled||this.#A()}));const c=()=>{e.classList.remove("dragging"),h?.abort(),h=null};t.addEventListener("pointerdown",(t=>{if(h)return void c();const{clientX:i,clientY:n}=t;stopEvent(t),this.#Dt=i,this.#Bt=n,h=new AbortController;const{signal:s}=h,{innerHeight:a,innerWidth:o}=window;e.classList.add("dragging"),window.addEventListener("pointermove",(e=>{if(!h)return;const{clientX:t,clientY:i}=e;this.#De(this.#Rt+(t-this.#Dt)/o,this.#Ot+(i-this.#Bt)/a),this.#Dt=t,this.#Bt=i,stopEvent(e)}),{signal:s}),window.addEventListener("blur",c,{signal:s}),window.addEventListener("pointerup",(e=>{h&&(c(),stopEvent(e))}),{signal:s})})),o.register(e)}async open(e,t,i,n,s){t&&(this.#Z=e,this.#It=t);const{contentsObj:{str:a},color:o,opacity:r}=t.getData(),{style:l}=this.#D;o?(l.backgroundColor=CommentManager._makeCommentColor(o,r),l.borderColor=Util.makeHexColor(...o)):l.backgroundColor=l.borderColor="",this.#Mt=a||"";const d=this.#Nt;d.value=this.#xt=this.#Mt,a?(this.#Y.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-dialog-title-when-editing"),this.#Te.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-dialog-save-button-when-editing")):(this.#Y.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-dialog-title-when-adding"),this.#Te.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-dialog-save-button-when-adding")),s?.height&&(d.style.height=`${s.height}px`),this.#Z?.removeEditListeners(),this.#Te.disabled=!0;const h=s?.parentDimensions,{innerHeight:c,innerWidth:u}=window;if(t.hasDefaultPopupPosition()){const{dialogWidth:e,dialogHeight:t}=this._dialogDimensions;if(h)if(this.#kt&&i+e>Math.min(h.x+h.width,u)){i-=e-this.#It.commentButtonWidth*h.width}else if(!this.#kt){const t=this.#It.commentButtonWidth*h.width;i-e<Math.max(0,h.x)?i=Math.max(0,i):i-=e-t}const a=Math.max(t,s?.height||0);n+a>c&&(n=c-a),n<0&&(n=0)}i=MathClamp(i/u,0,1),n=MathClamp(n/c,0,1),this.#De(i,n),await this.#G.open(this.#D),d.focus()}async#A(){this.#It.comment=this.#Nt.value,this.#le()}get _dialogDimensions(){const e=this.#D,{style:t}=e;t.opacity="0",t.display="block";const{width:i,height:n}=e.getBoundingClientRect();return t.opacity=t.display="",shadow(this,"_dialogDimensions",{dialogWidth:i,dialogHeight:n})}#De(e,t){this.#Rt=e,this.#Ot=t;const{style:i}=this.#D;i.left=100*e+"%",i.top=100*t+"%"}#le(){if(!this.#It)return;const e=this.#Nt.value!==this.#Mt;this.#C.dispatch("reporttelemetry",{source:this,details:{type:"comment",data:{edited:e}}}),this.#It?.focusCommentButton(),this.#It=null,this.#Nt.value=this.#xt=this.#Mt="",this.#G.closeIfActive(this.#D),this.#Nt.style.height="",this.#Z?.addEditListeners(),this.#Z=null}destroy(){this.#Z=null,this.#It=null,this.#le()}}class CommentPopup{#Ft=null;#C;#Vt;#mt;#It=null;#kt;#Le=null;#jt=null;#Ut=null;#Dt=0;#Bt=0;#Ht=0;#zt=0;#Wt=null;#Kt=!1;#s=!1;constructor(e,t,i,n){this.#C=e,this.#mt=t,this.#kt=i,this.#Vt=n,this.sidebar=null}get _popupWidth(){const e=this.#$t(),{style:t}=e;t.opacity="0",t.display="block",document.body.append(e);const i=e.getBoundingClientRect().width;return e.remove(),t.opacity=t.display="",shadow(this,"_popupWidth",i)}#$t(){if(this.#Le)return this.#Le;const e=this.#Le=document.createElement("div");e.className="commentPopup",e.id="commentPopup",e.tabIndex=-1,e.role="dialog",e.ariaModal="false",e.addEventListener("contextmenu",noContextMenu),e.addEventListener("keydown",(e=>{"Escape"===e.key&&(this.toggle(this.#It,!0,!1),this.#Wt?.focus(),stopEvent(e))})),e.addEventListener("click",(()=>{e.focus()}));const t=document.createElement("div");t.className="commentPopupTop";const i=this.#Ut=document.createElement("time");i.className="commentPopupTime";const n=this.#Ft=document.createElement("div");n.className="commentPopupButtons";const s=document.createElement("button");s.classList.add("commentPopupEdit","toolbarButton"),s.tabIndex=0,s.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-popup-button"),s.ariaHasPopup="dialog",s.ariaControlsElements=[this.#Vt];const a=document.createElement("span");a.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-popup-button-label"),s.append(a),s.addEventListener("click",(()=>{const e=this.#It,t=parseFloat(getComputedStyle(this.#jt).height);this.toggle(e,!0,!1),e.editComment({height:t})})),s.addEventListener("contextmenu",noContextMenu);const o=document.createElement("button");o.classList.add("commentPopupDelete","toolbarButton"),o.tabIndex=0,o.setAttribute("data-l10n-id","pdfjs-editor-delete-comment-popup-button");const r=document.createElement("span");r.setAttribute("data-l10n-id","pdfjs-editor-delete-comment-popup-button-label"),o.append(r),o.addEventListener("click",(()=>{this.#C.dispatch("reporttelemetry",{source:this,details:{type:"comment",data:{deleted:!0}}});const e=this.#It,t=e.comment;this.destroy(),t?.text?e._uiManager.deleteComment(e,t):e.comment=null,e.focus()})),o.addEventListener("contextmenu",noContextMenu),n.append(s,o),t.append(i,n);const l=document.createElement("hr"),d=this.#jt=document.createElement("div");let h;d.className="commentPopupText",e.append(t,l,d);const c=()=>{e.classList.remove("dragging"),h?.abort(),h=null};return t.addEventListener("pointerdown",(t=>{if(h)return void c();const{target:i,clientX:s,clientY:a}=t;if(n.contains(i))return;stopEvent(t);const{width:o,height:r}=this.#It.parentBoundingClientRect;this.#Dt=s,this.#Bt=a,h=new AbortController;const{signal:l}=h;e.classList.add("dragging"),window.addEventListener("pointermove",(e=>{if(!h)return;const{clientX:t,clientY:i}=e;this.#De(this.#Ht+(t-this.#Dt)/o,this.#zt+(i-this.#Bt)/r,!1),this.#Dt=t,this.#Bt=i,stopEvent(e)}),{signal:l}),window.addEventListener("blur",c,{signal:l}),window.addEventListener("pointerup",(e=>{h&&(c(),stopEvent(e))}),{signal:l})})),e}updateColor(e){if(this.#It!==e||!this.#s)return;const{color:t,opacity:i}=e.getData();this.#Le.style.backgroundColor=t&&CommentManager._makeCommentColor(t,i)||""}_hide(e){const t=this.#$t();t.classList.toggle("hidden",!0),t.classList.toggle("selected",!1),(e||this.#It)?.setCommentButtonStates({selected:!1,hasPopup:!1}),this.#It=null,this.#Kt=!1,this.#s=!1,this.#jt.replaceChildren(),this.sidebar.selectComment(null)}toggle(e,t,i=void 0,n=!0){if(!e)return void this.destroy();if(t)i??=this.#It!==e||(!this.#Kt||!this.#s);else{if(this.#Kt)return;i??=!this.#s}if(!i)return void this._hide(e);this.#s=!0,this.#It!==e&&this.#It?.setCommentButtonStates({selected:!1,hasPopup:!1});const s=this.#$t();this.#Ft.classList.toggle("hidden",!n),s.classList.toggle("hidden",!1),s.classList.toggle("selected",t),this.#Kt=t,this.#It=e,e.setCommentButtonStates({selected:t,hasPopup:!0});const{contentsObj:a,richText:o,creationDate:r,modificationDate:l,color:d,opacity:h}=e.getData();s.style.backgroundColor=d&&CommentManager._makeCommentColor(d,h)||"",this.#jt.replaceChildren();const c=!o?.str||a?.str&&o.str!==a.str?a?.str:o.html;c&&renderRichText({html:c,dir:a?.dir||"auto",className:"richText"},this.#jt),this.#Ut.textContent=this.#mt.format(PDFDateString.toDateObject(l||r)),this.#De(...e.commentPopupPosition,e.hasDefaultPopupPosition()),e.elementBeforePopup.after(s),s.addEventListener("focus",(({relatedTarget:e})=>{this.#Wt=e}),{once:!0}),t&&setTimeout((()=>s.focus()),0)}#De(e,t,i){if(i){const t=this.#It.parentBoundingClientRect,i=this._popupWidth/t.width;if(this.#kt&&e+i>1||!this.#kt&&e-i>=0){e-=i-this.#It.commentButtonWidth}const n=.01;e=this.#kt?Math.max(e,-t.x/t.width+n):Math.min(e,(window.innerWidth-t.x)/t.width-i-n)}else this.#It.commentPopupPosition=[e,t];this.#Ht=e,this.#zt=t;const{style:n}=this.#Le;n.left=100*e+"%",n.top=100*t+"%"}destroy(){this._hide(),this.#Le?.remove(),this.#Le=this.#jt=this.#Ut=null,this.#Dt=this.#Bt=1/0,this.#Ht=this.#zt=0,this.#Wt=null}}function download(e,t){const i=document.createElement("a");if(!i.click)throw new Error(\'DownloadManager: "a.click()" is not supported.\');i.href=e,i.target="_parent","download"in i&&(i.download=t),(document.body||document.documentElement).append(i),i.click(),i.remove()}class DownloadManager{#Gt=new WeakMap;downloadData(e,t,i){download(URL.createObjectURL(new Blob([e],{type:i})),t)}openOrDownloadData(e,t,i=null){const n=isPdfFile(t),s=n?"application/pdf":"";if(n){let n,a=this.#Gt.get(e);a||(a=URL.createObjectURL(new Blob([e],{type:s})),this.#Gt.set(e,a)),n="?file="+encodeURIComponent(a+"#"+t),i&&(n+=`#${escape(i)}`);try{return window.open(n),!0}catch(t){console.error("openOrDownloadData:",t),URL.revokeObjectURL(a),this.#Gt.delete(e)}}return this.downloadData(e,t,s),!1}download(e,t,i){let n;if(e)n=URL.createObjectURL(new Blob([e],{type:"application/pdf"}));else{if(!createValidAbsoluteUrl(t,"http://example.com"))return void console.error(`download - not a valid URL: ${t}`);n=t+"#pdfjs.action=download"}download(n,i)}}class EditorUndoBar{#ut=null;#Le;#C=null;#Xt=null;#Yt=null;isOpen=!1;#Zt;#qt=null;#Qt;static#Jt=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",signature:"pdfjs-editor-undo-bar-message-signature",comment:"pdfjs-editor-undo-bar-message-comment",_multiple:"pdfjs-editor-undo-bar-message-multiple"});constructor({container:e,message:t,undoButton:i,closeButton:n},s){this.#Le=e,this.#Zt=t,this.#Qt=i,this.#ut=n,this.#C=s}destroy(){this.#Yt?.abort(),this.#Yt=null,this.hide()}show(e,t){if(!this.#Yt){this.#Yt=new AbortController;const e={signal:this.#Yt.signal},t=this.hide.bind(this);this.#Le.addEventListener("contextmenu",noContextMenu,e),this.#ut.addEventListener("click",t,e),this.#C._on("beforeprint",t,e),this.#C._on("download",t,e)}this.hide(),"string"==typeof t?this.#Zt.setAttribute("data-l10n-id",EditorUndoBar.#Jt[t]):(this.#Zt.setAttribute("data-l10n-id",EditorUndoBar.#Jt._multiple),this.#Zt.setAttribute("data-l10n-args",JSON.stringify({count:t}))),this.isOpen=!0,this.#Le.hidden=!1,this.#qt=new AbortController,this.#Qt.addEventListener("click",(()=>{e(),this.hide()}),{signal:this.#qt.signal}),this.#Xt=setTimeout((()=>{this.#Le.focus(),this.#Xt=null}),100)}hide(){this.isOpen&&(this.isOpen=!1,this.#Le.hidden=!0,this.#qt?.abort(),this.#qt=null,this.#Xt&&(clearTimeout(this.#Xt),this.#Xt=null))}}class OverlayManager{#ei=new WeakMap;#ti=null;get active(){return this.#ti}async register(e,t=!1){if("object"!=typeof e)throw new Error("Not enough parameters.");if(this.#ei.has(e))throw new Error("The overlay is already registered.");this.#ei.set(e,{canForceClose:t}),e.addEventListener("cancel",(({target:e})=>{this.#ti===e&&(this.#ti=null)}))}async open(e){if(!this.#ei.has(e))throw new Error("The overlay does not exist.");if(this.#ti){if(this.#ti===e)throw new Error("The overlay is already active.");if(!this.#ei.get(e).canForceClose)throw new Error("Another overlay is currently active.");await this.close()}this.#ti=e,e.showModal()}async close(e=this.#ti){if(!this.#ei.has(e))throw new Error("The overlay does not exist.");if(!this.#ti)throw new Error("The overlay is currently not active.");if(this.#ti!==e)throw new Error("Another overlay is currently active.");e.close(),this.#ti=null}async closeIfActive(e){this.#ti===e&&await this.close(e)}}class PasswordPrompt{#ii=null;#ni=null;#si=null;constructor(e,t,i=!1){this.dialog=e.dialog,this.label=e.label,this.input=e.input,this.submitButton=e.submitButton,this.cancelButton=e.cancelButton,this.overlayManager=t,this._isViewerEmbedded=i,this.submitButton.addEventListener("click",this.#ai.bind(this)),this.cancelButton.addEventListener("click",this.close.bind(this)),this.input.addEventListener("keydown",(e=>{13===e.keyCode&&this.#ai()})),this.overlayManager.register(this.dialog,!0),this.dialog.addEventListener("close",this.#L.bind(this))}async open(){await(this.#ii?.promise),this.#ii=Promise.withResolvers();try{await this.overlayManager.open(this.dialog)}catch(e){throw this.#ii.resolve(),e}const e=this.#si===PasswordResponses.INCORRECT_PASSWORD;this._isViewerEmbedded&&!e||this.input.focus(),this.label.setAttribute("data-l10n-id",e?"pdfjs-password-invalid":"pdfjs-password-label")}async close(){this.overlayManager.closeIfActive(this.dialog)}#ai(){const e=this.input.value;e?.length>0&&this.#oi(e)}#L(){this.#oi(new Error("PasswordPrompt cancelled.")),this.#ii.resolve()}#oi(e){this.#ni&&(this.close(),this.input.value="",this.#ni(e),this.#ni=null)}async setUpdateCallback(e,t){this.#ii&&await this.#ii.promise,this.#ni=e,this.#si=t}}const TREEITEM_OFFSET_TOP=-100,TREEITEM_SELECTED_CLASS="selected";class BaseTreeViewer{constructor(e){this.container=e.container,this.eventBus=e.eventBus,this._l10n=e.l10n,this.reset()}reset(){this._pdfDocument=null,this._lastToggleIsShow=!0,this._currentTreeItem=null,this.container.replaceChildren(),this.container.classList.remove("withNesting")}_dispatchEvent(e){throw new Error("Not implemented: _dispatchEvent")}_bindLink(e,t){throw new Error("Not implemented: _bindLink")}_normalizeTextContent(e){return removeNullCharacters(e,!0)||"–"}_addToggleButton(e,t=!1){const i=document.createElement("div");i.className="treeItemToggler",t&&i.classList.add("treeItemsHidden"),e.prepend(i)}_toggleTreeItem(e,t=!1){this._l10n.pause(),this._lastToggleIsShow=t;for(const i of e.querySelectorAll(".treeItemToggler"))i.classList.toggle("treeItemsHidden",!t);this._l10n.resume()}_toggleAllTreeItems(){this._toggleTreeItem(this.container,!this._lastToggleIsShow)}_finishRendering(e,t,i=!1){i&&(this.container.classList.add("withNesting"),this._lastToggleIsShow=!e.querySelector(".treeItemsHidden"),this.container.addEventListener("click",(e=>{const{target:t}=e;if(t.classList.contains("treeItemToggler")&&(stopEvent(e),t.classList.toggle("treeItemsHidden"),e.shiftKey)){const e=!t.classList.contains("treeItemsHidden");this._toggleTreeItem(this.container,e)}}))),this._l10n.pause(),this.container.append(e),this._l10n.resume(),this._dispatchEvent(t)}render(e){throw new Error("Not implemented: render")}_updateCurrentTreeItem(e=null){this._currentTreeItem&&(this._currentTreeItem.classList.remove("selected"),this._currentTreeItem=null),e&&(e.classList.add("selected"),this._currentTreeItem=e)}_scrollToCurrentTreeItem(e){if(!e)return;this._l10n.pause();let t=e.parentNode;for(;t&&t!==this.container;){if(t.classList.contains("treeItem")){const e=t.firstElementChild;e?.classList.remove("treeItemsHidden")}t=t.parentNode}this._l10n.resume(),this._updateCurrentTreeItem(e),this.container.scrollTo(e.offsetLeft,e.offsetTop+-100)}}class PDFAttachmentViewer extends BaseTreeViewer{constructor(e){super(e),this.downloadManager=e.downloadManager,this.eventBus._on("fileattachmentannotation",this.#ri.bind(this))}reset(e=!1){super.reset(),this._attachments=null,e||(this._renderedCapability=Promise.withResolvers()),this._pendingDispatchEvent=!1}async _dispatchEvent(e){this._renderedCapability.resolve(),(0!==e||this._pendingDispatchEvent||(this._pendingDispatchEvent=!0,await waitOnEventOrTimeout({target:this.eventBus,name:"annotationlayerrendered",delay:1e3}),this._pendingDispatchEvent))&&(this._pendingDispatchEvent=!1,this.eventBus.dispatch("attachmentsloaded",{source:this,attachmentsCount:e}))}_bindLink(e,{content:t,description:i,filename:n}){i&&(e.title=i),e.onclick=()=>(this.downloadManager.openOrDownloadData(t,n),!1)}render({attachments:e,keepRenderedCapability:t=!1}){if(this._attachments&&this.reset(t),this._attachments=e||null,!e)return void this._dispatchEvent(0);const i=document.createDocumentFragment(),n=document.createElement("ul");i.append(n);let s=0;for(const t in e){const i=e[t],a=document.createElement("li");n.append(a);const o=document.createElement("a");a.append(o),this._bindLink(o,i),o.textContent=this._normalizeTextContent(i.filename),s++}this._finishRendering(i,s)}#ri(e){const t=this._renderedCapability.promise;t.then((()=>{if(t!==this._renderedCapability.promise)return;const i=this._attachments||Object.create(null);for(const t in i)if(e.filename===t)return;i[e.filename]=e,this.render({attachments:i,keepRenderedCapability:!0})}))}}const CSS_CLASS_GRAB="grab-to-pan-grab";class GrabToPan{#li=null;#di=null;#hi=null;constructor({element:e}){this.element=e,this.document=e.ownerDocument;(this.overlay=document.createElement("div")).className="grab-to-pan-grabbing"}activate(){this.#li||(this.#li=new AbortController,this.element.addEventListener("mousedown",this.#ci.bind(this),{capture:!0,signal:this.#li.signal}),this.element.classList.add(CSS_CLASS_GRAB))}deactivate(){this.#li&&(this.#li.abort(),this.#li=null,this.#ui(),this.element.classList.remove(CSS_CLASS_GRAB))}toggle(){this.#li?this.deactivate():this.activate()}ignoreTarget(e){return e.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}#ci(e){if(0!==e.button||this.ignoreTarget(e.target))return;if(e.originalTarget)try{e.originalTarget.tagName}catch{return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=e.clientX,this.clientYStart=e.clientY,this.#di=new AbortController;const t=this.#ui.bind(this),i={capture:!0,signal:this.#di.signal};this.document.addEventListener("mousemove",this.#gi.bind(this),i),this.document.addEventListener("mouseup",t,i),this.#hi=new AbortController,this.element.addEventListener("scroll",t,{capture:!0,signal:this.#hi.signal}),stopEvent(e);const n=document.activeElement;n&&!n.contains(e.target)&&n.blur()}#gi(e){if(this.#hi?.abort(),this.#hi=null,!(1&e.buttons))return void this.#ui();const t=e.clientX-this.clientXStart,i=e.clientY-this.clientYStart;this.element.scrollTo({top:this.scrollTopStart-i,left:this.scrollLeftStart-t,behavior:"instant"}),this.overlay.parentNode||document.body.append(this.overlay)}#ui(){this.#di?.abort(),this.#di=null,this.#hi?.abort(),this.#hi=null,this.overlay.remove()}}class PDFCursorTools{#ti=CursorTool.SELECT;#pi=null;constructor({container:e,eventBus:t,cursorToolOnLoad:i=CursorTool.SELECT}){this.container=e,this.eventBus=t,this.#mi(),Promise.resolve().then((()=>{this.switchTool(i)}))}get activeTool(){return this.#ti}switchTool(e){null===this.#pi&&this.#fi(e)}#fi(e,t=!1){if(e===this.#ti)return void(null!==this.#pi&&this.eventBus.dispatch("cursortoolchanged",{source:this,tool:e,disabled:t}));const i=()=>{switch(this.#ti){case CursorTool.SELECT:break;case CursorTool.HAND:this._handTool.deactivate()}};switch(e){case CursorTool.SELECT:i();break;case CursorTool.HAND:i(),this._handTool.activate();break;default:return void console.error(`switchTool: "${e}" is an unsupported value.`)}this.#ti=e,this.eventBus.dispatch("cursortoolchanged",{source:this,tool:e,disabled:t})}#mi(){this.eventBus._on("switchcursortool",(i=>{i.reset?null!==this.#pi&&(e=AnnotationEditorType.NONE,t=PresentationModeState.NORMAL,n()):this.switchTool(i.tool)}));let e=AnnotationEditorType.NONE,t=PresentationModeState.NORMAL;const i=()=>{this.#pi??=this.#ti,this.#fi(CursorTool.SELECT,!0)},n=()=>{null!==this.#pi&&e===AnnotationEditorType.NONE&&t===PresentationModeState.NORMAL&&(this.#fi(this.#pi),this.#pi=null)};this.eventBus._on("annotationeditormodechanged",(({mode:t})=>{e=t,t===AnnotationEditorType.NONE?n():i()})),this.eventBus._on("presentationmodechanged",(({state:e})=>{t=e,e===PresentationModeState.NORMAL?n():e===PresentationModeState.FULLSCREEN&&i()}))}get _handTool(){return shadow(this,"_handTool",new GrabToPan({element:this.container}))}}const NON_METRIC_LOCALES=["en-us","en-lr","my"],US_PAGE_NAMES={"8.5x11":"pdfjs-document-properties-page-size-name-letter","8.5x14":"pdfjs-document-properties-page-size-name-legal"},METRIC_PAGE_NAMES={"297x420":"pdfjs-document-properties-page-size-name-a-three","210x297":"pdfjs-document-properties-page-size-name-a-four"};function getPageName(e,t,i){return i[`${t?e.width:e.height}x${t?e.height:e.width}`]}class PDFDocumentProperties{#bi=null;constructor({dialog:e,fields:t,closeButton:i},n,s,a,o,r){this.dialog=e,this.fields=t,this.overlayManager=n,this.l10n=a,this._fileNameLookup=o,this._titleLookup=r,this.#vi(),i.addEventListener("click",this.close.bind(this)),this.overlayManager.register(this.dialog),s._on("pagechanging",(e=>{this._currentPageNumber=e.pageNumber})),s._on("rotationchanging",(e=>{this._pagesRotation=e.pagesRotation}))}async open(){await Promise.all([this.overlayManager.open(this.dialog),this._dataAvailableCapability.promise]);const e=this._currentPageNumber,t=this._pagesRotation;if(this.#bi&&e===this.#bi._currentPageNumber&&t===this.#bi._pagesRotation)return void this.#wi();const[{info:i,metadata:n,contentLength:s},a]=await Promise.all([this.pdfDocument.getMetadata(),this.pdfDocument.getPage(e)]),[o,r,l,d,h,c,u]=await Promise.all([this._fileNameLookup(),this.#Ei(s),this._titleLookup(),this.#yi(n?.get("xmp:createdate"),i.CreationDate),this.#yi(n?.get("xmp:modifydate"),i.ModDate),this.#Si(getPageSizeInches(a),t),this.#Ci(i.IsLinearized)]);this.#bi=Object.freeze({fileName:o,fileSize:r,title:l,author:n?.get("dc:creator")?.join("\\n")||i.Author,subject:n?.get("dc:subject")?.join("\\n")||i.Subject,keywords:n?.get("pdf:keywords")||i.Keywords,creationDate:d,modificationDate:h,creator:n?.get("xmp:creatortool")||i.Creator,producer:n?.get("pdf:producer")||i.Producer,version:i.PDFFormatVersion,pageCount:this.pdfDocument.numPages,pageSize:c,linearized:u,_currentPageNumber:e,_pagesRotation:t}),this.#wi();const{length:g}=await this.pdfDocument.getDownloadInfo();if(s===g)return;const p=Object.assign(Object.create(null),this.#bi);p.fileSize=await this.#Ei(g),this.#bi=Object.freeze(p),this.#wi()}async close(){this.overlayManager.close(this.dialog)}setDocument(e){this.pdfDocument&&(this.#vi(),this.#wi()),e&&(this.pdfDocument=e,this._dataAvailableCapability.resolve())}#vi(){this.pdfDocument=null,this.#bi=null,this._dataAvailableCapability=Promise.withResolvers(),this._currentPageNumber=1,this._pagesRotation=0}#wi(){if(!this.#bi||this.overlayManager.active===this.dialog)for(const e in this.fields){const t=this.#bi?.[e];this.fields[e].textContent=t||0===t?t:"-"}}async#Ei(e=0){const t=e/1024,i=t/1024;return t?this.l10n.get(i>=1?"pdfjs-document-properties-size-mb":"pdfjs-document-properties-size-kb",{mb:i,kb:t,b:e}):void 0}async#Si(e,t){if(!e)return;t%180!=0&&(e={width:e.height,height:e.width});const i=isPortraitOrientation(e),n=NON_METRIC_LOCALES.includes(this.l10n.getLanguage());let s={width:Math.round(100*e.width)/100,height:Math.round(100*e.height)/100},a={width:Math.round(25.4*e.width*10)/10,height:Math.round(25.4*e.height*10)/10},o=getPageName(s,i,US_PAGE_NAMES)||getPageName(a,i,METRIC_PAGE_NAMES);if(!(o||Number.isInteger(a.width)&&Number.isInteger(a.height))){const t={width:25.4*e.width,height:25.4*e.height},n={width:Math.round(a.width),height:Math.round(a.height)};Math.abs(t.width-n.width)<.1&&Math.abs(t.height-n.height)<.1&&(o=getPageName(n,i,METRIC_PAGE_NAMES),o&&(s={width:Math.round(n.width/25.4*100)/100,height:Math.round(n.height/25.4*100)/100},a=n))}const[{width:r,height:l},d,h,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"),o&&this.l10n.get(o),this.l10n.get(i?"pdfjs-document-properties-page-size-orientation-portrait":"pdfjs-document-properties-page-size-orientation-landscape")]);return this.l10n.get(h?"pdfjs-document-properties-page-size-dimension-name-string":"pdfjs-document-properties-page-size-dimension-string",{width:r,height:l,unit:d,name:h,orientation:c})}async#yi(e,t){const i=Date.parse(e)||PDFDateString.toDateObject(t);return i?this.l10n.get("pdfjs-document-properties-date-time-string",{dateObj:i.valueOf()}):void 0}#Ci(e){return this.l10n.get(e?"pdfjs-document-properties-linearized-yes":"pdfjs-document-properties-linearized-no")}}const CharacterType={SPACE:0,ALPHA_LETTER:1,PUNCT:2,HAN_LETTER:3,KATAKANA_LETTER:4,HIRAGANA_LETTER:5,HALFWIDTH_KATAKANA_LETTER:6,THAI_LETTER:7};function isAlphabeticalScript(e){return e<11904}function isAscii(e){return 0==(65408&e)}function isAsciiAlpha(e){return e>=97&&e<=122||e>=65&&e<=90}function isAsciiDigit(e){return e>=48&&e<=57}function isAsciiSpace(e){return 32===e||9===e||13===e||10===e}function isHan(e){return e>=13312&&e<=40959||e>=63744&&e<=64255}function isKatakana(e){return e>=12448&&e<=12543}function isHiragana(e){return e>=12352&&e<=12447}function isHalfwidthKatakana(e){return e>=65376&&e<=65439}function isThai(e){return 3584==(65408&e)}function getCharacterType(e){return isAlphabeticalScript(e)?isAscii(e)?isAsciiSpace(e)?CharacterType.SPACE:isAsciiAlpha(e)||isAsciiDigit(e)||95===e?CharacterType.ALPHA_LETTER:CharacterType.PUNCT:isThai(e)?CharacterType.THAI_LETTER:160===e?CharacterType.SPACE:CharacterType.ALPHA_LETTER:isHan(e)?CharacterType.HAN_LETTER:isKatakana(e)?CharacterType.KATAKANA_LETTER:isHiragana(e)?CharacterType.HIRAGANA_LETTER:isHalfwidthKatakana(e)?CharacterType.HALFWIDTH_KATAKANA_LETTER:CharacterType.ALPHA_LETTER}let NormalizeWithNFKC;function getNormalizeWithNFKC(){return NormalizeWithNFKC}const FindState={FOUND:0,NOT_FOUND:1,WRAPPED:2,PENDING:3},FIND_TIMEOUT=250,MATCH_SCROLL_OFFSET_TOP=-50,CHARACTERS_TO_NORMALIZE={"‐":"-","‘":"\'","’":"\'","‚":"\'","‛":"\'","“":\'"\',"”":\'"\',"„":\'"\',"‟":\'"\',"¼":"1/4","½":"1/2","¾":"3/4"},DIACRITICS_EXCEPTION=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 DIACRITICS_EXCEPTION_STR;const DIACRITICS_REG_EXP=/\\p{M}+/gu,SPECIAL_CHARS_REG_EXP=/([+^$|])|(\\p{P}+)|(\\s+)|(\\p{M})|(\\p{L})/gu,NOT_DIACRITIC_FROM_END_REG_EXP=/([^\\p{M}])\\p{M}*$/u,NOT_DIACRITIC_FROM_START_REG_EXP=/^\\p{M}*([^\\p{M}])/u,SYLLABLES_REG_EXP=/[\\uAC00-\\uD7AF\\uFA6C\\uFACF-\\uFAD1\\uFAD5-\\uFAD7]+/g,SYLLABLES_LENGTHS=new Map,FIRST_CHAR_SYLLABLES_REG_EXP="[\\\\u1100-\\\\u1112\\\\ud7a4-\\\\ud7af\\\\ud84a\\\\ud84c\\\\ud850\\\\ud854\\\\ud857\\\\ud85f]",NFKC_CHARS_TO_NORMALIZE=new Map;let noSyllablesRegExp=null,withSyllablesRegExp=null;function normalize(e,t={}){const i=[];let n;for(;null!==(n=SYLLABLES_REG_EXP.exec(e));){let{index:e}=n;for(const t of n[0]){let n=SYLLABLES_LENGTHS.get(t);n||(n=t.normalize("NFD").length,SYLLABLES_LENGTHS.set(t,n)),i.push([n,e++])}}const s=i.length>0,a=t.ignoreDashEOL??!1;let o;if(!s&&noSyllablesRegExp)o=noSyllablesRegExp;else if(s&&withSyllablesRegExp)o=withSyllablesRegExp;else{const e=Object.keys(CHARACTERS_TO_NORMALIZE).join(""),t=getNormalizeWithNFKC();o=new RegExp([`[${e}]`,`[${t}]`,`${"(?:゙|゚)"}\\\\n`,"\\\\p{M}+(?:-\\\\n)?",`${"\\\\p{Ll}-\\\\n(?=\\\\p{Ll})|\\\\p{Lu}-\\\\n(?=\\\\p{L})"}`,"\\\\S-\\\\n",`${"(?:\\\\p{Ideographic}|[぀-ヿ])"}\\\\n`,"\\\\n",s?FIRST_CHAR_SYLLABLES_REG_EXP:"\\\\u0000"].map((e=>`(${e})`)).join("|"),"gum"),s?withSyllablesRegExp=o:noSyllablesRegExp=o}const r=[];for(;null!==(n=DIACRITICS_REG_EXP.exec(e));)r.push([n[0].length,n.index]);let l=e.normalize("NFD");const d=[0,0];let h=0,c=0,u=0,g=0,p=0,m=!1;l=l.replace(o,((e,t,n,s,o,l,f,b,v,w,E)=>{if(E-=g,t){const e=CHARACTERS_TO_NORMALIZE[t],i=e.length;for(let e=1;e<i;e++)d.push(E-u+e,u-e);return u-=i-1,e}if(n){let e=NFKC_CHARS_TO_NORMALIZE.get(n);e||(e=n.normalize("NFKC"),NFKC_CHARS_TO_NORMALIZE.set(n,e));const t=e.length;for(let e=1;e<t;e++)d.push(E-u+e,u-e);return u-=t-1,e}if(s)return m=!0,E+p===r[h]?.[1]?++h:(d.push(E-1-u+1,u-1),u-=1,g+=1),d.push(E-u+1,u),g+=1,p+=1,s.charAt(0);if(o){const e=o.endsWith("\\n"),t=e?o.length-2:o.length;m=!0;let i=t;E+p===r[h]?.[1]&&(i-=r[h][0],++h);for(let e=1;e<=i;e++)d.push(E-1-u+e,u-e);return u-=i,g+=i,e?(E+=t-1,d.push(E-u+1,1+u),u+=1,g+=1,p+=1,o.slice(0,t)):o}if(l){if(a)return g+=1,p+=1,l.slice(0,-1);const e=l.length-2;return d.push(E-u+e,1+u),u+=1,g+=1,p+=1,l.slice(0,-2)}if(f)return g+=1,p+=1,f.slice(0,-1);if(b){const e=b.length-1;return d.push(E-u+e,u),g+=1,p+=1,b.slice(0,-1)}if(v)return d.push(E-u+1,u-1),u-=1,g+=1,p+=1," ";if(E+p===i[c]?.[1]){const e=i[c][0]-1;++c;for(let t=1;t<=e;t++)d.push(E-(u-t),u-t);u-=e,g+=e}return w})),d.push(l.length,u);const f=new Uint32Array(d.length>>1),b=new Int32Array(d.length>>1);for(let e=0,t=d.length;e<t;e+=2)f[e>>1]=d[e],b[e>>1]=d[e+1];return[l,[f,b],m]}function getOriginalIndex(e,t,i){if(!e)return[t,i];const[n,s]=e,a=t,o=t+i-1;let r=binarySearchFirstItem(n,(e=>e>=a));n[r]>a&&--r;let l=binarySearchFirstItem(n,(e=>e>=o),r);n[l]>o&&--l;const d=a+s[r];return[d,o+s[l]+1-d]}class PDFFindController{#Ti=null;#Pi=!0;#Ai=0;constructor({linkService:e,eventBus:t,updateMatchesCountOnProgress:i=!0}){this._linkService=e,this._eventBus=t,this.#Pi=i,this.onIsPageVisible=null,this.#vi(),t._on("find",this.#_i.bind(this)),t._on("findbarclose",this.#Li.bind(this)),t._on("pagesedited",this.#Ii.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.#Ti}setDocument(e){this._pdfDocument&&this.#vi(),e&&(this._pdfDocument=e,this._firstPageCapability.resolve())}#_i(e){if(!e)return;const t=this._pdfDocument,{type:i}=e;(null===this.#Ti||this.#xi(e))&&(this._dirtyMatch=!0),this.#Ti=e,"highlightallchange"!==i&&this.#xe(FindState.PENDING),this._firstPageCapability.promise.then((()=>{if(!this._pdfDocument||t&&this._pdfDocument!==t)return;this.#Mi();const e=!this._highlightMatches,n=!!this._findTimeout;this._findTimeout&&(clearTimeout(this._findTimeout),this._findTimeout=null),i?this._dirtyMatch?this.#Ni():"again"===i?(this.#Ni(),e&&this.#Ti.highlightAll&&this.#Di()):"highlightallchange"===i?(n?this.#Ni():this._highlightMatches=!0,this.#Di()):this.#Ni():this._findTimeout=setTimeout((()=>{this.#Ni(),this._findTimeout=null}),250)}))}scrollMatchIntoView({element:e=null,selectedLeft:t=0,pageIndex:i=-1,matchIndex:n=-1}){if(!this._scrollMatches||!e)return;if(-1===n||n!==this._selected.matchIdx)return;if(-1===i||i!==this._selected.pageIdx)return;this._scrollMatches=!1;scrollIntoView(e,{top:-50,left:t},!0)}#vi(){this._highlightMatches=!1,this._scrollMatches=!1,this._pdfDocument=null,this._pageMatches=[],this._pageMatchesLength=[],this.#Ai=0,this.#Ti=null,this._selected={pageIdx:-1,matchIdx:-1},this._offset={pageIdx:null,matchIdx:null,wrapped:!1},this._extractTextPromises=[],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#Bi(){const{query:e}=this.#Ti;return"string"==typeof e?(e!==this._rawQuery&&(this._rawQuery=e,[this._normalizedQuery]=normalize(e)),this._normalizedQuery):(e||[]).filter((e=>!!e)).map((e=>normalize(e)[0]))}#xi(e){const t=e.query,i=this.#Ti.query,n=typeof t;if(n!==typeof i)return!0;if("string"===n){if(t!==i)return!0}else if(JSON.stringify(t)!==JSON.stringify(i))return!0;switch(e.type){case"again":const e=this._selected.pageIdx+1,t=this._linkService;return e>=1&&e<=t.pagesCount&&e!==t.page&&!(this.onIsPageVisible?.(e)??1);case"highlightallchange":return!1}return!0}#Ri(e,t,i){let n=e.slice(0,t).match(NOT_DIACRITIC_FROM_END_REG_EXP);if(n){const i=e.charCodeAt(t),s=n[1].charCodeAt(0);if(getCharacterType(i)===getCharacterType(s))return!1}if(n=e.slice(t+i).match(NOT_DIACRITIC_FROM_START_REG_EXP),n){const s=e.charCodeAt(t+i-1),a=n[1].charCodeAt(0);if(getCharacterType(s)===getCharacterType(a))return!1}return!0}#Oi(e,t){const{matchDiacritics:i}=this.#Ti;let n=!1;const s=(t,i)=>t===e?i:e.startsWith(t)?`${i}[ ]*`:e.endsWith(t)?`[ ]*${i}`:`[ ]*${i}[ ]*`,a="[ ]*";return(e=e.replaceAll(SPECIAL_CHARS_REG_EXP,((e,a,o,r,l,d)=>a?s(a,RegExp.escape(a)):o?s(o,RegExp.escape(o)):r?"[ ]+":i?l||d:l?DIACRITICS_EXCEPTION.has(l.charCodeAt(0))?l:"":t?(n=!0,`${d}\\\\p{M}*`):d))).endsWith(a)&&(e=e.slice(0,e.length-4)),i&&t&&(DIACRITICS_EXCEPTION_STR||=String.fromCharCode(...DIACRITICS_EXCEPTION),n=!0,e=`${e}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\\\p{M}]|$)`),[n,e]}#ki(e){if(!this.#Ti)return;const t=this.#Bi;if(0===t.length)return;const i=this._pageContents[e],n=this.match(t,i,e),s=this._pageMatches[e]=[],a=this._pageMatchesLength[e]=[],o=this._pageDiffs[e];n?.forEach((({index:e,length:t})=>{const[i,n]=getOriginalIndex(o,e,t);n&&(s.push(i),a.push(n))})),this.#Ti.highlightAll&&this.#Fi(e),this._resumePageIdx===e&&(this._resumePageIdx=null,this.#Vi());const r=s.length;this._matchesCountTotal+=r,this.#Pi?r>0&&this.#ji():++this.#Ai===this._linkService.pagesCount&&this.#ji()}match(e,t,i){const n=this._hasDiacritics[i];let s=!1;if("string"==typeof e?[s,e]=this.#Oi(e,n):e=e.sort().reverse().map((e=>{const[t,i]=this.#Oi(e,n);return s||=t,`(${i})`})).join("|"),!e)return;const{caseSensitive:a,entireWord:o}=this.#Ti;e=new RegExp(e,`g${s?"u":""}${a?"":"i"}`);const r=[];let l;for(;null!==(l=e.exec(t));)o&&!this.#Ri(t,l.index,l[0].length)||r.push({index:l.index,length:l[0].length});return r}#Mi(){if(this._extractTextPromises.length>0)return;let e=Promise.resolve();const t={disableNormalization:!0},i=this._pdfDocument;for(let n=0,s=this._linkService.pagesCount;n<s;n++){const{promise:s,resolve:a}=Promise.withResolvers();this._extractTextPromises[n]=s,e=e.then((async()=>{i===this._pdfDocument?await i.getPage(n+1).then((e=>e.getTextContent(t))).then((e=>{const t=[];for(const i of e.items)t.push(i.str),i.hasEOL&&t.push("\\n");[this._pageContents[n],this._pageDiffs[n],this._hasDiacritics[n]]=normalize(t.join("")),a()}),(e=>{console.error(`Unable to get text content for page ${n+1}`,e),this._pageContents[n]="",this._pageDiffs[n]=null,this._hasDiacritics[n]=!1,a()})):a()}))}}#Fi(e){this._scrollMatches&&this._selected.pageIdx===e&&(this._linkService.page=e+1),this._eventBus.dispatch("updatetextlayermatches",{source:this,pageIndex:e})}#Di(){this._eventBus.dispatch("updatetextlayermatches",{source:this,pageIndex:-1})}#Ni(){const e=this.#Ti.findPrevious,t=this._linkService.page-1,i=this._linkService.pagesCount;if(this._highlightMatches=!0,this._dirtyMatch){this._dirtyMatch=!1,this._selected.pageIdx=this._selected.matchIdx=-1,this._offset.pageIdx=t,this._offset.matchIdx=null,this._offset.wrapped=!1,this._resumePageIdx=null,this._pageMatches.length=0,this._pageMatchesLength.length=0,this.#Ai=0,this._matchesCountTotal=0,this.#Di();for(let e=0;e<i;e++)this._pendingFindMatches.has(e)||(this._pendingFindMatches.add(e),this._extractTextPromises[e].then((()=>{this._pendingFindMatches.delete(e),this.#ki(e)})))}if(0===this.#Bi.length)return void this.#xe(FindState.FOUND);if(this._resumePageIdx)return;const n=this._offset;if(this._pagesToSearch=i,null!==n.matchIdx){const t=this._pageMatches[n.pageIdx].length;if(!e&&n.matchIdx+1<t||e&&n.matchIdx>0)return n.matchIdx=e?n.matchIdx-1:n.matchIdx+1,void this.#Ui(!0);this.#Hi(e)}this.#Vi()}#zi(e){const t=this._offset,i=e.length,n=this.#Ti.findPrevious;return i?(t.matchIdx=n?i-1:0,this.#Ui(!0),!0):(this.#Hi(n),!!(t.wrapped&&(t.matchIdx=null,this._pagesToSearch<0))&&(this.#Ui(!1),!0))}#Vi(){null!==this._resumePageIdx&&console.error("There can only be one pending page.");let e=null;do{const t=this._offset.pageIdx;if(e=this._pageMatches[t],!e){this._resumePageIdx=t;break}}while(!this.#zi(e))}#Hi(e){const t=this._offset,i=this._linkService.pagesCount;t.pageIdx=e?t.pageIdx-1:t.pageIdx+1,t.matchIdx=null,this._pagesToSearch--,(t.pageIdx>=i||t.pageIdx<0)&&(t.pageIdx=e?i-1:0,t.wrapped=!0)}#Ui(e=!1){let t=FindState.NOT_FOUND;const i=this._offset.wrapped;if(this._offset.wrapped=!1,e){const e=this._selected.pageIdx;this._selected.pageIdx=this._offset.pageIdx,this._selected.matchIdx=this._offset.matchIdx,t=i?FindState.WRAPPED:FindState.FOUND,-1!==e&&e!==this._selected.pageIdx&&this.#Fi(e)}this.#xe(t,this.#Ti.findPrevious),-1!==this._selected.pageIdx&&(this._scrollMatches=!0,this.#Fi(this._selected.pageIdx))}#Ii({pagesMapper:e}){if(0===this._extractTextPromises.length)return;this.#Li(),this._dirtyMatch=!0;const t=this._extractTextPromises,i=this._extractTextPromises.length=[];for(let n=0,s=e.length;n<s;n++){const s=e.getPrevPageNumber(n+1)-1;-1!==s&&i.push(t[s]||Promise.resolve())}}#Li(e){const t=this._pdfDocument;this._firstPageCapability.promise.then((()=>{!this._pdfDocument||t&&this._pdfDocument!==t||(this._findTimeout&&(clearTimeout(this._findTimeout),this._findTimeout=null),this._resumePageIdx&&(this._resumePageIdx=null,this._dirtyMatch=!0),this.#xe(FindState.FOUND),this._highlightMatches=!1,this.#Di())}))}#Wi(){const{pageIdx:e,matchIdx:t}=this._selected;let i=0,n=this._matchesCountTotal;if(-1!==t){for(let t=0;t<e;t++)i+=this._pageMatches[t]?.length||0;i+=t+1}return(i<1||i>n)&&(i=n=0),{current:i,total:n}}#ji(){this._eventBus.dispatch("updatefindmatchescount",{source:this,matchesCount:this.#Wi()})}#xe(e,t=!1){(this.#Pi||this.#Ai===this._linkService.pagesCount&&e!==FindState.PENDING)&&this._eventBus.dispatch("updatefindcontrolstate",{source:this,state:e,previous:t,entireWord:this.#Ti?.entireWord??null,matchesCount:this.#Wi(),rawQuery:this.#Ti?.query??null})}}const MATCHES_COUNT_LIMIT=1e3;class PDFFindBar{#Oe;#et=new ResizeObserver(this.#Ki.bind(this));constructor(e,t,i){this.opened=!1,this.bar=e.bar,this.toggleButton=e.toggleButton,this.findField=e.findField,this.highlightAll=e.highlightAllCheckbox,this.caseSensitive=e.caseSensitiveCheckbox,this.matchDiacritics=e.matchDiacriticsCheckbox,this.entireWord=e.entireWordCheckbox,this.findMsg=e.findMsg,this.findResultsCount=e.findResultsCount,this.findPreviousButton=e.findPreviousButton,this.findNextButton=e.findNextButton,this.eventBus=i,this.#Oe=t;const n=new Map([[this.highlightAll,"highlightallchange"],[this.caseSensitive,"casesensitivitychange"],[this.entireWord,"entirewordchange"],[this.matchDiacritics,"diacriticmatchingchange"]]);this.toggleButton.addEventListener("click",(()=>{this.toggle()})),this.findField.addEventListener("input",(()=>{this.dispatchEvent("")})),this.bar.addEventListener("keydown",(({keyCode:e,shiftKey:t,target:i})=>{switch(e){case 13:i===this.findField?this.dispatchEvent("again",t):n.has(i)&&(i.checked=!i.checked,this.dispatchEvent(n.get(i)));break;case 27:this.close()}})),this.findPreviousButton.addEventListener("click",(()=>{this.dispatchEvent("again",!0)})),this.findNextButton.addEventListener("click",(()=>{this.dispatchEvent("again",!1)}));for(const[e,t]of n)e.addEventListener("click",(()=>{this.dispatchEvent(t)}))}reset(){this.updateUIState()}dispatchEvent(e,t=!1){this.eventBus.dispatch("find",{source:this,type:e,query:this.findField.value,caseSensitive:this.caseSensitive.checked,entireWord:this.entireWord.checked,highlightAll:this.highlightAll.checked,findPrevious:t,matchDiacritics:this.matchDiacritics.checked})}updateUIState(e,t,i){const{findField:n,findMsg:s}=this;let a="",o="";switch(e){case FindState.FOUND:break;case FindState.PENDING:o="pending";break;case FindState.NOT_FOUND:a="pdfjs-find-not-found",o="notFound";break;case FindState.WRAPPED:a=t?"pdfjs-find-reached-top":"pdfjs-find-reached-bottom"}n.setAttribute("data-status",o),n.setAttribute("aria-invalid",e===FindState.NOT_FOUND),s.setAttribute("data-status",o),a?s.setAttribute("data-l10n-id",a):(s.removeAttribute("data-l10n-id"),s.textContent=""),this.updateResultsCount(i)}updateResultsCount({current:e=0,total:t=0}={}){const{findResultsCount:i}=this;if(t>0){const n=1e3;i.setAttribute("data-l10n-id",t>n?"pdfjs-find-match-count-limit":"pdfjs-find-match-count"),i.setAttribute("data-l10n-args",JSON.stringify({limit:n,current:e,total:t}))}else i.removeAttribute("data-l10n-id"),i.textContent=""}open(){this.opened||(this.#et.observe(this.#Oe),this.#et.observe(this.bar),this.opened=!0,toggleExpandedBtn(this.toggleButton,!0,this.bar)),this.findField.select(),this.findField.focus()}close(){this.opened&&(this.#et.disconnect(),this.opened=!1,toggleExpandedBtn(this.toggleButton,!1,this.bar),this.eventBus.dispatch("findbarclose",{source:this}))}toggle(){this.opened?this.close():this.open()}#Ki(){const{bar:e}=this;e.classList.remove("wrapContainers");e.clientHeight>e.firstElementChild.clientHeight&&e.classList.add("wrapContainers")}}const HASH_CHANGE_TIMEOUT=1e3,POSITION_UPDATED_THRESHOLD=50,UPDATE_VIEWAREA_TIMEOUT=1e3;function getCurrentHash(){return document.location.hash}class PDFHistory{#$i=null;constructor({linkService:e,eventBus:t}){this.linkService=e,this.eventBus=t,this._initialized=!1,this._fingerprint="",this.reset(),this.eventBus._on("pagesinit",(()=>{this._isPagesLoaded=!1,this.eventBus._on("pagesloaded",(e=>{this._isPagesLoaded=!!e.pagesCount}),{once:!0})}))}initialize({fingerprint:e,resetHistory:t=!1,updateUrl:i=!1}){if(!e||"string"!=typeof e)return void console.error(\'PDFHistory.initialize: The "fingerprint" must be a non-empty string.\');this._initialized&&this.reset();const n=""!==this._fingerprint&&this._fingerprint!==e;this._fingerprint=e,this._updateUrl=!0===i,this._initialized=!0,this.#Gi();const s=window.history.state;if(this._popStateInProgress=!1,this._blockHashChange=0,this._currentHash=getCurrentHash(),this._numPositionUpdates=0,this._uid=this._maxUid=0,this._destination=null,this._position=null,!this.#Xi(s,!0)||t){const{hash:e,page:i,rotation:s}=this.#Yi(!0);return!e||n||t?void this.#Zi(null,!0):void this.#Zi({hash:e,page:i,rotation:s},!0)}const a=s.destination;this.#qi(a,s.uid,!0),void 0!==a.rotation&&(this._initialRotation=a.rotation),a.dest?(this._initialBookmark=JSON.stringify(a.dest),this._destination.page=null):a.hash?this._initialBookmark=a.hash:a.page&&(this._initialBookmark=`page=${a.page}`)}reset(){this._initialized&&(this.#Qi(),this._initialized=!1,this.#Ji()),this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),this._initialBookmark=null,this._initialRotation=null}push({namedDest:e=null,explicitDest:t,pageNumber:i}){if(!this._initialized)return;if(e&&"string"!=typeof e)return void console.error(`PDFHistory.push: "${e}" is not a valid namedDest parameter.`);if(!Array.isArray(t))return void console.error(`PDFHistory.push: "${t}" is not a valid explicitDest parameter.`);if(!this.#en(i)&&(null!==i||this._destination))return void console.error(`PDFHistory.push: "${i}" is not a valid pageNumber parameter.`);const n=e||JSON.stringify(t);if(!n)return;let s=!1;if(this._destination&&(isDestHashesEqual(this._destination.hash,n)||isDestArraysEqual(this._destination.dest,t))){if(this._destination.page)return;s=!0}this._popStateInProgress&&!s||(this.#Zi({dest:t,hash:n,page:i,rotation:this.linkService.rotation},s),this._popStateInProgress||(this._popStateInProgress=!0,Promise.resolve().then((()=>{this._popStateInProgress=!1}))))}pushPage(e){this._initialized&&(this.#en(e)?this._destination?.page!==e&&(this._popStateInProgress||(this.#Zi({dest:null,hash:`page=${e}`,page:e,rotation:this.linkService.rotation}),this._popStateInProgress||(this._popStateInProgress=!0,Promise.resolve().then((()=>{this._popStateInProgress=!1}))))):console.error(`PDFHistory.pushPage: "${e}" is not a valid page number.`))}pushCurrentPosition(){this._initialized&&!this._popStateInProgress&&this.#tn()}back(){if(!this._initialized||this._popStateInProgress)return;const e=window.history.state;this.#Xi(e)&&e.uid>0&&window.history.back()}forward(){if(!this._initialized||this._popStateInProgress)return;const e=window.history.state;this.#Xi(e)&&e.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}#Zi(e,t=!1){const i=t||!this._destination,n={fingerprint:this._fingerprint,uid:i?this._uid:this._uid+1,destination:e};let s;if(this.#qi(e,n.uid),this._updateUrl&&e?.hash){const{href:t,protocol:i}=document.location;"file:"!==i&&(s=updateUrlHash(t,e.hash))}i?window.history.replaceState(n,"",s):window.history.pushState(n,"",s)}#tn(e=!1){if(!this._position)return;let t=this._position;if(e&&(t=Object.assign(Object.create(null),this._position),t.temporary=!0),!this._destination)return void this.#Zi(t);if(this._destination.temporary)return void this.#Zi(t,!0);if(this._destination.hash===t.hash)return;if(!this._destination.page&&this._numPositionUpdates<=50)return;let i=!1;if(this._destination.page>=t.first&&this._destination.page<=t.page){if(void 0!==this._destination.dest||!this._destination.first)return;i=!0}this.#Zi(t,i)}#en(e){return Number.isInteger(e)&&e>0&&e<=this.linkService.pagesCount}#Xi(e,t=!1){if(!e)return!1;if(e.fingerprint!==this._fingerprint){if(!t)return!1;{if("string"!=typeof e.fingerprint||e.fingerprint.length!==this._fingerprint.length)return!1;const[t]=performance.getEntriesByType("navigation");if("reload"!==t?.type)return!1}}return!(!Number.isInteger(e.uid)||e.uid<0)&&(null!==e.destination&&"object"==typeof e.destination)}#qi(e,t,i=!1){this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),i&&e?.temporary&&delete e.temporary,this._destination=e,this._uid=t,this._maxUid=Math.max(this._maxUid,t),this._numPositionUpdates=0}#Yi(e=!1){const t=unescape(getCurrentHash()).substring(1),i=parseQueryString(t),n=i.get("nameddest")||"";let s=0|i.get("page");return(!this.#en(s)||e&&n.length>0)&&(s=null),{hash:t,page:s,rotation:this.linkService.rotation}}#in({location:e}){this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),this._position={hash:e.pdfOpenParams.substring(1),page:this.linkService.page,first:e.pageNumber,rotation:e.rotation},this._popStateInProgress||(this._isPagesLoaded&&this._destination&&!this._destination.page&&this._numPositionUpdates++,this._updateViewareaTimeout=setTimeout((()=>{this._popStateInProgress||this.#tn(!0),this._updateViewareaTimeout=null}),1e3))}#nn({state:e}){const t=getCurrentHash(),i=this._currentHash!==t;if(this._currentHash=t,!e){this._uid++;const{hash:e,page:t,rotation:i}=this.#Yi();return void this.#Zi({hash:e,page:t,rotation:i},!0)}if(!this.#Xi(e))return;this._popStateInProgress=!0,i&&(this._blockHashChange++,waitOnEventOrTimeout({target:window,name:"hashchange",delay:1e3}).then((()=>{this._blockHashChange--})));const n=e.destination;this.#qi(n,e.uid,!0),isValidRotation(n.rotation)&&(this.linkService.rotation=n.rotation),n.dest?this.linkService.goToDestination(n.dest):n.hash?this.linkService.setHash(n.hash):n.page&&(this.linkService.page=n.page),Promise.resolve().then((()=>{this._popStateInProgress=!1}))}#Qi(){this._destination&&!this._destination.temporary||this.#tn()}#Gi(){if(this.#$i)return;this.#$i=new AbortController;const{signal:e}=this.#$i;this.eventBus._on("updateviewarea",this.#in.bind(this),{signal:e}),window.addEventListener("popstate",this.#nn.bind(this),{signal:e}),window.addEventListener("pagehide",this.#Qi.bind(this),{signal:e})}#Ji(){this.#$i?.abort(),this.#$i=null}}function isDestHashesEqual(e,t){if("string"!=typeof e||"string"!=typeof t)return!1;if(e===t)return!0;return parseQueryString(e).get("nameddest")===t}function isDestArraysEqual(e,t){function i(e,t){if(typeof e!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t))return!1;if(null!==e&&"object"==typeof e&&null!==t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(!i(e[n],t[n]))return!1;return!0}return e===t||Number.isNaN(e)&&Number.isNaN(t)}if(!Array.isArray(e)||!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(let n=0,s=e.length;n<s;n++)if(!i(e[n],t[n]))return!1;return!0}class PDFLayerViewer extends BaseTreeViewer{constructor(e){super(e),this.eventBus._on("optionalcontentconfigchanged",(e=>{this.#sn(e.promise)})),this.eventBus._on("resetlayers",(()=>{this.#sn()})),this.eventBus._on("togglelayerstree",this._toggleAllTreeItems.bind(this))}reset(){super.reset(),this._optionalContentConfig=null,this._optionalContentVisibility?.clear(),this._optionalContentVisibility=null}_dispatchEvent(e){this.eventBus.dispatch("layersloaded",{source:this,layersCount:e})}_bindLink(e,{groupId:t,input:i}){const n=()=>{const e=i.checked;this._optionalContentConfig.setVisibility(t,e);const n=this._optionalContentVisibility.get(t);n&&(n.visible=e),this.eventBus.dispatch("optionalcontentconfig",{source:this,promise:Promise.resolve(this._optionalContentConfig)})};e.onclick=t=>t.target===i?(n(),!0):t.target!==e||(i.checked=!i.checked,n(),!1)}_setNestedName(e,{name:t=null}){"string"!=typeof t?(e.setAttribute("data-l10n-id","pdfjs-additional-layers"),e.style.fontStyle="italic",this._l10n.translateOnce(e)):e.textContent=this._normalizeTextContent(t)}_addToggleButton(e,{name:t=null}){super._addToggleButton(e,null===t)}_toggleAllTreeItems(){this._optionalContentConfig&&super._toggleAllTreeItems()}render({optionalContentConfig:e,pdfDocument:t}){this._optionalContentConfig&&this.reset(),this._optionalContentConfig=e||null,this._pdfDocument=t||null;const i=e?.getOrder();if(!i)return void this._dispatchEvent(0);this._optionalContentVisibility=new Map;const n=document.createDocumentFragment(),s=[{parent:n,groups:i}];let a=0,o=!1;for(;s.length>0;){const t=s.shift();for(const i of t.groups){const n=document.createElement("div");n.className="treeItem";const r=document.createElement("a");if(n.append(r),"object"==typeof i){o=!0,this._addToggleButton(n,i),this._setNestedName(r,i);const e=document.createElement("div");e.className="treeItems",n.append(e),s.push({parent:e,groups:i.order})}else{const t=e.getGroup(i),n=document.createElement("label"),s=document.createElement("input");n.append(s,document.createTextNode(this._normalizeTextContent(t.name))),this._bindLink(r,{groupId:i,input:s}),s.type="checkbox",s.checked=t.visible,this._optionalContentVisibility.set(i,{input:s,visible:s.checked}),r.append(n),a++}t.parent.append(n)}}this._finishRendering(n,a,o)}async#sn(e=null){if(!this._optionalContentConfig)return;const t=this._pdfDocument,i=await(e||t.getOptionalContentConfig({intent:"display"}));if(t===this._pdfDocument)if(e)for(const[e,t]of this._optionalContentVisibility){const n=i.getGroup(e);n&&t.visible!==n.visible&&(t.input.checked=t.visible=!t.visible)}else this.eventBus.dispatch("optionalcontentconfig",{source:this,promise:Promise.resolve(i)}),this.render({optionalContentConfig:i,pdfDocument:this._pdfDocument})}}class PDFOutlineViewer extends BaseTreeViewer{constructor(e){super(e),this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.eventBus._on("toggleoutlinetree",this._toggleAllTreeItems.bind(this)),this.eventBus._on("currentoutlineitem",this._currentOutlineItem.bind(this)),this.eventBus._on("pagechanging",(e=>{this._currentPageNumber=e.pageNumber})),this.eventBus._on("pagesloaded",(e=>{this._isPagesLoaded=!!e.pagesCount,this._currentOutlineItemCapability?.resolve(this._isPagesLoaded)})),this.eventBus._on("sidebarviewchanged",(e=>{this._sidebarView=e.view}))}reset(){super.reset(),this._outline=null,this._pageNumberToDestHashCapability=null,this._currentPageNumber=1,this._isPagesLoaded=null,this._currentOutlineItemCapability?.resolve(!1),this._currentOutlineItemCapability=null}_dispatchEvent(e){this._currentOutlineItemCapability=Promise.withResolvers(),0===e||this._pdfDocument?.loadingParams.disableAutoFetch?this._currentOutlineItemCapability.resolve(!1):null!==this._isPagesLoaded&&this._currentOutlineItemCapability.resolve(this._isPagesLoaded),this.eventBus.dispatch("outlineloaded",{source:this,outlineCount:e,currentOutlineItemPromise:this._currentOutlineItemCapability.promise})}_bindLink(e,{url:t,newWindow:i,action:n,attachment:s,dest:a,setOCGState:o}){const{linkService:r}=this;if(t)r.addLinkAttributes(e,t,i);else{if(n)return e.href=r.getAnchorUrl(""),void(e.onclick=()=>(r.executeNamedAction(n),!1));if(s)return e.href=r.getAnchorUrl(""),void(e.onclick=()=>(this.downloadManager.openOrDownloadData(s.content,s.filename),!1));if(o)return e.href=r.getAnchorUrl(""),void(e.onclick=()=>(r.executeSetOCGState(o),!1));e.href=r.getDestinationHash(a),e.onclick=e=>(this._updateCurrentTreeItem(e.target.parentNode),a&&r.goToDestination(a),!1)}}_setStyles(e,{bold:t,italic:i}){t&&(e.style.fontWeight="bold"),i&&(e.style.fontStyle="italic")}_addToggleButton(e,{count:t,items:i}){let n=!1;if(t<0){let e=i.length;if(e>0){const t=[...i];for(;t.length>0;){const{count:i,items:n}=t.shift();i>0&&n.length>0&&(e+=n.length,t.push(...n))}}Math.abs(t)===e&&(n=!0)}super._addToggleButton(e,n)}_toggleAllTreeItems(){this._outline&&super._toggleAllTreeItems()}render({outline:e,pdfDocument:t}){if(this._outline&&this.reset(),this._outline=e||null,this._pdfDocument=t||null,!e)return void this._dispatchEvent(0);const i=document.createDocumentFragment(),n=[{parent:i,items:e}];let s=0,a=!1;for(;n.length>0;){const e=n.shift();for(const t of e.items){const i=document.createElement("div");i.className="treeItem";const o=document.createElement("a");if(this._bindLink(o,t),this._setStyles(o,t),o.textContent=this._normalizeTextContent(t.title),i.append(o),t.items.length>0){a=!0,this._addToggleButton(i,t);const e=document.createElement("div");e.className="treeItems",i.append(e),n.push({parent:e,items:t.items})}e.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 e=await this._getPageNumberToDestHash(this._pdfDocument);if(e&&(this._updateCurrentTreeItem(null),this._sidebarView===SidebarView.OUTLINE))for(let t=this._currentPageNumber;t>0;t--){const i=e.get(t);if(!i)continue;const n=this.container.querySelector(`a[href="${i}"]`);if(n){this._scrollToCurrentTreeItem(n.parentNode);break}}}async _getPageNumberToDestHash(e){if(this._pageNumberToDestHashCapability)return this._pageNumberToDestHashCapability.promise;this._pageNumberToDestHashCapability=Promise.withResolvers();const t=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:o,items:r}of s.items){let s,l;if("string"==typeof o){if(s=await e.getDestination(o),e!==this._pdfDocument)return null}else s=o;if(Array.isArray(s)){const[n]=s;if(n&&"object"==typeof n?l=e.cachedPageNumber(n):Number.isInteger(n)&&(l=n+1),Number.isInteger(l)&&(!t.has(l)||a>i.get(l))){const e=this.linkService.getDestinationHash(o);t.set(l,e),i.set(l,a)}}r.length>0&&n.push({nesting:a+1,items:r})}}return this._pageNumberToDestHashCapability.resolve(t.size>0?t:null),this._pageNumberToDestHashCapability.promise}}const DELAY_BEFORE_HIDING_CONTROLS=3e3,ACTIVE_SELECTOR="pdfPresentationMode",CONTROLS_SELECTOR="pdfPresentationModeControls",MOUSE_SCROLL_COOLDOWN_TIME=50,PAGE_SWITCH_THRESHOLD=.1,SWIPE_MIN_DISTANCE_THRESHOLD=50,SWIPE_ANGLE_THRESHOLD=Math.PI/6;class PDFPresentationMode{#Ti=PresentationModeState.UNKNOWN;#an=null;#on=null;#rn=null;constructor({container:e,pdfViewer:t,eventBus:i}){this.container=e,this.pdfViewer=t,this.eventBus=i,this.contextMenuOpen=!1,this.mouseScrollTimeStamp=0,this.mouseScrollDelta=0,this.touchSwipeState=null}async request(){const{container:e,pdfViewer:t}=this;if(this.active||!t.pagesCount||!e.requestFullscreen)return!1;this.#ln(),this.#dn(PresentationModeState.CHANGING);const i=e.requestFullscreen();this.#an={pageNumber:t.currentPageNumber,scaleValue:t.currentScaleValue,scrollMode:t.scrollMode,spreadMode:null,annotationEditorMode:null},t.spreadMode===SpreadMode.NONE||t.pageViewsReady&&t.hasEqualPageSizes||(console.warn("Ignoring Spread modes when entering PresentationMode, since the document may contain varying page sizes."),this.#an.spreadMode=t.spreadMode),t.annotationEditorMode!==AnnotationEditorType.DISABLE&&(this.#an.annotationEditorMode=t.annotationEditorMode);try{return await i,t.focus(),!0}catch{this.#hn(),this.#dn(PresentationModeState.NORMAL)}return!1}get active(){return this.#Ti===PresentationModeState.CHANGING||this.#Ti===PresentationModeState.FULLSCREEN}#cn(e){if(!this.active)return;e.preventDefault();const t=normalizeWheelEventDelta(e),i=Date.now(),n=this.mouseScrollTimeStamp;if(!(i>n&&i-n<50)&&((this.mouseScrollDelta>0&&t<0||this.mouseScrollDelta<0&&t>0)&&this.#un(),this.mouseScrollDelta+=t,Math.abs(this.mouseScrollDelta)>=.1)){const e=this.mouseScrollDelta;this.#un();(e>0?this.pdfViewer.previousPage():this.pdfViewer.nextPage())&&(this.mouseScrollTimeStamp=i)}}#dn(e){this.#Ti=e,this.eventBus.dispatch("presentationmodechanged",{source:this,state:e})}#gn(){this.#dn(PresentationModeState.FULLSCREEN),this.container.classList.add(ACTIVE_SELECTOR),setTimeout((()=>{this.pdfViewer.scrollMode=ScrollMode.PAGE,null!==this.#an.spreadMode&&(this.pdfViewer.spreadMode=SpreadMode.NONE),this.pdfViewer.currentPageNumber=this.#an.pageNumber,this.pdfViewer.currentScaleValue="page-fit",null!==this.#an.annotationEditorMode&&(this.pdfViewer.annotationEditorMode={mode:AnnotationEditorType.NONE})}),0),this.#pn(),this.#mn(),this.contextMenuOpen=!1,document.getSelection().empty()}#fn(){const e=this.pdfViewer.currentPageNumber;this.container.classList.remove(ACTIVE_SELECTOR),setTimeout((()=>{this.#hn(),this.#dn(PresentationModeState.NORMAL),this.pdfViewer.scrollMode=this.#an.scrollMode,null!==this.#an.spreadMode&&(this.pdfViewer.spreadMode=this.#an.spreadMode),this.pdfViewer.currentScaleValue=this.#an.scaleValue,this.pdfViewer.currentPageNumber=e,null!==this.#an.annotationEditorMode&&(this.pdfViewer.annotationEditorMode={mode:this.#an.annotationEditorMode}),this.#an=null}),0),this.#bn(),this.#vn(),this.#un(),this.contextMenuOpen=!1}#wn(e){if(this.contextMenuOpen)return this.contextMenuOpen=!1,void e.preventDefault();0===e.button&&(e.target.href&&e.target.parentNode?.hasAttribute("data-internal-link")||(e.preventDefault(),e.shiftKey?this.pdfViewer.previousPage():this.pdfViewer.nextPage()))}#En(){this.contextMenuOpen=!0}#mn(){this.controlsTimeout?clearTimeout(this.controlsTimeout):this.container.classList.add(CONTROLS_SELECTOR),this.controlsTimeout=setTimeout((()=>{this.container.classList.remove(CONTROLS_SELECTOR),delete this.controlsTimeout}),3e3)}#vn(){this.controlsTimeout&&(clearTimeout(this.controlsTimeout),this.container.classList.remove(CONTROLS_SELECTOR),delete this.controlsTimeout)}#un(){this.mouseScrollTimeStamp=0,this.mouseScrollDelta=0}#yn(e){if(this.active)if(e.touches.length>1)this.touchSwipeState=null;else switch(e.type){case"touchstart":this.touchSwipeState={startX:e.touches[0].pageX,startY:e.touches[0].pageY,endX:e.touches[0].pageX,endY:e.touches[0].pageY};break;case"touchmove":if(null===this.touchSwipeState)return;this.touchSwipeState.endX=e.touches[0].pageX,this.touchSwipeState.endY=e.touches[0].pageY,e.preventDefault();break;case"touchend":if(null===this.touchSwipeState)return;let t=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<=SWIPE_ANGLE_THRESHOLD||s>=Math.PI-SWIPE_ANGLE_THRESHOLD)?t=i:Math.abs(n)>50&&Math.abs(s-Math.PI/2)<=SWIPE_ANGLE_THRESHOLD&&(t=n),t>0?this.pdfViewer.previousPage():t<0&&this.pdfViewer.nextPage()}}#pn(){if(this.#rn)return;this.#rn=new AbortController;const{signal:e}=this.#rn,t=this.#yn.bind(this);window.addEventListener("mousemove",this.#mn.bind(this),{signal:e}),window.addEventListener("mousedown",this.#wn.bind(this),{signal:e}),window.addEventListener("wheel",this.#cn.bind(this),{passive:!1,signal:e}),window.addEventListener("keydown",this.#un.bind(this),{signal:e}),window.addEventListener("contextmenu",this.#En.bind(this),{signal:e}),window.addEventListener("touchstart",t,{signal:e}),window.addEventListener("touchmove",t,{signal:e}),window.addEventListener("touchend",t,{signal:e})}#bn(){this.#rn?.abort(),this.#rn=null}#ln(){this.#on||(this.#on=new AbortController,window.addEventListener("fullscreenchange",(()=>{document.fullscreenElement?this.#gn():this.#fn()}),{signal:this.#on.signal}))}#hn(){this.#on?.abort(),this.#on=null}}class XfaLayerBuilder{constructor({pdfPage:e,annotationStorage:t=null,linkService:i,xfaHtml:n=null}){this.pdfPage=e,this.annotationStorage=t,this.linkService=i,this.xfaHtml=n,this.div=null,this._cancelled=!1}async render({viewport:e,intent:t="display"}){if("print"===t){const i={viewport:e.clone({dontFlip:!0}),div:this.div,xfaHtml:this.xfaHtml,annotationStorage:this.annotationStorage,linkService:this.linkService,intent:t};return this.div=document.createElement("div"),i.div=this.div,XfaLayer.render(i)}const i=await this.pdfPage.getXfa();if(this._cancelled||!i)return{textDivs:[]};const n={viewport:e.clone({dontFlip:!0}),div:this.div,xfaHtml:i,annotationStorage:this.annotationStorage,linkService:this.linkService,intent:t};return this.div?XfaLayer.update(n):(this.div=document.createElement("div"),n.div=this.div,XfaLayer.render(n))}cancel(){this._cancelled=!0}hide(){this.div&&(this.div.hidden=!0)}}function getXfaHtmlForPrinting(e,t){const i=t.allXfaHtml,n=new SimpleLinkService,s=Math.round(100*PixelsPerInch.PDF_TO_CSS_UNITS)/100;for(const a of i.children){const i=document.createElement("div");i.className="xfaPrintedPage",e.append(i);const o=new XfaLayerBuilder({pdfPage:null,annotationStorage:t.annotationStorage,linkService:n,xfaHtml:a}),r=getXfaPageViewport(a,{scale:s});o.render({viewport:r,intent:"print"}),i.append(o.div)}}let activeService=null,dialog=null,overlayManager=null,viewerApp={initialized:!1};function renderPage(e,t,i,n,s,a,o){const r=activeService.scratchCanvas,l=s/PixelsPerInch.PDF;r.width=Math.floor(n.width*l),r.height=Math.floor(n.height*l);const d=r.getContext("2d");return d.save(),d.fillStyle="rgb(255, 255, 255)",d.fillRect(0,0,r.width,r.height),d.restore(),Promise.all([t.getPage(i),o]).then((function([e,t]){const i={canvas:r,transform:[l,0,0,l,0,0],viewport:e.getViewport({scale:1,rotation:n.rotation}),intent:"print",annotationMode:AnnotationMode.ENABLE_STORAGE,optionalContentConfigPromise:a,printAnnotationStorage:t};return e.render(i).promise.catch((e=>{throw e instanceof RenderingCancelledException||console.error(e),e}))}))}class PDFPrintService{constructor({pdfDocument:e,pagesOverview:t,printContainer:i,printResolution:n,printAnnotationStoragePromise:s=null}){this.pdfDocument=e,this.pagesOverview=t,this.printContainer=i,this._printResolution=n||150,this._optionalContentConfigPromise=e.getOptionalContentConfig({intent:"print"}),this._printAnnotationStoragePromise=s||Promise.resolve(),this.currentPage=-1,this.scratchCanvas=document.createElement("canvas")}layout(){this.throwIfInactive();const e=document.querySelector("body");e.setAttribute("data-pdfjsprinting",!0);const{width:t,height:i}=this.pagesOverview[0];this.pagesOverview.every((e=>e.width===t&&e.height===i))||console.warn("Not all pages have the same size. The printed result may be incorrect!"),this.pageStyleSheet=document.createElement("style"),this.pageStyleSheet.textContent=`@page { size: ${t}pt ${i}pt;}`,e.append(this.pageStyleSheet)}destroy(){if(activeService!==this)return;this.printContainer.textContent="";document.querySelector("body").removeAttribute("data-pdfjsprinting"),this.pageStyleSheet&&(this.pageStyleSheet.remove(),this.pageStyleSheet=null),this.scratchCanvas.width=this.scratchCanvas.height=0,this.scratchCanvas=null,activeService=null,ensureOverlay().then((function(){overlayManager.closeIfActive(dialog)}))}renderPages(){if(this.pdfDocument.isPureXfa)return getXfaHtmlForPrinting(this.printContainer,this.pdfDocument),Promise.resolve();const e=this.pagesOverview.length,t=(i,n)=>{if(this.throwIfInactive(),++this.currentPage>=e)return renderProgress(e,e),void i();const s=this.currentPage;renderProgress(s,e),renderPage(this,this.pdfDocument,s+1,this.pagesOverview[s],this._printResolution,this._optionalContentConfigPromise,this._printAnnotationStoragePromise).then(this.useRenderedPage.bind(this)).then((function(){t(i,n)}),n)};return new Promise(t)}useRenderedPage(){this.throwIfInactive();const e=document.createElement("img");this.scratchCanvas.toBlob((t=>{e.src=URL.createObjectURL(t)}));const t=document.createElement("div");t.className="printedPage",t.append(e),this.printContainer.append(t);const{promise:i,resolve:n,reject:s}=Promise.withResolvers();return e.onload=n,e.onerror=s,i.catch((()=>{})).then((()=>{URL.revokeObjectURL(e.src)})),i}performPrint(){return this.throwIfInactive(),new Promise((e=>{setTimeout((()=>{this.active?(print.call(window),setTimeout(e,20)):e()}),0)}))}get active(){return this===activeService}throwIfInactive(){if(!this.active)throw new Error("This print request was cancelled or completed.")}}const print=window.print;function dispatchEvent(e){const t=new CustomEvent(e,{bubbles:!1,cancelable:!1,detail:"custom"});window.dispatchEvent(t)}function abort(){activeService&&(activeService.destroy(),dispatchEvent("afterprint"))}function renderProgress(e,t){dialog||=document.getElementById("printServiceDialog");const i=Math.round(100*e/t),n=dialog.querySelector("progress"),s=dialog.querySelector(".relative-progress");n.value=i,s.setAttribute("data-l10n-args",JSON.stringify({progress:i}))}if(window.print=function(){if(activeService)console.warn("Ignored window.print() because of a pending print job.");else{ensureOverlay().then((function(){activeService&&overlayManager.open(dialog)}));try{dispatchEvent("beforeprint")}finally{if(activeService){const e=activeService;activeService.renderPages().then((()=>e.performPrint())).catch((()=>{})).then((()=>{e.active&&abort()}))}else console.error("Expected print service to be initialized."),ensureOverlay().then((function(){overlayManager.closeIfActive(dialog)}))}}},window.addEventListener("keydown",(function(e){80!==e.keyCode||!e.ctrlKey&&!e.metaKey||e.altKey||e.shiftKey&&!window.chrome&&!window.opera||(window.print(),e.preventDefault(),e.stopImmediatePropagation())}),!0),"onbeforeprint"in window){const e=function(e){"custom"!==e.detail&&e.stopImmediatePropagation()};window.addEventListener("beforeprint",e),window.addEventListener("afterprint",e)}let overlayPromise;function ensureOverlay(){if(!overlayPromise){if(overlayManager=viewerApp.overlayManager,!overlayManager)throw new Error("The overlay manager has not yet been initialized.");dialog||=document.getElementById("printServiceDialog"),overlayPromise=overlayManager.register(dialog,!0),document.getElementById("printCancel").onclick=abort,dialog.addEventListener("close",abort)}return overlayPromise}class PDFPrintServiceFactory{static initGlobals(e){viewerApp=e}static get supportsPrinting(){return shadow(this,"supportsPrinting",!0)}static createPrintService(e){if(activeService)throw new Error("The print service is created and active.");return activeService=new PDFPrintService(e)}}const CLEANUP_TIMEOUT=3e4;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(e){this.pdfViewer=e}setThumbnailViewer(e){this.pdfThumbnailViewer=e}isHighestPriority(e){return this.highestPriorityPage===e.renderingId}renderHighestPriority(e){this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.pdfViewer.forceRendering(e)||this.isThumbnailViewEnabled&&this.pdfThumbnailViewer?.forceRendering()||this.printing||this.onIdle&&(this.idleTimeout=setTimeout(this.onIdle.bind(this),3e4))}getHighestPriority(e,t,i,n=!1,s=!1){const a=e.views,o=a.length;if(0===o)return null;for(let e=0;e<o;e++){const t=a[e].view;if(!this.isViewFinished(t))return t}if(!s)for(let e=0;e<o;e++){const{detailView:t}=a[e].view;if(t&&!this.isViewFinished(t))return t}const r=e.first.id,l=e.last.id;if(l-r+1>o){const n=e.ids;for(let e=1,s=l-r;e<s;e++){const s=i?r+e:l-e;if(n.has(s))continue;const a=t[s-1];if(!this.isViewFinished(a))return a}}let d=i?l:r-2,h=t[d];return h&&!this.isViewFinished(h)||n&&(d+=i?1:-1,h=t[d],h&&!this.isViewFinished(h))?h:null}isViewFinished(e){return e.renderingState===RenderingStates.FINISHED}renderView(e){switch(e.renderingState){case RenderingStates.FINISHED:return!1;case RenderingStates.PAUSED:this.highestPriorityPage=e.renderingId,e.resume();break;case RenderingStates.RUNNING:this.highestPriorityPage=e.renderingId;break;case RenderingStates.INITIAL:this.highestPriorityPage=e.renderingId,e.draw().finally((()=>{this.renderHighestPriority()})).catch((e=>{e instanceof RenderingCancelledException||console.error("renderView:",e)}))}return!0}}class PDFScriptingManager{#Sn=null;#Cn=null;#Tn=null;#$i=null;#C=null;#r=null;#Pn=null;#An=null;#_n=!1;#Ln=null;#In=null;constructor({eventBus:e,externalServices:t=null,docProperties:i=null}){this.#C=e,this.#r=t,this.#Tn=i}setViewer(e){this.#An=e}async setDocument(e){if(this.#Pn&&await this.#xn(),this.#Pn=e,!e)return;const[t,i,n]=await Promise.all([e.getFieldObjects(),e.getCalculationOrderIds(),e.getJSActions()]);if(!t&&!n)return void await this.#xn();if(e!==this.#Pn)return;try{this.#Ln=this.#Mn()}catch(e){return console.error("setDocument:",e),void await this.#xn()}const s=this.#C;this.#$i=new AbortController;const{signal:a}=this.#$i;s._on("updatefromsandbox",(e=>{e?.source===window&&this.#Nn(e.detail)}),{signal:a}),s._on("dispatcheventinsandbox",(e=>{this.#Ln?.dispatchEventInSandbox(e.detail)}),{signal:a}),s._on("pagechanging",(({pageNumber:e,previous:t})=>{e!==t&&(this.#Dn(t),this.#Bn(e))}),{signal:a}),s._on("pagerendered",(({pageNumber:e})=>{this._pageOpenPending.has(e)&&e===this.#An.currentPageNumber&&this.#Bn(e)}),{signal:a}),s._on("pagesdestroy",(async()=>{await this.#Dn(this.#An.currentPageNumber),await(this.#Ln?.dispatchEventInSandbox({id:"doc",name:"WillClose"})),this.#Sn?.resolve()}),{signal:a});try{const a=await this.#Tn(e);if(e!==this.#Pn)return;await this.#Ln.createSandbox({objects:t,calculationOrder:i,appInfo:{platform:navigator.platform,language:navigator.language},docInfo:{...a,actions:n}}),s.dispatch("sandboxcreated",{source:this})}catch(e){return console.error("setDocument:",e),void await this.#xn()}await(this.#Ln?.dispatchEventInSandbox({id:"doc",name:"Open"})),await this.#Bn(this.#An.currentPageNumber,!0),Promise.resolve().then((()=>{e===this.#Pn&&(this.#_n=!0)}))}async dispatchWillSave(){return this.#Ln?.dispatchEventInSandbox({id:"doc",name:"WillSave"})}async dispatchDidSave(){return this.#Ln?.dispatchEventInSandbox({id:"doc",name:"DidSave"})}async dispatchWillPrint(){if(this.#Ln){await(this.#In?.promise),this.#In=Promise.withResolvers();try{await this.#Ln.dispatchEventInSandbox({id:"doc",name:"WillPrint"})}catch(e){throw this.#In.resolve(),this.#In=null,e}await this.#In.promise}}async dispatchDidPrint(){return this.#Ln?.dispatchEventInSandbox({id:"doc",name:"DidPrint"})}get destroyPromise(){return this.#Cn?.promise||null}get ready(){return this.#_n}get _pageOpenPending(){return shadow(this,"_pageOpenPending",new Set)}get _visitedPages(){return shadow(this,"_visitedPages",new Map)}async#Nn(e){const t=this.#An,i=t.isInPresentationMode||t.isChangingPresentationMode,{id:n,siblings:s,command:a,value:o}=e;if(!n){switch(a){case"clear":console.clear();break;case"error":console.error(o);break;case"layout":if(!i){const e=apiPageLayoutToViewerModes(o);t.spreadMode=e.spreadMode}break;case"page-num":t.currentPageNumber=o+1;break;case"print":await t.pagesPromise,this.#C.dispatch("print",{source:this});break;case"println":console.log(o);break;case"zoom":i||(t.currentScaleValue=o);break;case"SaveAs":this.#C.dispatch("download",{source:this});break;case"FirstPage":t.currentPageNumber=1;break;case"LastPage":t.currentPageNumber=t.pagesCount;break;case"NextPage":t.nextPage();break;case"PrevPage":t.previousPage();break;case"ZoomViewIn":i||t.increaseScale();break;case"ZoomViewOut":i||t.decreaseScale();break;case"WillPrintFinished":this.#In?.resolve(),this.#In=null}return}if(i&&e.focus)return;delete e.id,delete e.siblings;const r=s?[n,...s]:[n];for(const t of r){const i=document.querySelector(`[data-element-id="${t}"]`);i?i.dispatchEvent(new CustomEvent("updatefromsandbox",{detail:e})):this.#Pn?.annotationStorage.setValue(t,e)}}async#Bn(e,t=!1){const i=this.#Pn,n=this._visitedPages;if(t&&(this.#Sn=Promise.withResolvers()),!this.#Sn)return;const s=this.#An.getPageView(e-1);if(s?.renderingState!==RenderingStates.FINISHED)return void this._pageOpenPending.add(e);this._pageOpenPending.delete(e);const a=(async()=>{const t=await(n.has(e)?null:s.pdfPage?.getJSActions());i===this.#Pn&&await(this.#Ln?.dispatchEventInSandbox({id:"page",name:"PageOpen",pageNumber:e,actions:t}))})();n.set(e,a)}async#Dn(e){const t=this.#Pn,i=this._visitedPages;if(!this.#Sn)return;if(this._pageOpenPending.has(e))return;const n=i.get(e);n&&(i.set(e,null),await n,t===this.#Pn&&await(this.#Ln?.dispatchEventInSandbox({id:"page",name:"PageClose",pageNumber:e})))}#Mn(){if(this.#Cn=Promise.withResolvers(),this.#Ln)throw new Error("#initScripting: Scripting already exists.");return this.#r.createScripting()}async#xn(){if(!this.#Ln)return this.#Pn=null,void this.#Cn?.resolve();this.#Sn&&(await Promise.race([this.#Sn.promise,new Promise((e=>{setTimeout(e,1e3)}))]).catch((()=>{})),this.#Sn=null),this.#Pn=null;try{await this.#Ln.destroySandbox()}catch{}this.#In?.reject(new Error("Scripting destroyed.")),this.#In=null,this.#$i?.abort(),this.#$i=null,this._pageOpenPending.clear(),this._visitedPages.clear(),this.#Ln=null,this.#_n=!1,this.#Cn?.resolve()}}class PdfTextExtractor{#An;#r;#Rn;#On=new Set;constructor(e){this.#r=e,window.addEventListener("requestTextContent",(({detail:e})=>{this.extractTextContent(e.requestId)}))}setViewer(e){if(this.#An=e,this.#An&&this.#On.size){for(const e of this.#On)this.extractTextContent(e);this.#On.clear()}}async extractTextContent(e){if(this.#An){if(!this.#Rn){const e=this.#Rn=this.#An.getAllText();e.then((()=>{setTimeout((()=>{this.#Rn===e&&(this.#Rn=null)}),5e3)}))}this.#r.reportText({text:await this.#Rn,requestId:e})}else this.#On.add(e)}}class Menu{#kn;#Fn;#Vn;#jn=null;#Un=new AbortController;#Hn=-1;constructor(e,t,i){if(this.#Fn=e,this.#kn=t,Array.isArray(i))this.#Vn=i;else{this.#Vn=[];for(const e of this.#Fn.querySelectorAll("button"))this.#Vn.push(e)}this.#zn()}#Wn(){if(!this.#jn)return;const e=this.#Fn;this.#kn.ariaExpanded="false",this.#jn.abort(),this.#jn=null,e.contains(document.activeElement)&&setTimeout((()=>{e.contains(document.activeElement)||this.#kn.focus()}),0),this.#Hn=-1}#zn(){this.#kn.addEventListener("click",(e=>{if(this.#jn)return void this.#Wn();const t=this.#Fn;this.#kn.ariaExpanded="true",this.#jn=new AbortController;const i=AbortSignal.any([this.#Un.signal,this.#jn.signal]);window.addEventListener("pointerdown",(({target:e})=>{e===this.#kn||t.contains(e)||this.#Wn()}),{signal:i}),window.addEventListener("blur",this.#Wn.bind(this),{signal:i})}));const{signal:e}=this.#Un;this.#Fn.addEventListener("keydown",(e=>{switch(e.key){case"Escape":this.#Wn(),stopEvent(e);break;case"ArrowDown":case"Tab":this.#Kn(e.target,!0),stopEvent(e);break;case"ArrowUp":case"ShiftTab":this.#Kn(e.target,!1),stopEvent(e);break;case"Home":this.#Vn.find((e=>!e.disabled&&!e.classList.contains("hidden"))).focus(),stopEvent(e);break;case"End":this.#Vn.findLast((e=>!e.disabled&&!e.classList.contains("hidden"))).focus(),stopEvent(e);break;default:const t=e.key.toLocaleLowerCase();this.#Kn(e.target,!0,(e=>e.textContent.trim().toLowerCase().startsWith(t))),stopEvent(e)}}),{signal:e,capture:!0}),this.#Fn.addEventListener("contextmenu",noContextMenu,{signal:e}),this.#Fn.addEventListener("click",this.#Wn.bind(this),{signal:e,capture:!0}),this.#kn.addEventListener("keydown",(e=>{switch(e.key){case" ":case"Enter":case"ArrowDown":case"Home":this.#jn||this.#kn.click(),this.#Vn.find((e=>!e.disabled&&!e.classList.contains("hidden"))).focus(),stopEvent(e);break;case"ArrowUp":case"End":this.#jn||this.#kn.click(),this.#Vn.findLast((e=>!e.disabled&&!e.classList.contains("hidden"))).focus(),stopEvent(e);break;case"Escape":this.#Wn(),stopEvent(e)}}),{signal:e})}#Kn(e,t,i=(()=>!0)){const n=-1===this.#Hn?this.#Vn.indexOf(e):this.#Hn,s=this.#Vn.length,a=t?1:s-1;for(let e=(n+a)%s;e!==n;e=(e+a)%s){const t=this.#Vn[e];if(!t.disabled&&!t.classList.contains("hidden")&&i(t)){t.focus(),this.#Hn=e;break}}}destroy(){this.#Wn(),this.#Un?.abort(),this.#Un=null}}const DRAW_UPSCALE_FACTOR=2,MAX_NUM_SCALING_STEPS=3,THUMBNAIL_WIDTH=126;class TempImageFactory{static getCanvas(e,t){let i;FeatureTest.isOffscreenCanvasSupported?i=new OffscreenCanvas(e,t):(i=document.createElement("canvas"),i.width=e,i.height=t);const n=i.getContext("2d",{alpha:!1});return n.save(),n.fillStyle="rgb(255, 255, 255)",n.fillRect(0,0,e,t),n.restore(),[i,n]}}class PDFThumbnailView{constructor({container:e,eventBus:t,id:i,defaultViewport:n,optionalContentConfigPromise:s,linkService:a,renderingQueue:o,maxCanvasPixels:r,maxCanvasDim:l,pageColors:d,enableSplitMerge:h=!1}){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.maxCanvasPixels=r??AppOptions.get("maxCanvasPixels"),this.maxCanvasDim=l||AppOptions.get("maxCanvasDim"),this.pageColors=d||null,this.eventBus=t,this.linkService=a,this.renderingQueue=o,this.renderTask=null,this.renderingState=RenderingStates.INITIAL,this.resume=null,this.placeholder=null;const c=this.div=document.createElement("div");if(c.className="thumbnail",c.setAttribute("page-number",i),c.setAttribute("page-id",i),h){const e=this.checkbox=document.createElement("input");e.type="checkbox",e.tabIndex=-1,c.append(e)}const u=this.image=document.createElement("img");u.classList.add("thumbnailImage","missingThumbnailImage"),u.role="button",u.tabIndex=-1,u.draggable=!1,this.#$n(),c.append(u),e.append(c)}updateId(e){this.id=e,this.renderingId=`thumbnail${e}`,this.div.setAttribute("page-number",e),this.setPageLabel(this.pageLabel)}#$n(){const{width:e,height:t}=this.viewport,i=e/t,n=this.canvasWidth=126,s=this.canvasHeight=n/i|0;this.scale=n/e,this.image.style.height=`${s}px`}setPdfPage(e){this.pdfPage=e,this.pdfPageRotate=e.rotate;const t=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport({scale:1,rotation:t}),this.reset()}reset(){this.cancelRendering(),this.renderingState=RenderingStates.INITIAL,this.#$n();const{image:e}=this,t=e.src;t&&(URL.revokeObjectURL(t),e.removeAttribute("data-l10n-id"),e.removeAttribute("data-l10n-args"),e.src="",this.image.classList.add("missingThumbnailImage"))}update({rotation:e=null}){"number"==typeof e&&(this.rotation=e);const t=(this.rotation+this.pdfPageRotate)%360;this.viewport=this.viewport.clone({scale:1,rotation:t}),this.reset()}toggleCurrent(e){e?(this.image.ariaCurrent="page",this.image.tabIndex=0):(this.image.ariaCurrent=!1,this.image.tabIndex=-1)}cancelRendering(){this.renderTask&&(this.renderTask.cancel(),this.renderTask=null),this.resume=null}#Gn(e=1){const t=new OutputScale,i=e*this.canvasWidth,n=e*this.canvasHeight;t.limitCanvas(i,n,this.maxCanvasPixels,this.maxCanvasDim);const s=document.createElement("canvas");s.width=i*t.sx|0,s.height=n*t.sy|0;return{canvas:s,transform:t.scaled?[t.sx,0,0,t.sy,0,0]:null}}async#Xn(e){if(this.renderingState!==RenderingStates.FINISHED)throw new Error("#convertCanvasToImage: Rendering has not finished.");const t=this.#Yn(e),{image:i}=this,{promise:n,resolve:s}=Promise.withResolvers();t.toBlob(s);const a=await n;i.src=URL.createObjectURL(a),i.setAttribute("data-l10n-id","pdfjs-thumb-page-canvas"),i.setAttribute("data-l10n-args",this.#Zn),i.classList.remove("missingThumbnailImage"),FeatureTest.isOffscreenCanvasSupported||(t.width=t.height=0)}async draw(){if(this.renderingState!==RenderingStates.INITIAL)return void console.error("Must be in new state before drawing");const{pageColors:e,pdfPage:t}=this;if(!t)throw this.renderingState=RenderingStates.FINISHED,new Error("pdfPage is not loaded");this.renderingState=RenderingStates.RUNNING;const{canvas:i,transform:n}=this.#Gn(2),s={canvas:i,transform:n,viewport:this.viewport.clone({scale:2*this.scale}),optionalContentConfigPromise:this._optionalContentConfigPromise,pageColors:e},a=this.renderTask=t.render(s);a.onContinue=e=>{if(!this.renderingQueue.isHighestPriority(this))return this.renderingState=RenderingStates.PAUSED,void(this.resume=()=>{this.renderingState=RenderingStates.RUNNING,e()});e()};let o=null;try{await a.promise}catch(e){if(e instanceof RenderingCancelledException)return;o=e}finally{a===this.renderTask&&(this.renderTask=null)}if(this.renderingState=RenderingStates.FINISHED,await this.#Xn(i),this.eventBus.dispatch("thumbnailrendered",{source:this,pageNumber:this.id,pdfPage:t}),o)throw o}setImage(e){if(this.renderingState!==RenderingStates.INITIAL)return;const{thumbnailCanvas:t,pdfPage:i,scale:n}=e;t&&(this.pdfPage||this.setPdfPage(i),n<this.scale||(this.renderingState=RenderingStates.FINISHED,this.#Xn(t)))}#qn(e){const t=e.width<<3,i=e.height<<3,n=new OutputScale;return n.sx=n.sy=1,n.limitCanvas(t,i,this.maxCanvasPixels,this.maxCanvasDim),[t*n.sx|0,i*n.sy|0]}#Yn(e){const{canvas:t}=this.#Gn(1),i=t.getContext("2d",{alpha:!1,willReadFrequently:!1});if(e.width<=2*t.width)return i.drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),t;let[n,s]=this.#qn(t);const[a,o]=TempImageFactory.getCanvas(n,s);for(;n>e.width||s>e.height;)n>>=1,s>>=1;for(o.drawImage(e,0,0,e.width,e.height,0,0,n,s);n>2*t.width;)o.drawImage(a,0,0,n,s,0,0,n>>1,s>>1),n>>=1,s>>=1;return i.drawImage(a,0,0,n,s,0,0,t.width,t.height),t}get#Zn(){return JSON.stringify({page:this.pageLabel??this.id})}setPageLabel(e){this.pageLabel="string"==typeof e?e:null,this.image.setAttribute("data-l10n-args",this.#Zn)}}const SCROLL_OPTIONS={behavior:"instant",block:"nearest",inline:"nearest",container:"nearest"},DRAG_THRESHOLD_IN_PIXELS=5,PIXELS_TO_SCROLL_WHEN_DRAGGING=20,SPACE_FOR_DRAG_MARKER_WHEN_NO_NEXT_ELEMENT=15;class PDFThumbnailViewer{static#Qn=0;#Jn=!1;#es=null;#ts=null;#is=null;#ns=NaN;#ss=null;#as=0;#os=0;#rs=0;#ls=0;#ds=0;#hs=0;#cs=null;#us=NaN;#gs=0;#ps=0;#ms=PagesMapper.instance;#fs=null;constructor({container:e,eventBus:t,linkService:i,renderingQueue:n,maxCanvasPixels:s,maxCanvasDim:a,pageColors:o,abortSignal:r,enableHWA:l,enableSplitMerge:d,manageMenu:h}){if(this.scrollableContainer=e.parentElement,this.container=e,this.eventBus=t,this.linkService=i,this.renderingQueue=n,this.maxCanvasPixels=s,this.maxCanvasDim=a,this.pageColors=o||null,this.enableHWA=l||!1,this.#Jn=d||!1,this.#Jn&&h){const{button:e,menu:t,copy:i,cut:n,delete:s,saveAs:a}=h;this._manageMenu=new Menu(t,e,[i,n,s,a]),this.#fs=a,a.addEventListener("click",(()=>{this.eventBus.dispatch("savepageseditedpdf",{source:this,data:this.#ms.getPageMappingForSaving()})}))}else h.button.hidden=!0;this.scroll=watchScroll(this.scrollableContainer,this.#bs.bind(this),r),this.#vs(),this.#mi()}#bs(){this.renderingQueue.renderHighestPriority()}getThumbnail(e){return this._thumbnails[e]}#ws(){return getVisibleElements({scrollEl:this.scrollableContainer,views:this._thumbnails})}scrollThumbnailIntoView(e){if(!this.pdfDocument)return;const t=this._thumbnails[e-1];if(!t)return void console.error(\'scrollThumbnailIntoView: Invalid "pageNumber" parameter.\');if(e!==this._currentPageNumber){this._thumbnails[this._currentPageNumber-1].toggleCurrent(!1),t.toggleCurrent(!0),this._currentPageNumber=e}const{first:i,last:n,views:s}=this.#ws();if(s.length>0){let a=!1;if(e<=this.#ms.getPageNumber(i.id)||e>=this.#ms.getPageNumber(n.id))a=!0;else for(const{id:t,percent:i}of s){if(this.#ms.getPageNumber(t)===e){a=i<100;break}}a&&t.div.scrollIntoView(SCROLL_OPTIONS)}this._currentPageNumber=e}get pagesRotation(){return this._pagesRotation}set pagesRotation(e){if(!isValidRotation(e))throw new Error("Invalid thumbnails rotation angle.");if(!this.pdfDocument)return;if(this._pagesRotation===e)return;this._pagesRotation=e;const t={rotation:e};for(const e of this._thumbnails)e.update(t)}cleanup(){for(const e of this._thumbnails)e.renderingState!==RenderingStates.FINISHED&&e.reset()}#vs(){this._thumbnails=[],this._currentPageNumber=1,this._pageLabels=null,this._pagesRotation=0,this.container.textContent=""}setDocument(e){if(this.pdfDocument&&(this.#Es(),this.#vs()),this.pdfDocument=e,!e)return;const t=e.getPage(1),i=e.getOptionalContentConfig({intent:"display"});t.then((t=>{const n=e.numPages,s=t.getViewport({scale:1}),a=document.createDocumentFragment();for(let e=1;e<=n;++e){const t=new PDFThumbnailView({container:a,eventBus:this.eventBus,id:e,defaultViewport:s.clone(),optionalContentConfigPromise:i,linkService:this.linkService,renderingQueue:this.renderingQueue,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,pageColors:this.pageColors,enableHWA:this.enableHWA,enableSplitMerge:this.#Jn});this._thumbnails.push(t)}this._thumbnails[0]?.setPdfPage(t);this._thumbnails[this._currentPageNumber-1].toggleCurrent(!0),this.container.append(a)})).catch((e=>{console.error("Unable to initialize thumbnail viewer",e)}))}#Es(){for(const e of this._thumbnails)e.cancelRendering()}setPageLabels(e){if(this.pdfDocument){e?Array.isArray(e)&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("PDFThumbnailViewer_setPageLabels: Invalid page labels.")):this._pageLabels=null;for(let e=0,t=this._thumbnails.length;e<t;e++)this._thumbnails[e].setPageLabel(this._pageLabels?.[e]??null)}}async#ys(e){if(e.pdfPage)return e.pdfPage;try{const t=await this.pdfDocument.getPage(e.id);return e.pdfPage||e.setPdfPage(t),t}catch(e){return console.error("Unable to get page for thumb view",e),null}}#Ss(e){return 1===e.first?.id||e.last?.id!==this._thumbnails.length&&this.scroll.down}forceRendering(){const e=this.#ws(),t=this.#Ss(e),i=this.renderingQueue.getHighestPriority(e,this._thumbnails,t,!1,!0);return!!i&&(this.#ys(i).then((()=>{this.renderingQueue.renderView(i)})),!0)}static#Cs(e){return PDFThumbnailViewer.#Qn||=parseFloat(getComputedStyle(e).getPropertyValue("--thumbnail-dragging-scale"))}#Ts(){const e=this.#ms;this.container.replaceChildren();const t=this._thumbnails,i=this._thumbnails=[],n=document.createDocumentFragment();for(let s=0,a=e.pagesNumber;s<a;s++){const a=e.getPrevPageNumber(s+1)-1;if(-1===a)continue;const o=t[a];i.push(o),o.updateId(s+1),o.checkbox.checked=!1,n.append(o.div)}this.container.append(n)}#Ps(e){this.#ps=this.scrollableContainer.scrollTop,this.#gs=this.#ps+this.scrollableContainer.clientHeight,this.#es=new AbortController,this.container.classList.add("isDragging");const t=parseInt(e.getAttribute("page-number"),10);this.#ns=t-1,this.#ss?.has(t)||(this.#us=t,this.#As(t,!0));for(const e of this.#ss){const i=this._thumbnails[e-1],n=i.placeholder=document.createElement("div");n.classList.add("thumbnailImage","placeholder");const{div:s,image:a}=i;if(s.classList.add("isDragging"),n.style.height=getComputedStyle(a).height,a.after(n),e!==t){a.classList.add("hidden");continue}if(1===this.#ss.size){a.classList.add("draggingThumbnail"),this.#ts=a;continue}const o=this.#ts=document.createElement("div");o.classList.add("draggingThumbnail","thumbnailImage","multiple"),o.style.height=getComputedStyle(a).height,a.replaceWith(o),a.classList.remove("thumbnailImage"),o.append(a),o.setAttribute("data-multiple-count",this.#ss.size)}}#_s(e=!1){const t=this.#ts;this.#ts=null;const i=this.#ns;this.#ns=NaN,this.#cs?.remove(),this.#cs=null,this.#es.abort(),this.#es=null,this.container.classList.remove("isDragging");for(const e of this.#ss){const t=this._thumbnails[e-1],{div:i,placeholder:n,image:s}=t;n.remove(),s.classList.remove("draggingThumbnail","hidden"),i.classList.remove("isDragging")}if(t.classList.contains("multiple")){const e=t.firstElementChild;t.replaceWith(e),e.classList.add("thumbnailImage")}else t.style.translate="";const n=this.#ss;if(!isNaN(i)&&e&&(1!==n.size||!n.has(i+1)&&!n.has(i+2))){const e=i+1,t=Array.from(n).sort(((e,t)=>e-t)),s=this.#ms,a=s.getPageId(this._currentPageNumber),o=s.getPageId(isNaN(this.#us)?t[0]:this.#us);this.eventBus.dispatch("beforepagesedited",{source:this,pagesMapper:s}),s.movePages(n,t,e),this.#Ts(),this._currentPageNumber=s.getPageNumber(a),this.#Ls(),n.clear(),this.#us=NaN;(this.#fs.disabled=!this.#ms.hasBeenAltered())||this.eventBus.dispatch("pagesedited",{source:this,pagesMapper:s,index:e,pagesToMove:t});const r=s.getPageNumber(o);setTimeout((()=>{this.linkService.goToPage(r)}),0)}isNaN(this.#us)||(this.#As(this.#us,!1),this.#us=NaN)}#Is(e,t){this.#ds+=e,this.#hs+=t,this.#as+=e,this.#os+=t,this.#ts.style.translate=`${this.#ds}px ${this.#hs}px`,this.#os+this.#ls>this.#gs?this.scrollableContainer.scrollTop=Math.min(this.scrollableContainer.scrollTop+20,this.scrollableContainer.scrollHeight):this.#os<this.#ps&&(this.scrollableContainer.scrollTop=Math.max(this.scrollableContainer.scrollTop-20,0));const i=this.#xs(this.#as+this.#rs/2,this.#os+this.#ls/2);if(!i)return;let n=this.#cs;n||(n=this.#cs=document.createElement("div"),n.className="dragMarker",this.container.firstChild.before(n));const[s,a]=i,o=n.style,{bbox:r,x:l}=this.#is;let d,h,c,u;s<0?1===l.length?(h=r[1]-15,d=r[4],c=r[2]):(h=r[1],d=r[0]-15,u=r[3]):1===l.length?(h=r[4*s+1]+r[4*s+3]+a,d=r[4*s],c=r[4*s+2]):(h=r[4*s+1],d=r[4*s]+r[4*s+2]+a,u=r[4*s+3]),o.translate=`${d}px ${h}px`,o.width=c?`${c}px`:"",o.height=u?`${u}px`:""}#Ls(){const e=[],t=[],i=[],n=new Float32Array(4*this._thumbnails.length);let s,a,o,r=-1/0,l=-1/0,d=-1;for(let h=0,c=this._thumbnails.length;h<c;h++){const{div:u}=this._thumbnails[h],{offsetTop:g,offsetLeft:p,offsetWidth:m,offsetHeight:f}=u;if(0===m)return;if(n[4*h]=p,n[4*h+1]=g,n[4*h+2]=m,n[4*h+3]=f,p>r&&(r=p+m/2,s??=r+m,e.push(r)),d>0&&h>=c-d){const e=p+m/2;i.push(e),a??=e+m}g>l&&(-1===d&&e.length>1&&(d=c%e.length),l=g+f/2,o??=l+f,t.push(l))}const h=e.length>1?(e[1]-s)/2:(t[1]-o)/2;this.#is={x:e,y:t,lastX:i,space:h,lastSpace:(i.at(-1)-a)/2,bbox:n}}#mi(){this.eventBus.on("resize",(({source:e})=>{e.thumbnailsView===this.container&&this.#Ls()})),this.container.addEventListener("keydown",(e=>{switch(e.key){case"ArrowLeft":this.#Kn(e.target,!1,!0),stopEvent(e);break;case"ArrowRight":this.#Kn(e.target,!0,!0),stopEvent(e);break;case"ArrowDown":this.#Kn(e.target,!0,!1),stopEvent(e);break;case"ArrowUp":this.#Kn(e.target,!1,!1),stopEvent(e);break;case"Home":this._thumbnails[0].image.focus(),stopEvent(e);break;case"End":this._thumbnails.at(-1).image.focus(),stopEvent(e);break;case"Enter":case" ":this.#Ms(e)}})),this.container.addEventListener("click",(e=>{const{target:t}=e;if(t instanceof HTMLInputElement){const e=parseInt(t.parentElement.getAttribute("page-number"),10);this.#As(e,t.checked)}else this.#Ms(e)})),this.#Ns()}#As(e,t){const i=this.#ss??=new Set;t?i.add(e):i.delete(e)}#Ns(){this.#Jn&&this.container.addEventListener("pointerdown",(e=>{const{target:t,clientX:i,clientY:n,pointerId:s}=e;if(!isNaN(this.#ns)||!t.classList.contains("thumbnailImage"))return;const a=t.parentElement,o=new AbortController,{signal:r}=o;let l=i,d=n,h=this.scrollableContainer.scrollTop;const c=PDFThumbnailViewer.#Cs(t);this.#ds=((c-1)*e.layerX+t.offsetLeft)/c,this.#hs=((c-1)*e.layerY+t.offsetTop)/c,this.#as=a.offsetLeft+this.#ds,this.#os=a.offsetTop+this.#hs,this.#rs=t.offsetWidth/c,this.#ls=t.offsetHeight/c,this.container.addEventListener("pointermove",(e=>{const{clientX:t,clientY:r,pointerId:c}=e;if(c!==s||Math.abs(t-i)<=5&&Math.abs(r-n)<=5)return;if(isNaN(this.#ns)){this.#Ps(a);const e=(e,t=!1)=>{this.#_s(t),o.abort()},{signal:t}=this.#es;window.addEventListener("touchmove",stopEvent,{passive:!1,signal:t}),window.addEventListener("contextmenu",noContextMenu,{signal:t}),this.scrollableContainer.addEventListener("scrollend",(()=>{const{scrollableContainer:{clientHeight:e,scrollTop:t}}=this;this.#ps=t,this.#gs=t+e;const i=t-h;h=t,this.#Is(0,i)}),{passive:!0,signal:t}),window.addEventListener("pointerup",(i=>{i.pointerId===s&&(window.addEventListener("click",stopEvent,{capture:!0,once:!0,signal:t}),stopEvent(i),e(i,!0))}),{signal:t}),window.addEventListener("blur",e,{signal:t}),window.addEventListener("pointercancel",e,{signal:t}),window.addEventListener("wheel",stopEvent,{passive:!1,signal:t})}const u=t-l,g=r-d;l=t,d=r,this.#Is(u,g)}),{passive:!0,signal:r}),window.addEventListener("pointerup",(({pointerId:e})=>{e===s&&o.abort()}),{signal:r}),window.addEventListener("dragstart",stopEvent,{capture:!0,signal:r})}))}#Ms(e){const{target:t}=e;if(t.classList.contains("thumbnailImage")){const i=parseInt(t.parentElement.getAttribute("page-number"),10);this.linkService.goToPage(i),stopEvent(e)}}#Kn(e,t,i){let n=parseInt(e.parentElement.getAttribute("page-number"),10);isNaN(n)&&(n=this._currentPageNumber);const s=t?1:-1;let a;if(i){const e=MathClamp(n+s,1,this._thumbnails.length+1);a=this._thumbnails[e-1]}else{const e=this._thumbnails[n-1],{x:t,y:i}=e.div.getBoundingClientRect();let o;for(let e=n-1+s;e>=0&&e<this._thumbnails.length;e+=s){const n=this._thumbnails[e],{x:s,y:r}=n.div.getBoundingClientRect();if(o||r===i||(o=n),s===t){a=n;break}}a||(a=o)}a&&a.image.focus()}#xs(e,t){this.#is||this.#Ls();const{x:i,y:n,lastX:s,space:a,lastSpace:o}=this.#is,r=this.#ns;let l=r%i.length,d=Math.floor(r/i.length),h=d===n.length-1?s:i;if(n[d]<=t&&t<(n[d+1]??1/0)&&h[l]<=e&&e<(h[l+1]??1/0))return null;d=binarySearchFirstItem(n,(e=>t<e))-1,h=d===n.length-1&&s.length>0?s:i,l=Math.max(0,binarySearchFirstItem(h,(t=>e<t))-1),d<0&&(l<=0&&(l=-1),d=0);const c=MathClamp(d*i.length+l,-1,this._thumbnails.length-1);if(c===r)return null;this.#ns=c;return[c,d===n.length-1&&s.length>0&&l>=0?o:a]}}class AnnotationEditorLayerBuilder{#Ds=null;#Bs=null;#Rs=null;#Os=null;#ks=null;#Z;constructor(e){this.pdfPage=e.pdfPage,this.accessibilityManager=e.accessibilityManager,this.l10n=e.l10n,this.l10n||=new genericl10n_GenericL10n,this.annotationEditorLayer=null,this.div=null,this._cancelled=!1,this.#Z=e.uiManager,this.#Ds=e.annotationLayer||null,this.#ks=e.textLayer||null,this.#Bs=e.drawLayer||null,this.#Rs=e.onAppend||null,this.#Os=e.structTreeLayer||null}async render({viewport:e,intent:t="display"}){if("display"!==t)return;if(this._cancelled)return;const i=e.clone({dontFlip:!0});if(this.div)return this.annotationEditorLayer.update({viewport:i}),void this.show();const n=this.div=document.createElement("div");n.className="annotationEditorLayer",n.hidden=!0,n.dir=this.#Z.direction,this.#Rs?.(n),this.annotationEditorLayer=new AnnotationEditorLayer({uiManager:this.#Z,div:n,structTreeLayer:this.#Os,accessibilityManager:this.accessibilityManager,pageIndex:this.pdfPage.pageNumber-1,l10n:this.l10n,viewport:i,annotationLayer:this.#Ds,textLayer:this.#ks,drawLayer:this.#Bs});const s={viewport:i,div:n,annotations:null,intent:t};this.annotationEditorLayer.render(s),this.show()}cancel(){this._cancelled=!0,this.div&&this.annotationEditorLayer.destroy()}hide(){this.div&&(this.annotationEditorLayer.pause(!0),this.div.hidden=!0)}show(){this.div&&!this.annotationEditorLayer.isInvisible&&(this.div.hidden=!1,this.annotationEditorLayer.pause(!1))}}class AnnotationLayerBuilder{#rt=null;#Fs=null;#Vs=!1;#Rs=null;#$i=null;#js=!1;constructor({pdfPage:e,linkService:t,downloadManager:i,annotationStorage:n=null,imageResourcesPath:s="",renderForms:a=!0,enableComment:o=!1,commentManager:r=null,enableScripting:l=!1,hasJSActionsPromise:d=null,fieldObjectsPromise:h=null,annotationCanvasMap:c=null,accessibilityManager:u=null,annotationEditorUIManager:g=null,onAppend:p=null}){this.pdfPage=e,this.linkService=t,this.downloadManager=i,this.imageResourcesPath=s,this.renderForms=a,this.annotationStorage=n,this.enableComment=o,this.#Fs=r,this.enableScripting=l,this._hasJSActionsPromise=d||Promise.resolve(!1),this._fieldObjectsPromise=h||Promise.resolve(null),this._annotationCanvasMap=c,this._accessibilityManager=u,this._annotationEditorUIManager=g,this.#Rs=p,this.annotationLayer=null,this.div=null,this._cancelled=!1,this._eventBus=t.eventBus}async render({viewport:e,intent:t="display",structTreeLayer:i=null}){if(this.div){if(this._cancelled||!this.annotationLayer)return;return void this.annotationLayer.update({viewport:e.clone({dontFlip:!0})})}const[n,s,a]=await Promise.all([this.pdfPage.getAnnotations({intent:t}),this._hasJSActionsPromise,this._fieldObjectsPromise]);if(this._cancelled)return;const o=this.div=document.createElement("div");if(o.className="annotationLayer",this.#Rs?.(o),this.#Us(e,i),0===n.length)return this.#rt=n,void setLayerDimensions(this.div,e);await this.annotationLayer.render({annotations:n,imageResourcesPath:this.imageResourcesPath,renderForms:this.renderForms,downloadManager:this.downloadManager,enableComment:this.enableComment,enableScripting:this.enableScripting,hasJSActions:s,fieldObjects:a}),this.#rt=n,this.linkService.isInPresentationMode&&this.#Hs(PresentationModeState.FULLSCREEN),this.#$i||(this.#$i=new AbortController,this._eventBus?._on("presentationmodechanged",(e=>{this.#Hs(e.state)}),{signal:this.#$i.signal}))}#Us(e,t){this.annotationLayer=new AnnotationLayer({div:this.div,accessibilityManager:this._accessibilityManager,annotationCanvasMap:this._annotationCanvasMap,annotationEditorUIManager:this._annotationEditorUIManager,annotationStorage:this.annotationStorage,page:this.pdfPage,viewport:e.clone({dontFlip:!0}),structTreeLayer:t,commentManager:this.#Fs,linkService:this.linkService})}cancel(){this._cancelled=!0,this.#$i?.abort(),this.#$i=null}hide(e=!1){this.#Vs=!e,this.div&&(this.div.hidden=!0)}hasEditableAnnotations(){return!!this.annotationLayer?.hasEditableAnnotations()}async injectLinkAnnotations(e){if(null===this.#rt)throw new Error("`render` method must be called before `injectLinkAnnotations`.");if(this._cancelled||this.#js)return;this.#js=!0;const t=this.#rt.length?this.#zs(e):e;t.length&&(await this.annotationLayer.addLinkAnnotations(t),this.#Vs||(this.div.hidden=!1))}#Hs(e){if(!this.div)return;let t=!1;switch(e){case PresentationModeState.FULLSCREEN:t=!0;break;case PresentationModeState.NORMAL:break;default:return}for(const e of this.div.childNodes)e.hasAttribute("data-internal-link")||(e.inert=t)}#zs(e){function t(e){if(!e.quadPoints)return[e.rect];const t=[];for(let i=2,n=e.quadPoints.length;i<n;i+=8){const n=e.quadPoints[i],s=e.quadPoints[i+1],a=e.quadPoints[i+2],o=e.quadPoints[i+3];t.push([a,o,n,s])}return t}function i(e,i){const n=[],s=t(e),a=t(i);for(const e of s)for(const t of a){const i=Util.intersect(e,t);i&&n.push(i)}return n}function n(e){let t=0;for(const i of e)t+=Math.abs((i[2]-i[0])*(i[3]-i[1]));return t}return e.filter((e=>{let s;for(const a of this.#rt){if(a.annotationType!==AnnotationType.LINK||!a.url)continue;const o=i(a,e);if(0!==o.length&&(s??=n(t(e)),n(o)/s>.5))return!1}return!0}))}}function DOMRectToPDF({width:e,height:t,left:i,top:n},s){if(0===e||0===t)return null;const a=s.textLayer.div.getBoundingClientRect(),o=s.getPagePoint(i-a.left,n-a.top),r=s.getPagePoint(i-a.left+e,n-a.top+t);return Util.normalizeRect([o[0],o[1],r[0],r[1]])}function calculateLinkPosition(e,t){const i=e.getClientRects();if(1===i.length)return{rect:DOMRectToPDF(i[0],t)};const n=[1/0,1/0,-1/0,-1/0],s=[];let a=0;for(const e of i){const i=DOMRectToPDF(e,t);null!==i&&(s[a]=s[a+4]=i[0],s[a+1]=s[a+3]=i[3],s[a+2]=s[a+6]=i[2],s[a+5]=s[a+7]=i[1],Util.rectBoundingBox(...i,n),a+=8)}return{quadPoints:s,rect:n}}function textPosition(e,t){let i=e;do{if(i.nodeType===Node.TEXT_NODE){const e=i.textContent.length;if(t<=e)return[i,t];t-=e}else if(i.firstChild){i=i.firstChild;continue}for(;!i.nextSibling&&i!==e;)i=i.parentNode;i!==e&&(i=i.nextSibling)}while(i!==e);throw new Error("Offset is bigger than container\'s contents length.")}function createLinkAnnotation({url:e,index:t,length:i},n,s){const a=n._textHighlighter,[{begin:o,end:r}]=a._convertMatches([t],[i]),l=new Range;return l.setStart(...textPosition(a.textDivs[o.divIdx],o.offset)),l.setEnd(...textPosition(a.textDivs[r.divIdx],r.offset)),{id:`inferred_link_${s}`,unsafeUrl:e,url:e,annotationType:AnnotationType.LINK,rotation:0,...calculateLinkPosition(l,n),borderStyle:null}}class Autolinker{static#Ws=0;static#Ks;static#$s;static findLinks(e){this.#Ks??=/\\b(?:https?:\\/\\/|mailto:|www\\.)(?:[\\S--[\\p{P}<>]]|\\/|[\\S--[\\[\\]]]+[\\S--[\\p{P}<>]])+|(?=\\p{L})[\\S--[@\\p{Ps}\\p{Pe}<>]]+@([\\S--[[\\p{P}--\\-]<>]]+(?:\\.[\\S--[[\\p{P}--\\-]<>]]+)+)/gmv;const[t,i]=normalize(e,{ignoreDashEOL:!0}),n=t.matchAll(this.#Ks),s=[];for(const e of n){const[t,n]=e;let a;if(t.startsWith("www.")||t.startsWith("http://")||t.startsWith("https://"))a=t;else if(n){const e=URL.parse(`http://${n}`)?.hostname;if(!e)continue;if(this.#$s??=/\\.\\d+$/,this.#$s.test(e))continue}a??=t.startsWith("mailto:")?t:`mailto:${t}`;const o=createValidAbsoluteUrl(a,null,{addDefaultProtocol:!0});if(o){const[n,a]=getOriginalIndex(i,e.index,t.length);s.push({url:o.href,index:n,length:a})}}return s}static processLinks(e){return this.findLinks(e._textHighlighter.textContentItemsStr.join("\\n")).map((t=>createLinkAnnotation(t,e,this.#Ws++)))}}class BasePDFPageView{#Gs=null;#Xs=0;#Ys=null;#Zs=RenderingStates.INITIAL;#qs=null;#Qs=0;#Js=null;canvas=null;div=null;enableOptimizedPartialRendering=!1;eventBus=null;id=null;pageColors=null;recordedBBoxes=null;renderingQueue=null;renderTask=null;resume=null;constructor(e){this.eventBus=e.eventBus,this.id=e.id,this.pageColors=e.pageColors||null,this.renderingQueue=e.renderingQueue,this.enableOptimizedPartialRendering=e.enableOptimizedPartialRendering??!1,this.#Xs=e.minDurationToUpdateCanvas??500}get renderingState(){return this.#Zs}set renderingState(e){if(e!==this.#Zs)switch(this.#Zs=e,this.#Gs&&(clearTimeout(this.#Gs),this.#Gs=null),e){case RenderingStates.PAUSED:this.div.classList.remove("loading"),this.#Qs=0,this.#qs?.(!1);break;case RenderingStates.RUNNING:this.div.classList.add("loadingIcon"),this.#Gs=setTimeout((()=>{this.div.classList.add("loading"),this.#Gs=null}),0),this.#Qs=Date.now();break;case RenderingStates.INITIAL:case RenderingStates.FINISHED:this.div.classList.remove("loadingIcon","loading"),this.#Qs=0}}_createCanvas(e,t=!1){const{pageColors:i}=this,n=!(!i?.background||!i?.foreground),s=this.canvas,a=!s&&!n&&!t;let o=this.canvas=document.createElement("canvas");return this.#qs=t=>{if(a){let i=this.#Js;if(!t&&this.#Xs>0){if(Date.now()-this.#Qs<this.#Xs)return;i||(i=this.#Js=o,o=this.canvas=o.cloneNode(!1),e(o))}if(i){return o.getContext("2d",{alpha:!1}).drawImage(i,0,0),void(t?this.#ea():this.#Qs=Date.now())}return e(o),void(this.#qs=null)}t&&(s?(s.replaceWith(o),s.width=s.height=0):e(o))},{canvas:o,prevCanvas:s}}#ta=e=>{if(this.#qs?.(!1),this.renderingQueue&&!this.renderingQueue.isHighestPriority(this))return this.renderingState=RenderingStates.PAUSED,void(this.resume=()=>{this.renderingState=RenderingStates.RUNNING,e()});e()};_resetCanvas(){const{canvas:e}=this;e&&(e.remove(),e.width=e.height=0,this.canvas=null,this.#ea())}#ea(){this.#Js&&(this.#Js.width=this.#Js.height=0,this.#Js=null)}async _drawCanvas(e,t,i){const n=this.renderTask=this.pdfPage.render(e);n.onContinue=this.#ta,n.onError=e=>{e instanceof RenderingCancelledException&&(t(),this.#Ys=null)};let s=null;try{await n.promise,this.#qs?.(!0)}catch(e){if(e instanceof RenderingCancelledException)return;s=e,this.#qs?.(!0)}finally{this.#Ys=s,n===this.renderTask&&(this.renderTask=null,this.enableOptimizedPartialRendering&&(this.recordedBBoxes??=n.recordedBBoxes))}if(this.renderingState=RenderingStates.FINISHED,i(n),s)throw s}cancelRendering({cancelExtraDelay:e=0}={}){this.renderTask&&(this.renderTask.cancel(e),this.renderTask=null),this.resume=null}dispatchPageRender(){this.eventBus.dispatch("pagerender",{source:this,pageNumber:this.id})}dispatchPageRendered(e,t){this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:e,isDetailView:t,timestamp:performance.now(),error:this.#Ys})}}class DrawLayerBuilder{#Bs=null;async render({intent:e="display"}){"display"!==e||this.#Bs||this._cancelled||(this.#Bs=new DrawLayer)}cancel(){this._cancelled=!0,this.#Bs&&(this.#Bs.destroy(),this.#Bs=null)}setParent(e){this.#Bs?.setParent(e)}getDrawLayer(){return this.#Bs}}class PDFPageDetailView extends BasePDFPageView{#ia=null;renderingCancelled=!1;constructor({pageView:e}){super(e),this.pageView=e,this.renderingId="detail"+this.id,this.div=e.div}setPdfPage(e){this.pageView.setPdfPage(e)}get pdfPage(){return this.pageView.pdfPage}get renderingState(){return super.renderingState}set renderingState(e){this.renderingCancelled=!1,super.renderingState=e}reset({keepCanvas:e=!1}={}){const t=this.renderingCancelled||this.renderingState===RenderingStates.RUNNING||this.renderingState===RenderingStates.PAUSED;this.cancelRendering(),this.renderingState=RenderingStates.INITIAL,this.renderingCancelled=t,e||this._resetCanvas()}#na(e){if(!this.#ia)return!0;const t=this.#ia.minX,i=this.#ia.minY,n=this.#ia.width+t,s=this.#ia.height+i;if(e.minX<t||e.minY<i||e.maxX>n||e.maxY>s)return!0;const{width:a,height:o,scale:r}=this.pageView.viewport;if(this.#ia.scale!==r)return!0;const l=e.minX-t,d=n-e.maxX,h=e.minY-i,c=s-e.maxY;return t>0&&d/l>3||n<a&&l/d>3||i>0&&c/h>3||s<o&&h/c>3}update({visibleArea:e=null,underlyingViewUpdated:t=!1}={}){if(t)return this.cancelRendering(),void(this.renderingState=RenderingStates.INITIAL);if(!this.#na(e))return;const{viewport:i,maxCanvasPixels:n,capCanvasAreaFactor:s}=this.pageView,a=e.maxX-e.minX,o=e.maxY-e.minY,r=a*o*OutputScale.pixelRatio**2,l=(Math.sqrt(OutputScale.capPixels(n,s)/r)-1)/2;let d=Math.min(1,l);d<0&&(d=0);const h=a*d,c=o*d,u=Math.max(0,e.minX-h),g=Math.min(i.width,e.maxX+h),p=Math.max(0,e.minY-c),m=g-u,f=Math.min(i.height,e.maxY+c)-p;this.#ia={minX:u,minY:p,width:m,height:f,scale:i.scale},this.reset({keepCanvas:!0})}_getRenderingContext(e,t){const i=this.pageView._getRenderingContext(e,t,!1),n=this.pdfPage.recordedBBoxes;if(!n||!this.enableOptimizedPartialRendering)return i;const{viewport:{width:s,height:a}}=this.pageView,{width:o,height:r,minX:l,minY:d}=this.#ia,h=l/s,c=d/a,u=(l+o)/s,g=(d+r)/a;return{...i,operationsFilter:e=>!n.isEmpty(e)&&(n.minX(e)<=u&&n.maxX(e)>=h&&n.minY(e)<=g&&n.maxY(e)>=c)}}async draw(){if(this.pageView.detailView!==this)return;const e=this.pageView.renderingState===RenderingStates.FINISHED||this.renderingState===RenderingStates.FINISHED;this.renderingState!==RenderingStates.INITIAL&&(console.error("Must be in new state before drawing"),this.reset());const{div:t,pdfPage:i,viewport:n}=this.pageView;if(!i)throw this.renderingState=RenderingStates.FINISHED,new Error("pdfPage is not loaded");this.renderingState=RenderingStates.RUNNING;const s=this.pageView._ensureCanvasWrapper(),{canvas:a,prevCanvas:o}=this._createCanvas((e=>{"CANVAS"===s.firstElementChild?.tagName?s.firstElementChild.after(e):s.prepend(e)}),e);a.ariaHidden=!0,this.enableOptimizedPartialRendering&&(a.className="detailView");const{width:r,height:l}=n,d=this.#ia,{pixelRatio:h}=OutputScale,c=[h,0,0,h,-d.minX*h,-d.minY*h];a.width=d.width*h,a.height=d.height*h;const{style:u}=a;u.width=100*d.width/r+"%",u.height=100*d.height/l+"%",u.top=100*d.minY/l+"%",u.left=100*d.minX/r+"%";const g=this._drawCanvas(this._getRenderingContext(a,c),(()=>{this.canvas?.remove(),this.canvas=o}),(()=>{this.dispatchPageRendered(!1,!0)}));return t.setAttribute("data-loaded",!0),this.dispatchPageRender(),g}}const PDF_ROLE_TO_HTML_ROLE={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},MathMLElements=new Set(["math","merror","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mprescripts","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msubsup","msup","mtable","mtd","mtext","mtr","munder","munderover","semantics"]),MathMLNamespace="http://www.w3.org/1998/Math/MathML";class MathMLSanitizer{static get sanitizer(){return shadow(this,"sanitizer",FeatureTest.isSanitizerSupported?new Sanitizer({elements:[...MathMLElements].map((e=>({name:e,namespace:MathMLNamespace}))),replaceWithChildrenElements:[{name:"maction",namespace:MathMLNamespace}],attributes:["dir","displaystyle","mathbackground","mathcolor","mathsize","scriptlevel","encoding","display","linethickness","intent","arg","form","fence","separator","lspace","rspace","stretchy","symmetric","maxsize","minsize","largeop","movablelimits","width","height","depth","voffset","accent","accentunder","columnspan","rowspan"],comments:!1}):null)}}const HEADING_PATTERN=/^H(\\d+)$/;class StructTreeLayerBuilder{#sa;#aa=null;#oa;#ra=new Map;#la;#da=null;#ha=null;#ca=null;constructor(e,t){this.#sa=e.getStructTree(),this.#la=t}async render(){if(this.#oa)return this.#oa;const{promise:e,resolve:t,reject:i}=Promise.withResolvers();this.#oa=e;try{this.#aa=this.#ua(await this.#sa)}catch(e){i(e)}return this.#sa=null,this.#aa?.classList.add("structTree"),t(this.#aa),e}async getAriaAttributes(e){try{return await this.render(),this.#ra.get(e)}catch{}return null}hide(){this.#aa&&!this.#aa.hidden&&(this.#aa.hidden=!0)}show(){this.#aa?.hidden&&(this.#aa.hidden=!1)}#ga(e,t){const{alt:i,id:n,lang:s}=e;if(void 0!==i){let n=!1;const s=removeNullCharacters(i);for(const t of e.children)if("annotation"===t.type){let e=this.#ra.get(t.id);e||(e=new Map,this.#ra.set(t.id,e)),e.set("aria-label",s),n=!0}n||t.setAttribute("aria-label",s)}void 0!==n&&t.setAttribute("aria-owns",n),void 0!==s&&t.setAttribute("lang",removeNullCharacters(s,!0))}#pa(e,t){const{alt:i,bbox:n,children:s}=e,a=s?.[0];if(!this.#la||!i||!n||"content"!==a?.type)return!1;const{id:o}=a;if(!o)return!1;t.setAttribute("aria-owns",o);const r=document.createElement("span");(this.#da||=new Map).set(o,r),r.setAttribute("role","img"),r.setAttribute("aria-label",removeNullCharacters(i));const{pageHeight:l,pageX:d,pageY:h}=this.#la,c="calc(var(--total-scale-factor) *",{style:u}=r;return u.width=`${c}${n[2]-n[0]}px)`,u.height=`${c}${n[3]-n[1]}px)`,u.left=`${c}${n[0]-d}px)`,u.top=`${c}${l-n[3]+h}px)`,!0}updateTextLayer(){if(this.#da){for(const[e,t]of this.#da)document.getElementById(e)?.append(t);this.#da.clear(),this.#da=null}if(this.#ha){for(const e of this.#ha){const t=document.getElementById(e);t&&(t.ariaHidden=!0)}this.#ha.length=0,this.#ha=null}if(this.#ca){for(let e=0,t=this.#ca.length;e<t;e+=2){const t=this.#ca[e],i=this.#ca[e+1];let n="";for(const e of i){const t=document.getElementById(e);t&&(n+=t.textContent.trim()||"",t.ariaHidden="true")}n&&(t.textContent=n)}this.#ca.length=0,this.#ca=null}}#ua(e){if(!e)return null;let t;if("role"in e){const{role:i}=e;if(MathMLElements.has(i)){t=document.createElementNS(MathMLNamespace,i);const n=[];(this.#ca||=[]).push(t,n);for(const{type:t,id:i}of e.children||[])"content"===t&&i&&n.push(i)}else t=document.createElement("span");const n=i.match(HEADING_PATTERN);if(n?(t.setAttribute("role","heading"),t.setAttribute("aria-level",n[1])):PDF_ROLE_TO_HTML_ROLE[i]&&t.setAttribute("role",PDF_ROLE_TO_HTML_ROLE[i]),"Figure"===i&&this.#pa(e,t))return t;if("Formula"===i){if(e.mathML&&MathMLSanitizer.sanitizer){t.setHTML(e.mathML,{sanitizer:MathMLSanitizer.sanitizer});for(const{id:t}of e.children||[])t&&(this.#ha||=[]).push(t);delete e.alt}e.mathML||1!==e.children.length||"math"===e.children[0].role||(t=document.createElementNS(MathMLNamespace,"math"),delete e.alt)}}if(t||=document.createElement("span"),this.#ga(e,t),e.children)if(1===e.children.length&&"id"in e.children[0])this.#ga(e.children[0],t);else for(const i of e.children)t.append(this.#ua(i));return t}}class TextAccessibilityManager{#ma=!1;#fa=null;#ba=new Map;#va=new Map;setTextMapping(e){this.#fa=e}static#wa(e,t){const i=e.getBoundingClientRect(),n=t.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,o=i.y+i.height/2,r=n.y,l=n.y+n.height,d=n.y+n.height/2;if(o<=r&&d>=a)return-1;if(d<=s&&o>=l)return 1;return i.x+i.width/2-(n.x+n.width/2)}enable(){if(this.#ma)throw new Error("TextAccessibilityManager is already enabled.");if(!this.#fa)throw new Error("Text divs and strings have not been set.");if(this.#ma=!0,this.#fa=this.#fa.slice(),this.#fa.sort(TextAccessibilityManager.#wa),this.#ba.size>0){const e=this.#fa;for(const[t,i]of this.#ba){document.getElementById(t)?this.#Ea(t,e[i]):this.#ba.delete(t)}}for(const[e,t]of this.#va)this.addPointerInTextLayer(e,t);this.#va.clear()}disable(){this.#ma&&(this.#va.clear(),this.#fa=null,this.#ma=!1)}removePointerInTextLayer(e){if(!this.#ma)return void this.#va.delete(e);const t=this.#fa;if(!t||0===t.length)return;const{id:i}=e,n=this.#ba.get(i);if(void 0===n)return;const s=t[n];this.#ba.delete(i);let a=s.getAttribute("aria-owns");a?.includes(i)&&(a=a.split(" ").filter((e=>e!==i)).join(" "),a?s.setAttribute("aria-owns",a):(s.removeAttribute("aria-owns"),s.setAttribute("role","presentation")))}#Ea(e,t){const i=t.getAttribute("aria-owns");i?.includes(e)||t.setAttribute("aria-owns",i?`${i} ${e}`:e),t.removeAttribute("role")}addPointerInTextLayer(e,t){const{id:i}=e;if(!i)return null;if(!this.#ma)return this.#va.set(e,t),null;t&&this.removePointerInTextLayer(e);const n=this.#fa;if(!n||0===n.length)return null;const s=binarySearchFirstItem(n,(t=>TextAccessibilityManager.#wa(e,t)<0)),a=Math.max(0,s-1),o=n[a];this.#Ea(i,o),this.#ba.set(i,a);const r=o.parentNode;return r?.classList.contains("markedContent")?r.id:null}moveElementInDOM(e,t,i,n){const s=this.addPointerInTextLayer(i,n);if(!e.hasChildNodes())return e.append(t),s;const a=Array.from(e.childNodes).filter((e=>e!==t));if(0===a.length)return s;const o=binarySearchFirstItem(a,(e=>TextAccessibilityManager.#wa(t,e)<0));return 0===o?a[0].before(t):a[o-1].after(t),s}}class TextHighlighter{#$i=null;constructor({findController:e,eventBus:t,pageIndex:i}){this.findController=e,this.matches=[],this.eventBus=t,this.pageIdx=i,this.textDivs=null,this.textContentItemsStr=null,this.enabled=!1}setTextMapping(e,t){this.textDivs=e,this.textContentItemsStr=t}enable(){if(!this.textDivs||!this.textContentItemsStr)throw new Error("Text divs and strings have not been set.");if(this.enabled)throw new Error("TextHighlighter is already enabled.");this.enabled=!0,this.#$i||(this.#$i=new AbortController,this.eventBus._on("updatetextlayermatches",(e=>{e.pageIndex!==this.pageIdx&&-1!==e.pageIndex||this._updateMatches()}),{signal:this.#$i.signal})),this._updateMatches()}disable(){this.enabled&&(this.enabled=!1,this.#$i?.abort(),this.#$i=null,this._updateMatches(!0))}_convertMatches(e,t){if(!e)return[];const{textContentItemsStr:i}=this;let n=0,s=0;const a=i.length-1,o=[];for(let r=0,l=e.length;r<l;r++){let l=e[r];for(;n!==a&&l>=s+i[n].length;)s+=i[n].length,n++;n===i.length&&console.error("Could not find a matching mapping");const d={begin:{divIdx:n,offset:l-s}};for(l+=t[r];n!==a&&l>s+i[n].length;)s+=i[n].length,n++;d.end={divIdx:n,offset:l-s},o.push(d)}return o}_renderMatches(e){if(0===e.length)return;const{findController:t,pageIdx:i}=this,{textContentItemsStr:n,textDivs:s}=this,a=i===t.selected.pageIdx,o=t.selected.matchIdx;let r=null;const l={divIdx:-1,offset:void 0};function d(e,t){const i=e.divIdx;return s[i].textContent="",h(i,0,e.offset,t)}function h(e,t,i,a){let o=s[e];if(o.nodeType===Node.TEXT_NODE){const t=document.createElement("span");o.before(t),t.append(o),s[e]=t,o=t}const r=n[e].substring(t,i),l=document.createTextNode(r);if(a){const e=document.createElement("span");if(e.className=`${a} appended`,e.append(l),o.append(e),a.includes("selected")){const{left:t}=e.getClientRects()[0];return t-o.getBoundingClientRect().left}return 0}return o.append(l),0}let c=o,u=c+1;if(t.state.highlightAll)c=0,u=e.length;else if(!a)return;let g=-1,p=-1;for(let n=c;n<u;n++){const c=e[n],u=c.begin;if(u.divIdx===g&&u.offset===p)continue;g=u.divIdx,p=u.offset;const m=c.end,f=a&&n===o,b=f?" selected":"";let v=0;if(r&&u.divIdx===r.divIdx?h(r.divIdx,r.offset,u.offset):(null!==r&&h(r.divIdx,r.offset,l.offset),d(u)),u.divIdx===m.divIdx)v=h(u.divIdx,u.offset,m.offset,"highlight"+b);else{v=h(u.divIdx,u.offset,l.offset,"highlight begin"+b);for(let e=u.divIdx+1,t=m.divIdx;e<t;e++)s[e].className="highlight middle"+b;d(m,"highlight end"+b)}r=m,f&&t.scrollMatchIntoView({element:s[u.divIdx],selectedLeft:v,pageIndex:i,matchIndex:o})}r&&h(r.divIdx,r.offset,l.offset)}_updateMatches(e=!1){if(!this.enabled&&!e)return;const{findController:t,matches:i,pageIdx:n}=this,{textContentItemsStr:s,textDivs:a}=this;let o=-1;for(const e of i){for(let t=Math.max(o,e.begin.divIdx),i=e.end.divIdx;t<=i;t++){const e=a[t];e.textContent=s[t],e.className=""}o=e.end.divIdx+1}if(!t?.highlightMatches||e)return;const r=t.pageMatches[n]||null,l=t.pageMatchesLength[n]||null;this.matches=this._convertMatches(r,l),this._renderMatches(this.matches)}}class TextLayerBuilder{#ya=!1;#Rs=null;#Sa=!1;#ks=null;static#Ca=new Map;static#Ta=null;constructor({pdfPage:e,highlighter:t=null,accessibilityManager:i=null,enablePermissions:n=!1,onAppend:s=null}){this.pdfPage=e,this.highlighter=t,this.accessibilityManager=i,this.#ya=!0===n,this.#Rs=s,this.div=document.createElement("div"),this.div.tabIndex=0,this.div.className="textLayer"}async render({viewport:e,textContentParams:t=null}){if(this.#Sa&&this.#ks)return this.#ks.update({viewport:e,onBefore:this.hide.bind(this)}),void this.show();this.cancel(),this.#ks=new TextLayer({textContentSource:this.pdfPage.streamTextContent(t||{includeMarkedContent:!0,disableNormalization:!0}),container:this.div,viewport:e});const{textDivs:i,textContentItemsStr:n}=this.#ks;this.highlighter?.setTextMapping(i,n),this.accessibilityManager?.setTextMapping(i),await this.#ks.render(),this.#Sa=!0;const s=document.createElement("div");s.className="endOfContent",this.div.append(s),this.#Pa(s),this.#Rs?.(this.div),this.highlighter?.enable(),this.accessibilityManager?.enable()}hide(){!this.div.hidden&&this.#Sa&&(this.highlighter?.disable(),this.div.hidden=!0)}show(){this.div.hidden&&this.#Sa&&(this.div.hidden=!1,this.highlighter?.enable())}cancel(){this.#ks?.cancel(),this.#ks=null,this.highlighter?.disable(),this.accessibilityManager?.disable(),TextLayerBuilder.#Aa(this.div)}#Pa(e){const{div:t}=this;t.addEventListener("mousedown",(()=>{t.classList.add("selecting")})),t.addEventListener("copy",(e=>{if(!this.#ya){const t=document.getSelection();e.clipboardData.setData("text/plain",removeNullCharacters(normalizeUnicode(t.toString())))}stopEvent(e)})),TextLayerBuilder.#Ca.set(t,e),TextLayerBuilder.#_a()}static#Aa(e){this.#Ca.delete(e),0===this.#Ca.size&&(this.#Ta?.abort(),this.#Ta=null)}static#_a(){if(this.#Ta)return;this.#Ta=new AbortController;const{signal:e}=this.#Ta,t=(e,t)=>{t.append(e),e.style.width="",e.style.height="",t.classList.remove("selecting")};let i=!1;var n,s;document.addEventListener("pointerdown",(()=>{i=!0}),{signal:e}),document.addEventListener("pointerup",(()=>{i=!1,this.#Ca.forEach(t)}),{signal:e}),window.addEventListener("blur",(()=>{i=!1,this.#Ca.forEach(t)}),{signal:e}),document.addEventListener("keyup",(()=>{i||this.#Ca.forEach(t)}),{signal:e}),document.addEventListener("selectionchange",(()=>{const e=document.getSelection();if(0===e.rangeCount)return void this.#Ca.forEach(t);const i=new Set;for(let t=0;t<e.rangeCount;t++){const n=e.getRangeAt(t);for(const e of this.#Ca.keys())!i.has(e)&&n.intersectsNode(e)&&i.add(e)}for(const[e,n]of this.#Ca)i.has(e)?e.classList.add("selecting"):t(n,e);if(n??="none"===getComputedStyle(this.#Ca.values().next().value).getPropertyValue("-moz-user-select"),n)return;const a=e.getRangeAt(0),o=s&&(0===a.compareBoundaryPoints(Range.END_TO_END,s)||0===a.compareBoundaryPoints(Range.START_TO_END,s));let r=o?a.startContainer:a.endContainer;if(r.nodeType===Node.TEXT_NODE&&(r=r.parentNode),!o&&0===a.endOffset)do{for(;!r.previousSibling;)r=r.parentNode;r=r.previousSibling}while(!r.childNodes.length);const l=r.parentElement?.closest(".textLayer"),d=this.#Ca.get(l);d&&(d.style.width=l.style.width,d.style.height=l.style.height,d.style.userSelect="text",r.parentElement.insertBefore(d,o?r:r.nextSibling)),s=a.cloneRange()}),{signal:e})}}const DEFAULT_LAYER_PROPERTIES=null,LAYERS_ORDER=new Map([["canvasWrapper",0],["textLayer",1],["annotationLayer",2],["annotationEditorLayer",3],["xfaLayer",3]]);class PDFPageView extends BasePDFPageView{#La=AnnotationMode.ENABLE_FORMS;#Ia=null;#Fs=null;#xa=!0;#Ma=!1;#j=!1;#Na=null;#Da=!1;#Ba=null;#Ra=null;#Oa=1;#ka=1;#Fa=TextLayerMode.ENABLE;#Va=1;#ja={directDrawing:!0,initialOptionalContent:!0,regularAnnotations:!0};#Ua=[null,null,null,null];constructor(e){super(e);const t=e.container,i=e.defaultViewport;this.renderingId="page"+this.id,this.#Na=e.layerProperties||null,this.pdfPage=null,this.pageLabel=null,this.rotation=0,this.scale=e.scale||1,this.viewport=i,this.pdfPageRotate=i.rotation,this._optionalContentConfigPromise=e.optionalContentConfigPromise||null,this.#Fa=e.textLayerMode??TextLayerMode.ENABLE,this.#La=e.annotationMode??AnnotationMode.ENABLE_FORMS,this.imageResourcesPath=e.imageResourcesPath||"",this.enableDetailCanvas=e.enableDetailCanvas??!0,this.maxCanvasPixels=e.maxCanvasPixels??AppOptions.get("maxCanvasPixels"),this.maxCanvasDim=e.maxCanvasDim||AppOptions.get("maxCanvasDim"),this.capCanvasAreaFactor=e.capCanvasAreaFactor??AppOptions.get("capCanvasAreaFactor"),this.#xa=!1!==e.enableAutoLinking,this.#Fs=e.commentManager||null,this.l10n=e.l10n,this.l10n||=new genericl10n_GenericL10n,this._isStandalone=!this.renderingQueue?.hasViewer(),this._container=t,this._annotationCanvasMap=null,this.annotationLayer=null,this.annotationEditorLayer=null,this.textLayer=null,this.xfaLayer=null,this.structTreeLayer=null,this.drawLayer=null,this.detailView=null;const n=document.createElement("div");if(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.#Ha(),t?.append(n),this._isStandalone){t?.style.setProperty("--scale-factor",this.scale*PixelsPerInch.PDF_TO_CSS_UNITS),this.pageColors?.background&&t?.style.setProperty("--page-bg-color",this.pageColors.background);const{optionalContentConfigPromise:i}=e;i&&i.then((e=>{i===this._optionalContentConfigPromise&&(this.#ja.initialOptionalContent=e.hasInitialVisibility)})),e.l10n||this.l10n.translate(this.div)}}#za(e,t){const i=LAYERS_ORDER.get(t),n=this.#Ua[i];if(this.#Ua[i]=e,n)n.replaceWith(e);else{for(let t=i-1;t>=0;t--){const i=this.#Ua[t];if(i)return void i.after(e)}this.div.prepend(e)}}#Ha(){const{div:e,viewport:t}=this;if(t.userUnit!==this.#Va&&(1!==t.userUnit?e.style.setProperty("--user-unit",t.userUnit):e.style.removeProperty("--user-unit"),this.#Va=t.userUnit),this.pdfPage){if(this.#Ra===t.rotation)return;this.#Ra=t.rotation}setLayerDimensions(e,t,!0,!1)}updatePageNumber(e){if(this.id===e)return;this.id=e,this.renderingId=`page${e}`,this.pdfPage&&(this.pdfPage.pageNumber=e),this.setPageLabel(this.pageLabel);const{div:t}=this;t.setAttribute("data-page-number",e),t.setAttribute("data-l10n-args",JSON.stringify({page:e})),this._textHighlighter.pageIdx=e-1}setPdfPage(e){!this._isStandalone||"CanvasText"!==this.pageColors?.foreground&&"Canvas"!==this.pageColors?.background||(this._container?.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),this._container?.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","Highlight"))),this.pdfPage=e,this.pdfPageRotate=e.rotate;const t=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport({scale:this.scale*PixelsPerInch.PDF_TO_CSS_UNITS,rotation:t}),this.#Ha(),this.reset()}destroy(){this.reset(),this.pdfPage?.cleanup()}hasEditableAnnotations(){return!!this.annotationLayer?.hasEditableAnnotations()}get _textHighlighter(){return shadow(this,"_textHighlighter",new TextHighlighter({pageIndex:this.id-1,eventBus:this.eventBus,findController:this.#Na.findController}))}#Wa(e,t){this.eventBus.dispatch(e,{source:this,pageNumber:this.id,error:t})}async#Ka(){let e=null;try{await this.annotationLayer.render({viewport:this.viewport,intent:"display",structTreeLayer:this.structTreeLayer})}catch(t){console.error("#renderAnnotationLayer:",t),e=t}finally{this.#Wa("annotationlayerrendered",e)}}async#$a(){let e=null;try{await this.annotationEditorLayer.render({viewport:this.viewport,intent:"display"})}catch(t){console.error("#renderAnnotationEditorLayer:",t),e=t}finally{this.#Wa("annotationeditorlayerrendered",e)}}async#Ga(){try{await this.drawLayer.render({intent:"display"})}catch(e){console.error("#renderDrawLayer:",e)}}async#Xa(){let e=null;try{const e=await this.xfaLayer.render({viewport:this.viewport,intent:"display"});e?.textDivs&&this._textHighlighter&&this.#Ya(e.textDivs)}catch(t){console.error("#renderXfaLayer:",t),e=t}finally{this.xfaLayer?.div&&(this.l10n.pause(),this.#za(this.xfaLayer.div,"xfaLayer"),this.l10n.resume()),this.#Wa("xfalayerrendered",e)}}async#Za(){if(!this.textLayer)return;let e=null;try{await this.textLayer.render({viewport:this.viewport})}catch(t){if(t instanceof AbortException)return;console.error("#renderTextLayer:",t),e=t}this.#Wa("textlayerrendered",e),this.#qa()}async#qa(){if(!this.textLayer)return;const e=await(this.structTreeLayer?.render());e&&(this.l10n.pause(),this.structTreeLayer?.updateTextLayer(),this.canvas&&e.parentNode!==this.canvas&&this.canvas.append(e),this.l10n.resume()),this.structTreeLayer?.show()}async#Ya(e){const t=await this.pdfPage.getTextContent(),i=[];for(const e of t.items)i.push(e.str);this._textHighlighter.setTextMapping(e,i),this._textHighlighter.enable()}async#Qa(e){let t=null;try{if(await e,!this.annotationLayer)return;await this.annotationLayer.injectLinkAnnotations(Autolinker.processLinks(this))}catch(e){console.error("#injectLinkAnnotations:",e),t=e}}_resetCanvas(){super._resetCanvas(),this.#Ba=null}reset({keepAnnotationLayer:e=!1,keepAnnotationEditorLayer:t=!1,keepXfaLayer:i=!1,keepTextLayer:n=!1,keepCanvasWrapper:s=!1,preserveDetailViewState:a=!1}={}){const o=this.pdfPage?._pdfBug??!1;this.cancelRendering({keepAnnotationLayer:e,keepAnnotationEditorLayer:t,keepXfaLayer:i,keepTextLayer:n}),this.renderingState=RenderingStates.INITIAL;const r=this.div,l=r.childNodes,d=e&&this.annotationLayer?.div||null,h=t&&this.annotationEditorLayer?.div||null,c=i&&this.xfaLayer?.div||null,u=n&&this.textLayer?.div||null,g=s&&this.#Ia||null;for(let e=l.length-1;e>=0;e--){const t=l[e];switch(t){case d:case h:case c:case u:case g:continue}if(o&&t.classList.contains("pdfBugGroupsLayer"))continue;t.remove();const i=this.#Ua.indexOf(t);i>=0&&(this.#Ua[i]=null)}r.removeAttribute("data-loaded"),d&&this.annotationLayer.hide(),h&&this.annotationEditorLayer.hide(),c&&this.xfaLayer.hide(),u&&this.textLayer.hide(),this.structTreeLayer?.hide(),!s&&this.#Ia&&(this.#Ia=null,this._resetCanvas()),a||(this.detailView?.reset({keepCanvas:s}),s||(this.detailView=null))}toggleEditingMode(e){this.#j=e,this.hasEditableAnnotations()&&this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0})}updateVisibleArea(e){this.enableDetailCanvas&&(this.#Da&&this.maxCanvasPixels>0&&e?(this.detailView??=new PDFPageDetailView({pageView:this,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering}),this.detailView.update({visibleArea:e})):this.detailView&&(this.detailView.reset(),this.detailView=null))}update({scale:e=0,rotation:t=null,optionalContentConfigPromise:i=null,drawingDelay:n=-1}){this.scale=e||this.scale,"number"==typeof t&&(this.rotation=t),i instanceof Promise&&(this._optionalContentConfigPromise=i,i.then((e=>{i===this._optionalContentConfigPromise&&(this.#ja.initialOptionalContent=e.hasInitialVisibility)}))),this.#ja.directDrawing=!0;const s=(this.rotation+this.pdfPageRotate)%360;if(this.viewport=this.viewport.clone({scale:this.scale*PixelsPerInch.PDF_TO_CSS_UNITS,rotation:s}),this.#Ha(),this._isStandalone&&this._container?.style.setProperty("--scale-factor",this.viewport.scale),this.#Ja(),this.canvas){const e=this.#Ma&&this.#Da,t=n>=0&&n<1e3;if(t||e)return t&&!e&&this.renderingState!==RenderingStates.FINISHED&&(this.cancelRendering({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,cancelExtraDelay:n}),this.renderingState=RenderingStates.FINISHED,this.#ja.directDrawing=!1),this.cssTransform({redrawAnnotationLayer:!0,redrawAnnotationEditorLayer:!0,redrawXfaLayer:!0,redrawTextLayer:!t,hideTextLayer:t}),void(t||(this.detailView?.update({underlyingViewUpdated:!0}),this.dispatchPageRendered(!0,!1)))}this.cssTransform({}),this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0,preserveDetailViewState:!0}),this.detailView?.update({underlyingViewUpdated:!0})}#Ja(){const{width:e,height:t}=this.viewport,i=this.outputScale=new OutputScale;if(0===this.maxCanvasPixels){const e=1/this.scale;i.sx*=e,i.sy*=e,this.#Da=!0}else if(this.#Da=i.limitCanvas(e,t,this.maxCanvasPixels,this.maxCanvasDim,this.capCanvasAreaFactor),this.#Da&&this.enableDetailCanvas){const e=this.enableOptimizedPartialRendering?4:2;i.sx/=e,i.sy/=e}}cancelRendering({keepAnnotationLayer:e=!1,keepAnnotationEditorLayer:t=!1,keepXfaLayer:i=!1,keepTextLayer:n=!1,cancelExtraDelay:s=0}={}){super.cancelRendering({cancelExtraDelay:s}),!this.textLayer||n&&this.textLayer.div||(this.textLayer.cancel(),this.textLayer=null),!this.annotationLayer||e&&this.annotationLayer.div||(this.annotationLayer.cancel(),this.annotationLayer=null,this._annotationCanvasMap=null),this.structTreeLayer&&!this.textLayer&&(this.structTreeLayer=null),!this.annotationEditorLayer||t&&this.annotationEditorLayer.div||(this.drawLayer&&(this.drawLayer.cancel(),this.drawLayer=null),this.annotationEditorLayer.cancel(),this.annotationEditorLayer=null),!this.xfaLayer||i&&this.xfaLayer.div||(this.xfaLayer.cancel(),this.xfaLayer=null,this._textHighlighter?.disable())}cssTransform({redrawAnnotationLayer:e=!1,redrawAnnotationEditorLayer:t=!1,redrawXfaLayer:i=!1,redrawTextLayer:n=!1,hideTextLayer:s=!1}){const{canvas:a}=this;if(!a)return;const o=this.#Ba;if(this.viewport!==o){const e=(360+this.viewport.rotation-o.rotation)%360;if(90===e||270===e){const{width:t,height:i}=this.viewport,n=i/t,s=t/i;a.style.transform=`rotate(${e}deg) scale(${n},${s})`}else a.style.transform=0===e?"":`rotate(${e}deg)`}e&&this.annotationLayer&&this.#Ka(),t&&this.annotationEditorLayer&&(this.drawLayer&&this.#Ga(),this.#$a()),i&&this.xfaLayer&&this.#Xa(),this.textLayer&&(s?(this.textLayer.hide(),this.structTreeLayer?.hide()):n&&this.#Za())}get width(){return this.viewport.width}get height(){return this.viewport.height}getPagePoint(e,t){return this.viewport.convertToPdfPoint(e,t)}_ensureCanvasWrapper(){let e=this.#Ia;return e||(e=this.#Ia=document.createElement("div"),e.classList.add("canvasWrapper"),this.#za(e,"canvasWrapper")),e}_getRenderingContext(e,t,i){return{canvas:e,transform:t,viewport:this.viewport,annotationMode:this.#La,optionalContentConfigPromise:this._optionalContentConfigPromise,annotationCanvasMap:this._annotationCanvasMap,pageColors:this.pageColors,isEditing:this.#j,recordOperations:i}}async draw(){this.renderingState!==RenderingStates.INITIAL&&(console.error("Must be in new state before drawing"),this.reset());const{div:e,l10n:t,pdfPage:i,viewport:n}=this;if(!i)throw this.renderingState=RenderingStates.FINISHED,new Error("pdfPage is not loaded");this.renderingState=RenderingStates.RUNNING;const s=this._ensureCanvasWrapper();if(this.textLayer||this.#Fa===TextLayerMode.DISABLE||i.isPureXfa||(this._accessibilityManager||=new TextAccessibilityManager,this.textLayer=new TextLayerBuilder({pdfPage:i,highlighter:this._textHighlighter,accessibilityManager:this._accessibilityManager,enablePermissions:this.#Fa===TextLayerMode.ENABLE_PERMISSIONS,onAppend:e=>{this.l10n.pause(),this.#za(e,"textLayer"),this.l10n.resume()}})),!this.annotationLayer&&this.#La!==AnnotationMode.DISABLE){const{annotationStorage:e,annotationEditorUIManager:t,downloadManager:n,enableComment:s,enableScripting:a,fieldObjectsPromise:o,hasJSActionsPromise:r,linkService:l}=this.#Na;this._annotationCanvasMap||=new Map,this.annotationLayer=new AnnotationLayerBuilder({pdfPage:i,annotationStorage:e,imageResourcesPath:this.imageResourcesPath,renderForms:this.#La===AnnotationMode.ENABLE_FORMS,linkService:l,downloadManager:n,enableComment:s,enableScripting:a,hasJSActionsPromise:r,fieldObjectsPromise:o,annotationCanvasMap:this._annotationCanvasMap,accessibilityManager:this._accessibilityManager,annotationEditorUIManager:t,commentManager:this.#Fs,onAppend:e=>{this.#za(e,"annotationLayer")}})}const{width:a,height:o}=n;this.#Ba=n;const{canvas:r,prevCanvas:l}=this._createCanvas((e=>{s.prepend(e)}));r.setAttribute("role","presentation"),this.outputScale||this.#Ja();const{outputScale:d}=this;this.#Ma=this.#Da;const h=approximateFraction(d.sx),c=approximateFraction(d.sy),u=r.width=floorToDivide(calcRound(a*d.sx),h[0]),g=r.height=floorToDivide(calcRound(o*d.sy),c[0]),p=floorToDivide(calcRound(a),h[1]),m=floorToDivide(calcRound(o),c[1]);d.sx=u/p,d.sy=g/m,this.#Oa!==h[1]&&(e.style.setProperty("--scale-round-x",`${h[1]}px`),this.#Oa=h[1]),this.#ka!==c[1]&&(e.style.setProperty("--scale-round-y",`${c[1]}px`),this.#ka=c[1]);const f=this.enableOptimizedPartialRendering&&this.#Ma&&!this.recordedBBoxes,b=d.scaled?[d.sx,0,0,d.sy,0,0]:null,v=this._drawCanvas(this._getRenderingContext(r,b,f),(()=>{l?.remove(),this._resetCanvas()}),(e=>{this.#ja.regularAnnotations=!e.separateAnnots,this.dispatchPageRendered(!1,!1)})).then((async()=>{if(this.renderingState!==RenderingStates.FINISHED)return;this.structTreeLayer||=new StructTreeLayerBuilder(i,n.rawDims);const e=this.#Za();this.annotationLayer&&(await this.#Ka(),this.#xa&&this.annotationLayer&&this.textLayer&&await this.#Qa(e));const{annotationEditorUIManager:a}=this.#Na;a&&(this.drawLayer||=new DrawLayerBuilder,await this.#Ga(),this.drawLayer.setParent(s),(this.annotationLayer||this.#La===AnnotationMode.DISABLE)&&(this.annotationEditorLayer||=new AnnotationEditorLayerBuilder({uiManager:a,pdfPage:i,l10n:t,structTreeLayer:this.structTreeLayer,accessibilityManager:this._accessibilityManager,annotationLayer:this.annotationLayer?.annotationLayer,textLayer:this.textLayer,drawLayer:this.drawLayer.getDrawLayer(),onAppend:e=>{this.#za(e,"annotationEditorLayer")}}),this.#$a()))}));if(i.isPureXfa){if(!this.xfaLayer){const{annotationStorage:e,linkService:t}=this.#Na;this.xfaLayer=new XfaLayerBuilder({pdfPage:i,annotationStorage:e,linkService:t})}this.#Xa()}return e.setAttribute("data-loaded",!0),this.dispatchPageRender(),v}setPageLabel(e){this.pageLabel="string"==typeof e?e: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:e,initialOptionalContent:t,regularAnnotations:i}=this.#ja;return e&&t&&i?this.canvas:null}}const DEFAULT_CACHE_SIZE=10,PagesCountLimit={FORCE_SCROLL_MODE_PAGE:1e4,FORCE_LAZY_PAGE_INIT:5e3,PAUSE_EAGER_PAGE_INIT:250};function isValidAnnotationEditorMode(e){return Object.values(AnnotationEditorType).includes(e)&&e!==AnnotationEditorType.DISABLE}class PDFPageViewBuffer{#eo=new Set;#to=0;constructor(e){this.#to=e}push(e){const t=this.#eo;t.has(e)&&t.delete(e),t.add(e),t.size>this.#to&&this.#io()}resize(e,t=null){this.#to=e;const i=this.#eo;if(t){const e=i.size;let n=1;for(const s of i)if(t.has(s.id)&&(i.delete(s),i.add(s)),++n>e)break}for(;i.size>this.#to;)this.#io()}has(e){return this.#eo.has(e)}[Symbol.iterator](){return this.#eo.keys()}#io(){const e=this.#eo.keys().next().value;e?.destroy(),this.#eo.delete(e)}}class PDFViewer{#no=null;#so=null;#ao=null;#oo=AnnotationEditorType.NONE;#ro=null;#La=AnnotationMode.ENABLE_FORMS;#Fs=null;#lo=null;#do=null;#ho=!1;#co=!1;#ya=!1;#uo=!1;#go=!1;#xa=!0;#$i=null;#Xs=0;#ge=null;#po=!0;#mo=null;#fo=null;#bo=null;#vo=!1;#wo=null;#Eo=!1;#yo=0;#et=new ResizeObserver(this.#Ki.bind(this));#So=null;#Co=null;#To=null;#Po=!0;#Fa=TextLayerMode.ENABLE;#Ao=null;#ms=PagesMapper.instance;constructor(e){const t="5.4.624";if(version!==t)throw new Error(`The API version "${version}" does not match the Viewer version "${t}".`);if(this.container=e.container,this.viewer=e.viewer||e.container.firstElementChild,this.#Ao=e.viewerAlert||null,"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.#et.observe(this.container),this.eventBus=e.eventBus,this.linkService=e.linkService||new SimpleLinkService,this.downloadManager=e.downloadManager||null,this.findController=e.findController||null,this.#so=e.altTextManager||null,this.#Fs=e.commentManager||null,this.#To=e.signatureManager||null,this.#do=e.editorUndoBar||null,this.findController&&(this.findController.onIsPageVisible=e=>this._getVisiblePages().ids.has(e)),this._scriptingManager=e.scriptingManager||null,this.#Fa=e.textLayerMode??TextLayerMode.ENABLE,this.#La=e.annotationMode??AnnotationMode.ENABLE_FORMS,this.#oo=e.annotationEditorMode??AnnotationEditorType.NONE,this.#ao=e.annotationEditorHighlightColors||null,this.#co=!0===e.enableHighlightFloatingButton,this.#uo=!0===e.enableUpdatedAddImage,this.#go=!0===e.enableNewAltTextWhenAddingImage,this.imageResourcesPath=e.imageResourcesPath||"",this.enablePrintAutoRotate=e.enablePrintAutoRotate||!1,this.removePageBorders=e.removePageBorders||!1,this.maxCanvasPixels=e.maxCanvasPixels,this.maxCanvasDim=e.maxCanvasDim,this.capCanvasAreaFactor=e.capCanvasAreaFactor,this.enableDetailCanvas=e.enableDetailCanvas??!0,this.enableOptimizedPartialRendering=e.enableOptimizedPartialRendering??!1,this.l10n=e.l10n,this.l10n||=new genericl10n_GenericL10n,this.#ya=e.enablePermissions||!1,this.pageColors=e.pageColors||null,this.#ge=e.mlManager||null,this.#ho=e.enableHWA||!1,this.#Po=!1!==e.supportsPinchToZoom,this.#xa=!1!==e.enableAutoLinking,this.#Xs=e.minDurationToUpdateCanvas??500,this.defaultRenderingQueue=!e.renderingQueue,this.defaultRenderingQueue?(this.renderingQueue=new PDFRenderingQueue,this.renderingQueue.setViewer(this)):this.renderingQueue=e.renderingQueue;const{abortSignal:i}=e;i?.addEventListener("abort",(()=>{this.#et.disconnect(),this.#et=null}),{once:!0}),this.scroll=watchScroll(this.container,this._scrollUpdate.bind(this),i),this.presentationModeState=PresentationModeState.UNKNOWN,this._resetView(),this.removePageBorders&&this.viewer.classList.add("removePageBorders"),this.#_o(),this.eventBus._on("thumbnailrendered",(({pageNumber:e,pdfPage:t})=>{const i=this._pages[e-1];this.#no.has(i)||t?.cleanup()})),e.l10n||this.l10n.translate(this.container)}get printingAllowed(){return this.#po}get pagesCount(){return this._pages.length}getPageView(e){return this._pages[e]}getCachedPageViews(){return new Set(this.#no)}get pageViewsReady(){return this._pages.every((e=>e?.pdfPage))}get renderForms(){return this.#La===AnnotationMode.ENABLE_FORMS}get enableScripting(){return!!this._scriptingManager}get currentPageNumber(){return this._currentPageNumber}set currentPageNumber(e){if(!Number.isInteger(e))throw new Error("Invalid page number.");this.pdfDocument&&(this._setCurrentPageNumber(e,!0)||console.error(`currentPageNumber: "${e}" is not a valid page.`))}_setCurrentPageNumber(e,t=!1){if(this._currentPageNumber===e)return t&&this.#Lo(),!0;if(!(0<e&&e<=this.pagesCount))return!1;const i=this._currentPageNumber;return this._currentPageNumber=e,this.eventBus.dispatch("pagechanging",{source:this,pageNumber:e,pageLabel:this._pageLabels?.[e-1]??null,previous:i}),t&&this.#Lo(),!0}get currentPageLabel(){return this._pageLabels?.[this._currentPageNumber-1]??null}set currentPageLabel(e){if(!this.pdfDocument)return;let t=0|e;if(this._pageLabels){const i=this._pageLabels.indexOf(e);i>=0&&(t=i+1)}this._setCurrentPageNumber(t,!0)||console.error(`currentPageLabel: "${e}" is not a valid page.`)}get currentScale(){return 0!==this._currentScale?this._currentScale:1}set currentScale(e){if(isNaN(e))throw new Error("Invalid numeric scale.");this.pdfDocument&&this.#Io(e,{noScroll:!1})}get currentScaleValue(){return this._currentScaleValue}set currentScaleValue(e){this.pdfDocument&&this.#Io(e,{noScroll:!1})}get pagesRotation(){return this._pagesRotation}set pagesRotation(e){if(!isValidRotation(e))throw new Error("Invalid pages rotation angle.");if(!this.pdfDocument)return;if((e%=360)<0&&(e+=360),this._pagesRotation===e)return;this._pagesRotation=e;const t=this._currentPageNumber;this.refresh(!0,{rotation:e}),this._currentScaleValue&&this.#Io(this._currentScaleValue,{noScroll:!0}),this.eventBus.dispatch("rotationchanging",{source:this,pagesRotation:e,pageNumber:t}),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 e=this;return shadow(this,"_layerProperties",{get annotationEditorUIManager(){return e.#ro},get annotationStorage(){return e.pdfDocument?.annotationStorage},get downloadManager(){return e.downloadManager},get enableComment(){return!!e.#Fs},get enableScripting(){return!!e._scriptingManager},get fieldObjectsPromise(){return e.pdfDocument?.getFieldObjects()},get findController(){return e.findController},get hasJSActionsPromise(){return e.pdfDocument?.hasJSActions()},get linkService(){return e.linkService}})}#xo(e){const t={annotationEditorMode:this.#oo,annotationMode:this.#La,textLayerMode:this.#Fa};return e?(this.#po=e.includes(PermissionFlag.PRINT_HIGH_QUALITY)||e.includes(PermissionFlag.PRINT),this.eventBus.dispatch("printingallowed",{source:this,isAllowed:this.#po}),e.includes(PermissionFlag.COPY)||this.#Fa!==TextLayerMode.ENABLE||(t.textLayerMode=TextLayerMode.ENABLE_PERMISSIONS),e.includes(PermissionFlag.MODIFY_CONTENTS)||(t.annotationEditorMode=AnnotationEditorType.DISABLE),e.includes(PermissionFlag.MODIFY_ANNOTATIONS)||e.includes(PermissionFlag.FILL_INTERACTIVE_FORMS)||this.#La!==AnnotationMode.ENABLE_FORMS||(t.annotationMode=AnnotationMode.ENABLE),t):(this.#po=!0,this.eventBus.dispatch("printingallowed",{source:this,isAllowed:this.#po}),t)}async#Mo(e){if("hidden"===document.visibilityState||!this.container.offsetParent||0===this._getVisiblePages().views.length)return;const t=Promise.withResolvers(),i=new AbortController;document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&t.resolve()}),{signal:AbortSignal.any([e,i.signal])}),await Promise.race([this._onePageRenderedCapability.promise,t.promise]),i.abort()}async getAllText(){const e=[],t=[];for(let i=1,n=this.pdfDocument.numPages;i<=n;++i){if(this.#Eo)return null;t.length=0;const n=await this.pdfDocument.getPage(i),{items:s}=await n.getTextContent();for(const e of s)e.str&&t.push(e.str),e.hasEOL&&t.push("\\n");e.push(removeNullCharacters(t.join("")))}return e.join("\\n")}#No(e,t){const i=document.getSelection(),{focusNode:n,anchorNode:s}=i;if(s&&n&&i.containsNode(this.#wo)){if(this.#vo||e===TextLayerMode.ENABLE_PERMISSIONS)return void stopEvent(t);this.#vo=!0;const{classList:i}=this.viewer;i.add("copyAll");const n=new AbortController;window.addEventListener("keydown",(e=>this.#Eo="Escape"===e.key),{signal:n.signal}),this.getAllText().then((async e=>{null!==e&&await navigator.clipboard.writeText(e)})).catch((e=>{console.warn(`Something goes wrong when extracting the text: ${e.message}`)})).finally((()=>{this.#vo=!1,this.#Eo=!1,n.abort(),i.remove("copyAll")})),stopEvent(t)}}setDocument(e){if(this.pdfDocument&&(this.eventBus.dispatch("pagesdestroy",{source:this}),this._cancelRendering(),this._resetView(),this.findController?.setDocument(null),this._scriptingManager?.setDocument(null),this.#ro?.destroy(),this.#ro=null,this.#oo=AnnotationEditorType.NONE,this.#po=!0,this.#ms.pagesNumber=0),this.pdfDocument=e,!e)return;const t=e.numPages,i=e.getPage(1),n=e.getOptionalContentConfig({intent:"display"}),s=this.#ya?e.getPermissions():Promise.resolve(),{eventBus:a,pageColors:o,viewer:r}=this;this.#$i=new AbortController;const{signal:l}=this.#$i;if(t>PagesCountLimit.FORCE_SCROLL_MODE_PAGE){console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");const e=this._scrollMode=ScrollMode.PAGE;a.dispatch("scrollmodechanged",{source:this,mode:e})}this._pagesCapability.promise.then((()=>{a.dispatch("pagesloaded",{source:this,pagesCount:t})}),(()=>{}));a._on("pagerender",(e=>{const t=this._pages[e.pageNumber-1];t&&this.#no.push(t)}),{signal:l});const d=e=>{e.cssTransform||e.isDetailView||(this._onePageRenderedCapability.resolve({timestamp:e.timestamp}),a._off("pagerendered",d))};a._on("pagerendered",d,{signal:l}),Promise.all([i,s]).then((([i,s])=>{if(e!==this.pdfDocument)return;this._firstPageCapability.resolve(i),this._optionalContentConfigPromise=n;const{annotationEditorMode:d,annotationMode:h,textLayerMode:c}=this.#xo(s);if(c!==TextLayerMode.DISABLE){const e=this.#wo=document.createElement("div");e.id="hiddenCopyElement",r.before(e)}if(d!==AnnotationEditorType.DISABLE){const t=d;e.isPureXfa?console.warn("Warning: XFA-editing is not implemented."):isValidAnnotationEditorMode(t)?(this.#ro=new AnnotationEditorUIManager(this.container,r,this.#Ao,this.#so,this.#Fs,this.#To,a,e,o,this.#ao,this.#co,this.#uo,this.#go,this.#ge,this.#do,this.#Po),a.dispatch("annotationeditoruimanager",{source:this,uiManager:this.#ro}),t!==AnnotationEditorType.NONE&&(this.#Do(t),this.#ro.updateMode(t))):console.error(`Invalid AnnotationEditor mode: ${t}`)}const u=this._scrollMode===ScrollMode.PAGE?null:r,g=this.currentScale,p=i.getViewport({scale:g*PixelsPerInch.PDF_TO_CSS_UNITS});r.style.setProperty("--scale-factor",p.scale),o?.background&&r.style.setProperty("--page-bg-color",o.background),"CanvasText"!==o?.foreground&&"Canvas"!==o?.background||(r.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),r.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","ButtonText")));for(let e=1;e<=t;++e){const t=new PDFPageView({container:u,eventBus:a,id:e,scale:g,defaultViewport:p.clone(),optionalContentConfigPromise:n,renderingQueue:this.renderingQueue,textLayerMode:c,annotationMode:h,imageResourcesPath:this.imageResourcesPath,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,capCanvasAreaFactor:this.capCanvasAreaFactor,enableDetailCanvas:this.enableDetailCanvas,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,pageColors:o,l10n:this.l10n,layerProperties:this._layerProperties,enableHWA:this.#ho,enableAutoLinking:this.#xa,minDurationToUpdateCanvas:this.#Xs,commentManager:this.#Fs});this._pages.push(t)}this._pages[0]?.setPdfPage(i),this._scrollMode===ScrollMode.PAGE?this.#Bo():this._spreadMode!==SpreadMode.NONE&&this._updateSpreadMode(),a._on("annotationeditorlayerrendered",(e=>{this.#ro&&a.dispatch("annotationeditormodechanged",{source:this,mode:this.#oo})}),{once:!0,signal:l}),this.#Mo(l).then((async()=>{if(e!==this.pdfDocument)return;if(this.findController?.setDocument(e),this._scriptingManager?.setDocument(e),this.#wo&&document.addEventListener("copy",this.#No.bind(this,c),{signal:l}),e.loadingParams.disableAutoFetch||t>PagesCountLimit.FORCE_LAZY_PAGE_INIT)return void this._pagesCapability.resolve();let i=t-1;if(i<=0)this._pagesCapability.resolve();else for(let n=2;n<=t;++n){const t=e.getPage(n).then((e=>{const t=this._pages[n-1];t.pdfPage||t.setPdfPage(e),0==--i&&this._pagesCapability.resolve()}),(e=>{console.error(`Unable to get page ${n} to initialize viewer`,e),0==--i&&this._pagesCapability.resolve()}));n%PagesCountLimit.PAUSE_EAGER_PAGE_INIT==0&&await t}})),a.dispatch("pagesinit",{source:this}),e.getMetadata().then((({info:t})=>{e===this.pdfDocument&&t.Language&&(r.lang=t.Language)})),this.defaultRenderingQueue&&this.update()})).catch((e=>{console.error("Unable to initialize viewer",e),this._pagesCapability.reject(e)}))}async onBeforePagesEdited({pagesMapper:e}){await this._pagesCapability.promise,this._currentPageId=e.getPageId(this._currentPageNumber)}onPagesEdited({pagesMapper:e}){this._currentPageNumber=e.getPageNumber(this._currentPageId);const t=this._pages,i=this._pages=[];for(let n=0,s=e.pagesNumber;n<s;n++){const s=e.getPrevPageNumber(n+1)-1;if(-1===s)continue;const a=t[s];i[n]=a,a.updatePageNumber(n+1)}const n=this._scrollMode===ScrollMode.PAGE?null:this.viewer;if(n){n.replaceChildren();const t=document.createDocumentFragment();for(let n=0,s=e.pagesNumber;n<s;n++){const{div:e}=i[n];e.setAttribute("data-page-number",n+1),t.append(e)}n.append(t)}setTimeout((()=>{this.forceRendering()}))}setPageLabels(e){if(this.pdfDocument){e?Array.isArray(e)&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("setPageLabels: Invalid page labels.")):this._pageLabels=null;for(let e=0,t=this._pages.length;e<t;e++)this._pages[e].setPageLabel(this._pageLabels?.[e]??null)}}_resetView(){this._pages=[],this._currentPageNumber=1,this._currentScale=0,this._currentScaleValue=null,this._pageLabels=null,this.#no=new PDFPageViewBuffer(10),this._location=null,this._pagesRotation=0,this._optionalContentConfigPromise=null,this._firstPageCapability=Promise.withResolvers(),this._onePageRenderedCapability=Promise.withResolvers(),this._pagesCapability=Promise.withResolvers(),this._scrollMode=ScrollMode.VERTICAL,this._previousScrollMode=ScrollMode.UNKNOWN,this._spreadMode=SpreadMode.NONE,this.#So={previousPageNumber:1,scrollDown:!0,pages:[]},this.#$i?.abort(),this.#$i=null,this.viewer.textContent="",this._updateScrollMode(),this.viewer.removeAttribute("lang"),this.#wo?.remove(),this.#wo=null,this.#Ro(),this.#Oo()}#Bo(){if(this._scrollMode!==ScrollMode.PAGE)throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");const e=this._currentPageNumber,t=this.#So,i=this.viewer;if(i.textContent="",t.pages.length=0,this._spreadMode!==SpreadMode.NONE||this.isInPresentationMode){const n=new Set,s=this._spreadMode-1;-1===s?n.add(e-1):e%2!==s?(n.add(e-1),n.add(e)):(n.add(e-2),n.add(e-1));const a=document.createElement("div");if(a.className="spread",this.isInPresentationMode){const e=document.createElement("div");e.className="dummyPage",a.append(e)}for(const e of n){const i=this._pages[e];i&&(a.append(i.div),t.pages.push(i))}i.append(a)}else{const n=this._pages[e-1];i.append(n.div),t.pages.push(n)}t.scrollDown=e>=t.previousPageNumber,t.previousPageNumber=e}_scrollUpdate(){0!==this.pagesCount&&(this.#mo&&clearTimeout(this.#mo),this.#mo=setTimeout((()=>{this.#mo=null,this.update()}),100),this.update())}#ko(e,t=null){const{div:i,id:n}=e;if(this._currentPageNumber!==n&&this._setCurrentPageNumber(n),this._scrollMode===ScrollMode.PAGE&&(this.#Bo(),this.update()),!t&&!this.isInPresentationMode){const e=i.offsetLeft+i.clientLeft,n=e+i.clientWidth,{scrollLeft:s,clientWidth:a}=this.container;(this._scrollMode===ScrollMode.HORIZONTAL||e<s||n>s+a)&&(t={left:0,top:0})}scrollIntoView(i,t),!this._currentScaleValue&&this._location&&(this._location=null)}#Fo(e){return e===this._currentScale||Math.abs(e-this._currentScale)<1e-15}#Vo(e,t,{noScroll:i=!1,preset:n=!1,drawingDelay:s=-1,origin:a=null}){if(this._currentScaleValue=t.toString(),this.#Fo(e))return void(n&&this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:t}));this.viewer.style.setProperty("--scale-factor",e*PixelsPerInch.PDF_TO_CSS_UNITS);const o=s>=0&&s<1e3;this.refresh(!0,{scale:e,drawingDelay:o?s:-1}),o&&(this.#Co=setTimeout((()=>{this.#Co=null,this.refresh()}),s));const r=this._currentScale;if(this._currentScale=e,!i){let t,i=this._currentPageNumber;if(!this._location||this.isInPresentationMode||this.isChangingPresentationMode||(i=this._location.pageNumber,t=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:i,destArray:t,allowNegativeOffset:!0}),Array.isArray(a)){const t=e/r-1,[i,n]=this.containerTopLeft;this.container.scrollLeft+=(a[0]-n)*t,this.container.scrollTop+=(a[1]-i)*t}}this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:n?t:void 0}),this.defaultRenderingQueue&&this.update()}get#jo(){return this._spreadMode!==SpreadMode.NONE&&this._scrollMode!==ScrollMode.HORIZONTAL?2:1}#Io(e,t){let i=parseFloat(e);if(i>0)t.preset=!1,this.#Vo(i,e,t);else{const n=this._pages[this._currentPageNumber-1];if(!n)return;let s=40,a=5;this.isInPresentationMode?(s=a=4,this._spreadMode!==SpreadMode.NONE&&(s*=2)):this.removePageBorders?s=a=0:this._scrollMode===ScrollMode.HORIZONTAL&&([s,a]=[a,s]);const o=(this.container.clientWidth-s)/n.width*n.scale/this.#jo,r=(this.container.clientHeight-a)/n.height*n.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=o;break;case"page-height":i=r;break;case"page-fit":i=Math.min(o,r);break;case"auto":const t=isPortraitOrientation(n)?o:Math.min(r,o);i=Math.min(1.25,t);break;default:return void console.error(`#setScale: "${e}" is an unknown zoom value.`)}t.preset=!0,this.#Vo(i,e,t)}}#Lo(){const e=this._pages[this._currentPageNumber-1];this.isInPresentationMode&&this.#Io(this._currentScaleValue,{noScroll:!0}),this.#ko(e)}pageLabelToPageNumber(e){if(!this._pageLabels)return null;const t=this._pageLabels.indexOf(e);return t<0?null:t+1}scrollPageIntoView({pageNumber:e,destArray:t=null,allowNegativeOffset:i=!1,ignoreDestinationZoom:n=!1,center:s=null}){if(!this.pdfDocument)return;const a=Number.isInteger(e)&&this._pages[e-1];if(!a)return void console.error(`scrollPageIntoView: "${e}" is not a valid pageNumber parameter.`);if(this.isInPresentationMode||!t)return void this._setCurrentPageNumber(e,!0);let o,r,l=0,d=0,h=0,c=0;const u=a.rotation%180!=0,g=(u?a.height:a.width)/a.scale/PixelsPerInch.PDF_TO_CSS_UNITS,p=(u?a.width:a.height)/a.scale/PixelsPerInch.PDF_TO_CSS_UNITS;let m=0;switch(t[1].name){case"XYZ":l=t[2],d=t[3],m=t[4],l=null!==l?l:0,d=null!==d?d:p;break;case"Fit":case"FitB":m="page-fit";break;case"FitH":case"FitBH":d=t[2],m="page-width",null===d&&this._location?(l=this._location.left,d=this._location.top):("number"!=typeof d||d<0)&&(d=p);break;case"FitV":case"FitBV":l=t[2],h=g,c=p,m="page-height";break;case"FitR":l=t[2],d=t[3],h=t[4]-l,c=t[5]-d;let e=40,i=5;this.removePageBorders&&(e=i=0),o=(this.container.clientWidth-e)/h/PixelsPerInch.PDF_TO_CSS_UNITS,r=(this.container.clientHeight-i)/c/PixelsPerInch.PDF_TO_CSS_UNITS,m=Math.min(Math.abs(o),Math.abs(r));break;default:return void console.error(`scrollPageIntoView: "${t[1].name}" is not a valid destination type.`)}if(n||(m&&m!==this._currentScale?this.currentScaleValue=m:0===this._currentScale&&(this.currentScaleValue="auto")),"page-fit"===m&&!t[4])return void this.#ko(a);const f=[a.viewport.convertToViewportPoint(l,d),a.viewport.convertToViewportPoint(l+h,d+c)];let b=Math.min(f[0][0],f[1][0]),v=Math.min(f[0][1],f[1][1]);s?("both"!==s&&"vertical"!==s||(v-=(this.container.clientHeight-Math.abs(f[1][1]-f[0][1]))/2),"both"!==s&&"horizontal"!==s||(b-=(this.container.clientWidth-Math.abs(f[1][0]-f[0][0]))/2)):i||(b=Math.max(b,0),v=Math.max(v,0)),this.#ko(a,{left:b,top:v})}_updateLocation(e){const t=this._currentScale,i=this._currentScaleValue,n=parseFloat(i)===t?Math.round(1e4*t)/100:i,s=e.id,a=this._pages[s-1],o=this.container,r=a.getPagePoint(o.scrollLeft-e.x,o.scrollTop-e.y),l=Math.round(r[0]),d=Math.round(r[1]);let h=`#page=${s}`;this.isInPresentationMode||(h+=`&zoom=${n},${l},${d}`),this._location={pageNumber:s,scale:n,top:d,left:l,rotation:this._pagesRotation,pdfOpenParams:h}}update(){const e=this._getVisiblePages(),t=e.views,i=t.length;if(0===i)return;const n=Math.max(10,2*i+1);this.#no.resize(n,e.ids);for(const{view:e,visibleArea:i}of t)e.updateVisibleArea(i);for(const t of this.#no)e.ids.has(t.id)||t.updateVisibleArea(null);this.renderingQueue.renderHighestPriority(e);const s=this._spreadMode===SpreadMode.NONE&&(this._scrollMode===ScrollMode.PAGE||this._scrollMode===ScrollMode.VERTICAL),a=this._currentPageNumber;let o=!1;for(const e of t){if(e.percent<100)break;if(e.id===a&&s){o=!0;break}}this._setCurrentPageNumber(o?this._currentPageNumber:t[0].id),this._updateLocation(e.first),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}#Uo(){const e=this._getVisiblePages(),t=[],{ids:i,views:n}=e;for(const e of n){const{view:n}=e;n.hasEditableAnnotations()?t.push(e):i.delete(n.id)}return 0===t.length?null:(this.renderingQueue.renderHighestPriority({first:t[0],last:t.at(-1),views:t,ids:i}),i)}containsElement(e){return this.container.contains(e)}focus(){this.container.focus()}get _isContainerRtl(){return"rtl"===getComputedStyle(this.container).direction}get isInPresentationMode(){return this.presentationModeState===PresentationModeState.FULLSCREEN}get isChangingPresentationMode(){return this.presentationModeState===PresentationModeState.CHANGING}get isHorizontalScrollbarEnabled(){return!this.isInPresentationMode&&this.container.scrollWidth>this.container.clientWidth}get isVerticalScrollbarEnabled(){return!this.isInPresentationMode&&this.container.scrollHeight>this.container.clientHeight}_getVisiblePages(){const e=this._scrollMode===ScrollMode.PAGE?this.#So.pages:this._pages,t=this._scrollMode===ScrollMode.HORIZONTAL,i=t&&this._isContainerRtl;return getVisibleElements({scrollEl:this.container,views:e,sortByVisibility:!0,horizontal:t,rtl:i})}cleanup(){for(const e of this._pages)e.renderingState!==RenderingStates.FINISHED&&e.reset()}_cancelRendering(){for(const e of this._pages)e.cancelRendering()}async#ys(e){if(e.pdfPage)return e.pdfPage;try{const t=await this.pdfDocument.getPage(e.id);return e.pdfPage||e.setPdfPage(t),t}catch(e){return console.error("Unable to get page for page view",e),null}}#Ss(e){if(1===e.first?.id)return!0;if(e.last?.id===this.pagesCount)return!1;switch(this._scrollMode){case ScrollMode.PAGE:return this.#So.scrollDown;case ScrollMode.HORIZONTAL:return this.scroll.right}return this.scroll.down}forceRendering(e){const t=e||this._getVisiblePages(),i=this.#Ss(t),n=this._spreadMode!==SpreadMode.NONE&&this._scrollMode!==ScrollMode.HORIZONTAL,s=null!==this.#Co||null!==this.#mo&&t.views.some((e=>e.detailView?.renderingCancelled)),a=this.renderingQueue.getHighestPriority(t,this._pages,i,n,s);return!!a&&(this.#ys(a).then((()=>{this.renderingQueue.renderView(a)})),!0)}get hasEqualPageSizes(){const e=this._pages[0];for(let t=1,i=this._pages.length;t<i;++t){const i=this._pages[t];if(i.width!==e.width||i.height!==e.height)return!1}return!0}getPagesOverview(){let e;return this._pages.map((t=>{const i=t.pdfPage.getViewport({scale:1}),n=isPortraitOrientation(i);if(void 0===e)e=n;else if(this.enablePrintAutoRotate&&n!==e)return{width:i.height,height:i.width,rotation:(i.rotation-90)%360};return{width:i.width,height:i.height,rotation:i.rotation}}))}get optionalContentConfigPromise(){return this.pdfDocument?this._optionalContentConfigPromise?this._optionalContentConfigPromise:(console.error("optionalContentConfigPromise: Not initialized yet."),this.pdfDocument.getOptionalContentConfig({intent:"display"})):Promise.resolve(null)}set optionalContentConfigPromise(e){if(!(e instanceof Promise))throw new Error(`Invalid optionalContentConfigPromise: ${e}`);this.pdfDocument&&this._optionalContentConfigPromise&&(this._optionalContentConfigPromise=e,this.refresh(!1,{optionalContentConfigPromise:e}),this.eventBus.dispatch("optionalcontentconfigchanged",{source:this,promise:e}))}get scrollMode(){return this._scrollMode}set scrollMode(e){if(this._scrollMode!==e){if(!isValidScrollMode(e))throw new Error(`Invalid scroll mode: ${e}`);this.pagesCount>PagesCountLimit.FORCE_SCROLL_MODE_PAGE||(this._previousScrollMode=this._scrollMode,this._scrollMode=e,this.eventBus.dispatch("scrollmodechanged",{source:this,mode:e}),this._updateScrollMode(this._currentPageNumber))}}_updateScrollMode(e=null){const t=this._scrollMode,i=this.viewer;i.classList.toggle("scrollHorizontal",t===ScrollMode.HORIZONTAL),i.classList.toggle("scrollWrapped",t===ScrollMode.WRAPPED),this.pdfDocument&&e&&(t===ScrollMode.PAGE?this.#Bo():this._previousScrollMode===ScrollMode.PAGE&&this._updateSpreadMode(),this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#Io(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}get spreadMode(){return this._spreadMode}set spreadMode(e){if(this._spreadMode!==e){if(!isValidSpreadMode(e))throw new Error(`Invalid spread mode: ${e}`);this._spreadMode=e,this.eventBus.dispatch("spreadmodechanged",{source:this,mode:e}),this._updateSpreadMode(this._currentPageNumber)}}_updateSpreadMode(e=null){if(!this.pdfDocument)return;const t=this.viewer,i=this._pages;if(this._scrollMode===ScrollMode.PAGE)this.#Bo();else if(t.textContent="",this._spreadMode===SpreadMode.NONE)for(const e of this._pages)t.append(e.div);else{const e=this._spreadMode-1;let n=null;for(let s=0,a=i.length;s<a;++s)null===n?(n=document.createElement("div"),n.className="spread",t.append(n)):s%2===e&&(n=n.cloneNode(!1),t.append(n)),n.append(i[s].div)}e&&(this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#Io(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}_getPageAdvance(e,t=!1){switch(this._scrollMode){case ScrollMode.WRAPPED:{const{views:i}=this._getVisiblePages(),n=new Map;for(const{id:e,y:t,percent:s,widthPercent:a}of i){if(0===s||a<100)continue;let i=n.get(t);i||n.set(t,i||=[]),i.push(e)}for(const i of n.values()){const n=i.indexOf(e);if(-1===n)continue;const s=i.length;if(1===s)break;if(t)for(let t=n-1,s=0;t>=s;t--){const n=i[t],s=i[t+1]-1;if(n<s)return e-s}else for(let t=n+1,a=s;t<a;t++){const n=i[t],s=i[t-1]+1;if(n>s)return s-e}if(t){const t=i[0];if(t<e)return e-t+1}else{const t=i[s-1];if(t>e)return t-e+1}break}break}case ScrollMode.HORIZONTAL:break;case ScrollMode.PAGE:case ScrollMode.VERTICAL:{if(this._spreadMode===SpreadMode.NONE)break;const i=this._spreadMode-1;if(t&&e%2!==i)break;if(!t&&e%2===i)break;const{views:n}=this._getVisiblePages(),s=t?e-1:e+1;for(const{id:e,percent:t,widthPercent:i}of n)if(e===s){if(t>0&&100===i)return 2;break}break}}return 1}nextPage(){const e=this._currentPageNumber,t=this.pagesCount;if(e>=t)return!1;const i=this._getPageAdvance(e,!1)||1;return this.currentPageNumber=Math.min(e+i,t),!0}previousPage(){const e=this._currentPageNumber;if(e<=1)return!1;const t=this._getPageAdvance(e,!0)||1;return this.currentPageNumber=Math.max(e-t,1),!0}updateScale({drawingDelay:e,scaleFactor:t=null,steps:i=null,origin:n}){if(null===i&&null===t)throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided.");if(!this.pdfDocument)return;let s=this._currentScale;if(t>0&&1!==t)s=Math.round(s*t*100)/100;else if(i){const e=i>0?1.1:1/1.1,t=i>0?Math.ceil:Math.floor;i=Math.abs(i);do{s=t(10*(s*e).toFixed(2))/10}while(--i>0)}s=MathClamp(s,.1,10),this.#Io(s,{noScroll:!1,drawingDelay:e,origin:n})}increaseScale(e={}){this.updateScale({...e,steps:e.steps??1})}decreaseScale(e={}){this.updateScale({...e,steps:-(e.steps??1)})}#_o(e=this.container.clientHeight){e!==this.#yo&&(this.#yo=e,docStyle.setProperty("--viewer-container-height",`${e}px`))}#Ki(e){for(const t of e)if(t.target===this.container){this.#_o(Math.floor(t.borderBoxSize[0].blockSize)),this.#lo=null;break}}get containerTopLeft(){return this.#lo||=[this.container.offsetTop,this.container.offsetLeft]}#Ro(){null!==this.#Co&&(clearTimeout(this.#Co),this.#Co=null),null!==this.#mo&&(clearTimeout(this.#mo),this.#mo=null)}#Oo(){this.#fo?.abort(),this.#fo=null,null!==this.#bo&&(clearTimeout(this.#bo),this.#bo=null)}#Do(e){switch(e){case AnnotationEditorType.STAMP:this.#ge?.loadModel("altText");break;case AnnotationEditorType.SIGNATURE:this.#To?.loadSignatures()}}get annotationEditorMode(){return this.#ro?this.#oo:AnnotationEditorType.DISABLE}set annotationEditorMode({mode:e,editId:t=null,isFromKeyboard:i=!1,mustEnterInEditMode:n=!1,editComment:s=!1}){if(!this.#ro)throw new Error("The AnnotationEditor is not enabled.");if(this.#oo===e)return;if(!isValidAnnotationEditorMode(e))throw new Error(`Invalid AnnotationEditor mode: ${e}`);if(!this.pdfDocument)return;this.#Do(e);const{eventBus:a,pdfDocument:o}=this,r=async()=>{this.#Oo(),this.#oo=e,await this.#ro.updateMode(e,t,!0,i,n,s),e===this.#oo&&o===this.pdfDocument&&a.dispatch("annotationeditormodechanged",{source:this,mode:e})};if(e===AnnotationEditorType.NONE||this.#oo===AnnotationEditorType.NONE){const t=e!==AnnotationEditorType.NONE;t||this.pdfDocument.annotationStorage.resetModifiedIds(),this.cleanup();for(const e of this._pages)e.toggleEditingMode(t);const i=this.#Uo();if(t&&i){this.#Oo(),this.#fo=new AbortController;const e=AbortSignal.any([this.#$i.signal,this.#fo.signal]);return void a._on("pagerendered",(({pageNumber:e})=>{i.delete(e),0===i.size&&(this.#bo=setTimeout(r,0))}),{signal:e})}}r()}refresh(e=!1,t=Object.create(null)){if(this.pdfDocument){for(const e of this._pages)e.update(t);this.#Ro(),e||this.update()}}}class SecondaryToolbar{#a;constructor(e,t){this.#a=e;const i=[{element:e.presentationModeButton,eventName:"presentationmode",close:!0},{element:e.printButton,eventName:"print",close:!0},{element:e.downloadButton,eventName:"download",close:!0},{element:e.viewBookmarkButton,eventName:null,close:!0},{element:e.firstPageButton,eventName:"firstpage",close:!0},{element:e.lastPageButton,eventName:"lastpage",close:!0},{element:e.pageRotateCwButton,eventName:"rotatecw",close:!1},{element:e.pageRotateCcwButton,eventName:"rotateccw",close:!1},{element:e.cursorSelectToolButton,eventName:"switchcursortool",eventDetails:{tool:CursorTool.SELECT},close:!0},{element:e.cursorHandToolButton,eventName:"switchcursortool",eventDetails:{tool:CursorTool.HAND},close:!0},{element:e.scrollPageButton,eventName:"switchscrollmode",eventDetails:{mode:ScrollMode.PAGE},close:!0},{element:e.scrollVerticalButton,eventName:"switchscrollmode",eventDetails:{mode:ScrollMode.VERTICAL},close:!0},{element:e.scrollHorizontalButton,eventName:"switchscrollmode",eventDetails:{mode:ScrollMode.HORIZONTAL},close:!0},{element:e.scrollWrappedButton,eventName:"switchscrollmode",eventDetails:{mode:ScrollMode.WRAPPED},close:!0},{element:e.spreadNoneButton,eventName:"switchspreadmode",eventDetails:{mode:SpreadMode.NONE},close:!0},{element:e.spreadOddButton,eventName:"switchspreadmode",eventDetails:{mode:SpreadMode.ODD},close:!0},{element:e.spreadEvenButton,eventName:"switchspreadmode",eventDetails:{mode:SpreadMode.EVEN},close:!0},{element:e.imageAltTextSettingsButton,eventName:"imagealttextsettings",close:!0},{element:e.documentPropertiesButton,eventName:"documentproperties",close:!0}];i.push({element:e.openFileButton,eventName:"openfile",close:!0}),this.eventBus=t,this.opened=!1,this.#Re(i),this.reset()}get isOpen(){return this.opened}setPageNumber(e){this.pageNumber=e,this.#xe()}setPagesCount(e){this.pagesCount=e,this.#xe()}reset(){this.pageNumber=0,this.pagesCount=0,this.#xe(),this.eventBus.dispatch("switchcursortool",{source:this,reset:!0}),this.#Ho({mode:ScrollMode.VERTICAL}),this.#zo({mode:SpreadMode.NONE})}#xe(){const{firstPageButton:e,lastPageButton:t,pageRotateCwButton:i,pageRotateCcwButton:n}=this.#a;e.disabled=this.pageNumber<=1,t.disabled=this.pageNumber>=this.pagesCount,i.disabled=0===this.pagesCount,n.disabled=0===this.pagesCount}#Re(e){const{eventBus:t}=this,{toggleButton:i}=this.#a;i.addEventListener("click",this.toggle.bind(this));for(const{element:i,eventName:n,close:s,eventDetails:a}of e)i.addEventListener("click",(e=>{null!==n&&t.dispatch(n,{source:this,...a}),s&&this.close(),t.dispatch("reporttelemetry",{source:this,details:{type:"buttons",data:{id:i.id}}})}));t._on("cursortoolchanged",this.#Wo.bind(this)),t._on("scrollmodechanged",this.#Ho.bind(this)),t._on("spreadmodechanged",this.#zo.bind(this))}#Wo({tool:e,disabled:t}){const{cursorSelectToolButton:i,cursorHandToolButton:n}=this.#a;toggleCheckedBtn(i,e===CursorTool.SELECT),toggleCheckedBtn(n,e===CursorTool.HAND),i.disabled=t,n.disabled=t}#Ho({mode:e}){const{scrollPageButton:t,scrollVerticalButton:i,scrollHorizontalButton:n,scrollWrappedButton:s,spreadNoneButton:a,spreadOddButton:o,spreadEvenButton:r}=this.#a;toggleCheckedBtn(t,e===ScrollMode.PAGE),toggleCheckedBtn(i,e===ScrollMode.VERTICAL),toggleCheckedBtn(n,e===ScrollMode.HORIZONTAL),toggleCheckedBtn(s,e===ScrollMode.WRAPPED);const l=this.pagesCount>PagesCountLimit.FORCE_SCROLL_MODE_PAGE;t.disabled=l,i.disabled=l,n.disabled=l,s.disabled=l;const d=e===ScrollMode.HORIZONTAL;a.disabled=d,o.disabled=d,r.disabled=d}#zo({mode:e}){const{spreadNoneButton:t,spreadOddButton:i,spreadEvenButton:n}=this.#a;toggleCheckedBtn(t,e===SpreadMode.NONE),toggleCheckedBtn(i,e===SpreadMode.ODD),toggleCheckedBtn(n,e===SpreadMode.EVEN)}open(){if(this.opened)return;this.opened=!0;const{toggleButton:e,toolbar:t}=this.#a;toggleExpandedBtn(e,!0,t)}close(){if(!this.opened)return;this.opened=!1;const{toggleButton:e,toolbar:t}=this.#a;toggleExpandedBtn(e,!1,t)}toggle(){this.opened?this.close():this.open()}}const DEFAULT_HEIGHT_IN_PAGE=40;class SignatureManager{#Ko;#$o=null;#Go;#Xo;#x;#Yo;#D;#Zo=null;#qo;#Qo=null;#Jo="";#er=null;#tr;#ir;#nr;#sr;#ar;#or=null;#rr=null;#lr;#dr;#hr;#cr;#ur;#gr;#pr;#mr;#fr=null;#br;#vr=null;#wr=null;#Er=!1;#C;#yr=!1;#m;#G;#Sr;#Cr;#Z=null;static#Tr=null;constructor({dialog:e,panels:t,typeButton:i,typeInput:n,drawButton:s,drawPlaceholder:a,drawSVG:o,drawThickness:r,imageButton:l,imageSVG:d,imagePlaceholder:h,imagePicker:c,imagePickerLink:u,description:g,clearButton:p,cancelButton:m,addButton:f,errorCloseButton:b,errorBar:v,errorTitle:w,errorDescription:E,saveCheckbox:y,saveContainer:S},C,T,P,A,_,L){this.#Ko=f,this.#Go=p,this.#Xo=g.lastElementChild,this.#Yo=g.firstElementChild,this.#D=e,this.#tr=o,this.#qo=a,this.#ir=r,this.#nr=v,this.#ar=w,this.#sr=E,this.#cr=d,this.#hr=h,this.#lr=c,this.#dr=u,this.#G=P,this.#ur=y,this.#gr=S,this.#mr=T,this.#br=n,this.#m=A,this.#Cr=_,this.#C=L,this.#Sr=new EditDescriptionDialog(C,P),SignatureManager.#Tr||=Object.freeze({signature:"pdfjs-editor-add-signature-description-default-when-drawing",errorUploadTitle:"pdfjs-editor-add-signature-image-upload-error-title",errorUploadDescription:"pdfjs-editor-add-signature-image-upload-error-description",errorNoDataTitle:"pdfjs-editor-add-signature-image-no-data-error-title",errorNoDataDescription:"pdfjs-editor-add-signature-image-no-data-error-description"}),e.addEventListener("close",this.#Q.bind(this)),e.addEventListener("contextmenu",(e=>{const{target:t}=e;t!==this.#br&&t!==this.#Yo&&e.preventDefault()})),e.addEventListener("drop",(e=>{stopEvent(e)})),m.addEventListener("click",this.#L.bind(this)),f.addEventListener("click",this.#Pr.bind(this)),p.addEventListener("click",(()=>{this.#fe({type:"signature",action:"pdfjs.signature.clear",data:{type:this.#vr}}),this.#Ar(null)}),{passive:!0}),this.#Yo.addEventListener("input",(()=>{this.#Xo.disabled=""===this.#Yo.value}),{passive:!0}),this.#Xo.addEventListener("click",(()=>{this.#Yo.value="",this.#Xo.disabled=!0}),{passive:!0}),b.addEventListener("click",(()=>{v.hidden=!0}),{passive:!0}),this.#_r(i,s,l,t),c.accept=SupportedImageMimeTypes.join(","),L._on("storedsignatureschanged",this.#Lr.bind(this)),P.register(e)}#_r(e,t,i,n){const s=this.#pr=new Map([["type",e],["draw",t],["image",i]]),a=e=>{for(const[t,i]of s)i===e.target?(i.setAttribute("aria-selected",!0),i.setAttribute("tabindex",0),n.setAttribute("data-selected",t),this.#Ar(t)):(i.setAttribute("aria-selected",!1),i.setAttribute("tabindex",-1))},o=Array.from(s.values());for(let e=0,t=o.length;e<t;e++){const t=o[e];t.addEventListener("click",a,{passive:!0}),t.addEventListener("keydown",(({key:t})=>{"ArrowLeft"!==t&&"ArrowRight"!==t||o[e+("ArrowLeft"===t?-1:1)]?.focus()}),{passive:!0})}}#Ir(){this.#Er=!1,this.#Yo.value="",this.#vr&&(this.#$o.get(this.#vr).value="")}#xr(e){switch(e){case"type":this.#br.value="";break;case"draw":this.#Zo=null,this.#er=null,this.#Jo="",this.#Qo?.remove(),this.#Qo=null,this.#qo.hidden=!1,this.#ir.value=1;break;case"image":this.#hr.hidden=!1,this.#rr?.remove(),this.#rr=null}}#Ar(e){if(e&&this.#vr===e)return;this.#vr&&(this.#$o.get(this.#vr).value=this.#Yo.value),e&&(this.#vr=e),this.#nr.hidden=!0;const t=!e;switch(t?this.#Ir():this.#Yo.value=this.#$o.get(this.#vr).value,this.#Xo.disabled=""===this.#Yo.value,this.#wr?.abort(),this.#wr=new AbortController,this.#vr){case"type":this.#Mr(t);break;case"draw":this.#Nr(t);break;case"image":this.#Dr(t)}}#Br(e){e&&this.#yr||(this.#ur.disabled=!e),this.#Go.disabled=this.#Ko.disabled=this.#Yo.disabled=!e}#Mr(e){e&&this.#xr("type"),this.#Br(this.#br.value);const{signal:t}=this.#wr,i={passive:!0,signal:t};this.#br.addEventListener("input",(()=>{const{value:e}=this.#br;this.#Er||(this.#$o.get("type").default=this.#Yo.value=e,this.#Xo.disabled=""===e),this.#Br(e)}),i),this.#Yo.addEventListener("input",(()=>{this.#Er=this.#br.value!==this.#Yo.value}),i)}#Nr(e){e&&this.#xr("draw"),this.#Br(this.#Qo);const{signal:t}=this.#wr,i={signal:t};let n=NaN;const s=e=>{const{pointerId:a}=e;if(!isNaN(n)&&n!==a)return;n=a,e.preventDefault(),this.#tr.setPointerCapture(a);const{width:o,height:r}=this.#tr.getBoundingClientRect();let{offsetX:l,offsetY:d}=e;if(l=Math.round(l),d=Math.round(d),e.target===this.#qo&&(this.#qo.hidden=!0),!this.#Zo){this.#Zo={width:o,height:r,thickness:parseInt(this.#ir.value),curves:[]},this.#Br(!0);const e=new DOMSVGFactory,t=this.#Qo=e.createElement("path");t.setAttribute("stroke-width",this.#ir.value),this.#tr.append(t),this.#tr.addEventListener("pointerdown",s,i),this.#qo.removeEventListener("pointerdown",s),""===this.#Yo.value&&this.#m.get(SignatureManager.#Tr.signature).then((e=>{this.#$o.get("draw").default=e,this.#Yo.value||=e,this.#Xo.disabled=""===this.#Yo.value}))}this.#er=[l,d],this.#Zo.curves.push({points:this.#er}),this.#Jo+=`M ${l} ${d}`,this.#Qo.setAttribute("d",this.#Jo);const h=new AbortController,c={signal:AbortSignal.any([t,h.signal])};this.#tr.addEventListener("contextmenu",noContextMenu,c),this.#tr.addEventListener("pointermove",(e=>{e.preventDefault();let{offsetX:t,offsetY:i}=e;t=Math.round(t),i=Math.round(i);const n=this.#er;if(!(t<0||i<0||t>o||i>r||t===n.at(-2)&&i===n.at(-1))){if(n.length>=4){const[e,s,a,o]=n.slice(-4);this.#Jo+=`C${(e+5*a)/6} ${(s+5*o)/6} ${(5*a+t)/6} ${(5*o+i)/6} ${(a+t)/2} ${(o+i)/2}`}else this.#Jo+=`L${t} ${i}`;n.push(t,i),this.#Qo.setAttribute("d",this.#Jo)}}),c),this.#tr.addEventListener("pointerup",(e=>{const{pointerId:t}=e;(isNaN(n)||n===t)&&(n=NaN,e.preventDefault(),this.#tr.releasePointerCapture(t),h.abort(),2===this.#er.length&&(this.#Jo+=`L${this.#er[0]} ${this.#er[1]}`,this.#Qo.setAttribute("d",this.#Jo)))}),c)};this.#Zo?this.#tr.addEventListener("pointerdown",s,i):this.#qo.addEventListener("pointerdown",s,i),this.#ir.addEventListener("input",(()=>{const{value:e}=this.#ir;this.#ir.setAttribute("data-l10n-args",JSON.stringify({thickness:e})),this.#Zo&&(this.#Qo.setAttribute("stroke-width",e),this.#Zo.thickness=e)}),i)}#Rr(e){this.#ar.setAttribute("data-l10n-id",SignatureManager.#Tr[`error${e}Title`]),this.#sr.setAttribute("data-l10n-id",SignatureManager.#Tr[`error${e}Description`]),this.#nr.hidden=!1}#Dr(e){e&&this.#xr("image"),this.#Br(this.#rr);const{signal:t}=this.#wr,i={signal:t},n={passive:!0,signal:t};this.#dr.addEventListener("keydown",(e=>{const{key:t}=e;"Enter"!==t&&" "!==t||(stopEvent(e),this.#lr.click())}),i),this.#lr.addEventListener("click",(()=>{this.#D.classList.toggle("waiting",!0)}),n),this.#lr.addEventListener("change",(async()=>{const e=this.#lr.files?.[0];if(!e||!SupportedImageMimeTypes.includes(e.type))return this.#Rr("Upload"),void this.#D.classList.toggle("waiting",!1);await this.#Or(e)}),n),this.#lr.addEventListener("cancel",(()=>{this.#D.classList.toggle("waiting",!1)}),n),this.#hr.addEventListener("dragover",(e=>{const{dataTransfer:t}=e;for(const{type:i}of t.items)if(SupportedImageMimeTypes.includes(i))return t.dropEffect="copy"===t.effectAllowed?"copy":"move",void stopEvent(e);t.dropEffect="none"}),i),this.#hr.addEventListener("drop",(e=>{const{dataTransfer:{files:t}}=e;if(t?.length){for(const e of t)if(SupportedImageMimeTypes.includes(e.type)){this.#Or(e);break}stopEvent(e),this.#D.classList.toggle("waiting",!0)}}),i)}async#Or(e){let t;try{t=await this.#Z.imageManager.getFromFile(e)}catch(e){console.error("SignatureManager.#extractSignature.",e)}if(!t)return this.#Rr("Upload"),void this.#D.classList.toggle("waiting",!1);const i=this.#or=this.#x.getFromImage(t.bitmap);if(!i)return this.#Rr("NoData"),void this.#D.classList.toggle("waiting",!1);const{outline:n}=i;this.#hr.hidden=!0,this.#Br(!0);const s=new DOMSVGFactory,a=this.#rr=s.createElement("path");this.#cr.setAttribute("viewBox",n.viewBox),this.#cr.setAttribute("preserveAspectRatio","xMidYMid meet"),this.#cr.append(a),a.setAttribute("d",n.toSVGPath()),this.#$o.get("image").default=e.name,""===this.#Yo.value&&(this.#Yo.value=e.name||"",this.#Xo.disabled=""===this.#Yo.value),this.#D.classList.toggle("waiting",!1)}#kr(){return this.#x.getFromText(this.#br.value,window.getComputedStyle(this.#br))}#Fr(){const{width:e,height:t}=this.#tr.getBoundingClientRect();return this.#x.getDrawnSignature(this.#Zo,e,t)}#fe(e){this.#C.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}#Vr(e,t,i){const{curves:n,areContours:s,thickness:a,width:o,height:r}=e,l=Math.max(o,r),d=SignatureExtractor.processDrawnLines({lines:{curves:n,thickness:a,width:o,height:r},pageWidth:l,pageHeight:l,rotation:0,innerMargin:0,mustSmooth:!1,areContours:s});if(!d)return;const{outline:h}=d,c=new DOMSVGFactory,u=document.createElement("div"),g=document.createElement("button");g.addEventListener("click",(()=>{this.#C.dispatch("switchannotationeditorparams",{source:this,type:AnnotationEditorParamsType.CREATE,value:{signatureData:{lines:{curves:n,thickness:a,width:o,height:r},mustSmooth:!1,areContours:s,description:i,uuid:t,heightInPage:40}}})})),u.append(g),u.classList.add("toolbarAddSignatureButtonContainer");const p=c.create(1,1,!0);g.append(p);const m=document.createElement("span");m.ariaHidden=!0,g.append(m),g.classList.add("toolbarAddSignatureButton"),g.type="button",m.textContent=i,g.setAttribute("data-l10n-id","pdfjs-editor-add-saved-signature-button"),g.setAttribute("data-l10n-args",JSON.stringify({description:i})),g.tabIndex=0;const f=c.createElement("path");p.append(f),p.setAttribute("viewBox",h.viewBox),p.setAttribute("preserveAspectRatio","xMidYMid meet"),s&&f.classList.add("contours"),f.setAttribute("d",h.toSVGPath());const b=document.createElement("button");u.append(b),b.classList.add("toolbarButton","deleteButton"),b.setAttribute("data-l10n-id","pdfjs-editor-delete-signature-button1"),b.type="button",b.tabIndex=0,b.addEventListener("click",(async()=>{await this.#Cr.delete(t)&&(u.remove(),this.#fe({type:"signature",action:"pdfjs.signature.delete_saved",data:{savedCount:await this.#Cr.size()}}))}));const v=document.createElement("span");b.append(v),v.setAttribute("data-l10n-id","pdfjs-editor-delete-signature-button-label1"),this.#mr.before(u)}async#Lr(){const e=this.#mr.parentElement;for(;e.firstElementChild!==this.#mr;)e.firstElementChild.remove();this.#fr=null,await this.loadSignatures(!0)}getSignature(e){return this.open(e)}async loadSignatures(e=!1){if(!this.#mr||!e&&this.#mr.previousElementSibling||!this.#Cr)return;if(!this.#fr&&(this.#fr=this.#Cr.getAll().then((async e=>[e,await Promise.all(Array.from(e.values(),(({signatureData:e})=>SignatureExtractor.decompressSignature(e))))])),!e))return;const[t,i]=await this.#fr;this.#fr=null;let n=0;for(const[e,{description:s}]of t){const t=i[n++];t&&(t.curves=t.outlines.map((e=>({points:e}))),delete t.outlines,this.#Vr(t,e,s))}}async renderEditButton(e){const t=document.createElement("button");t.classList.add("altText","editDescription"),t.tabIndex=0,e.description&&(t.title=e.description);const i=document.createElement("span");return t.append(i),i.setAttribute("data-l10n-id","pdfjs-editor-add-signature-edit-button-label"),t.addEventListener("click",(()=>{this.#Sr.open(e)}),{passive:!0}),t}async open({uiManager:e,editor:t}){this.#$o||=new Map(this.#pr.keys().map((e=>[e,{value:"",default:""}]))),this.#Z=e,this.#x=t,this.#Z.removeEditListeners();const i=this.#yr=await this.#Cr.isFull();this.#gr.classList.toggle("fullStorage",i),this.#ur.checked=!i,await this.#G.open(this.#D);const n=this.#pr.get("type");n.focus(),n.click()}#L(){this.#le()}#le(){this.#G.closeIfActive(this.#D)}#Q(){null===this.#x._drawId&&this.#x.remove(),this.#Z?.addEditListeners(),this.#wr?.abort(),this.#wr=null,this.#Z=null,this.#x=null,this.#Ir();for(const[e]of this.#pr)this.#xr(e);this.#Br(!1),this.#vr=null,this.#$o=null}async#Pr(){let e;const t=this.#vr;switch(t){case"type":e=this.#kr();break;case"draw":e=this.#Fr();break;case"image":e=this.#or}let i=null;const n=this.#Yo.value;if(this.#ur.checked){const{newCurves:t,areContours:s,thickness:a,width:o,height:r}=e,l=await SignatureExtractor.compressSignature({outlines:t,areContours:s,thickness:a,width:o,height:r});i=await this.#Cr.create({description:n,signatureData:l}),i?this.#Vr({curves:t.map((e=>({points:e}))),areContours:s,thickness:a,width:o,height:r},i,n):console.warn("SignatureManager.add: cannot save the signature.")}const s=this.#$o.get(t);this.#fe({type:"signature",action:"pdfjs.signature.created",data:{type:t,saved:!!i,savedCount:await this.#Cr.size(),descriptionChanged:n!==s.default}}),this.#x.addSignature(e,40,this.#Yo.value,i),this.#le()}destroy(){this.#Z=null,this.#le()}}class EditDescriptionDialog{#x;#jr;#Yo;#D;#G;#Ur;#Z;constructor({dialog:e,description:t,cancelButton:i,updateButton:n,editSignatureView:s},a){const o=this.#Yo=t.firstElementChild;this.#Ur=s,this.#D=e,this.#G=a,e.addEventListener("close",this.#Q.bind(this)),e.addEventListener("contextmenu",(e=>{e.target!==this.#Yo&&e.preventDefault()})),i.addEventListener("click",this.#L.bind(this)),n.addEventListener("click",this.#Hr.bind(this));const r=t.lastElementChild;r.addEventListener("click",(()=>{o.value="",r.disabled=!0,n.disabled=""===this.#jr})),o.addEventListener("input",(()=>{const{value:e}=o;r.disabled=""===e,n.disabled=e===this.#jr,s.setAttribute("aria-label",e)}),{passive:!0}),a.register(e)}async open(e){this.#Z=e._uiManager,this.#x=e,this.#jr=this.#Yo.value=e.description,this.#Yo.dispatchEvent(new Event("input")),this.#Z.removeEditListeners();const{areContours:t,outline:i}=e.getSignaturePreview(),n=(new DOMSVGFactory).createElement("path");this.#Ur.append(n),this.#Ur.setAttribute("viewBox",i.viewBox),n.setAttribute("d",i.toSVGPath()),t&&n.classList.add("contours"),await this.#G.open(this.#D)}async#Hr(){this.#x._reportTelemetry({action:"pdfjs.signature.edit_description",data:{hasBeenChanged:!0}}),this.#x.description=this.#Yo.value,this.#le()}#L(){this.#x._reportTelemetry({action:"pdfjs.signature.edit_description",data:{hasBeenChanged:!1}}),this.#le()}#le(){this.#G.closeIfActive(this.#D)}#Q(){this.#Z?.addEditListeners(),this.#Z=null,this.#x=null,this.#Ur.firstElementChild.remove()}}class Toolbar{#zr=null;#a;constructor(e,t,i=0){this.#a=e,this.eventBus=t;const n=[{element:e.previous,eventName:"previouspage"},{element:e.next,eventName:"nextpage"},{element:e.zoomIn,eventName:"zoomin"},{element:e.zoomOut,eventName:"zoomout"},{element:e.print,eventName:"print"},{element:e.download,eventName:"download"},{element:e.editorCommentButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorCommentButton;return t.contains("toggled")?AnnotationEditorType.NONE:AnnotationEditorType.POPUP}}},{element:e.editorFreeTextButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorFreeTextButton;return t.contains("toggled")?AnnotationEditorType.NONE:AnnotationEditorType.FREETEXT}}},{element:e.editorHighlightButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorHighlightButton;return t.contains("toggled")?AnnotationEditorType.NONE:AnnotationEditorType.HIGHLIGHT}}},{element:e.editorInkButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorInkButton;return t.contains("toggled")?AnnotationEditorType.NONE:AnnotationEditorType.INK}}},{element:e.editorStampButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorStampButton;return t.contains("toggled")?AnnotationEditorType.NONE:AnnotationEditorType.STAMP}},telemetry:{type:"editing",data:{action:"pdfjs.image.icon_click"}}},{element:e.editorSignatureButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorSignatureButton;return t.contains("toggled")?AnnotationEditorType.NONE:AnnotationEditorType.SIGNATURE}}}];this.#Re(n),this.#Wr({value:i}),this.reset()}#Wr({value:e}){let t="normal";switch(e){case 1:t="compact";break;case 2:t="touch"}document.documentElement.setAttribute("data-toolbar-density",t)}setPageNumber(e,t){this.pageNumber=e,this.pageLabel=t,this.#xe(!1)}setPagesCount(e,t){this.pagesCount=e,this.hasPageLabels=t,this.#xe(!0)}setPageScale(e,t){this.pageScaleValue=(e||t).toString(),this.pageScale=t,this.#xe(!1)}reset(){this.#zr=null,this.pageNumber=0,this.pageLabel=null,this.hasPageLabels=!1,this.pagesCount=0,this.pageScaleValue="auto",this.pageScale=1,this.#xe(!0),this.updateLoadingIndicatorState(),this.#Kr({mode:AnnotationEditorType.DISABLE})}#Re(e){const{eventBus:t}=this,{editorHighlightColorPicker:i,editorHighlightButton:n,pageNumber:s,scaleSelect:a}=this.#a,o=this;for(const{element:i,eventName:n,eventDetails:s,telemetry:a}of e)i.addEventListener("click",(e=>{null!==n&&t.dispatch(n,{source:this,...s,isFromKeyboard:0===e.detail}),a&&t.dispatch("reporttelemetry",{source:this,details:a})}));s.addEventListener("click",(function(){this.select()})),s.addEventListener("change",(function(){t.dispatch("pagenumberchanged",{source:o,value:this.value})})),a.addEventListener("change",(function(){"custom"!==this.value&&t.dispatch("scalechanged",{source:o,value:this.value})})),a.addEventListener("click",(function({target:e}){this.value===o.pageScaleValue&&"OPTION"===e.tagName.toUpperCase()&&this.blur()})),a.oncontextmenu=noContextMenu,t._on("annotationeditormodechanged",this.#Kr.bind(this)),t._on("showannotationeditorui",(({mode:e})=>{if(e===AnnotationEditorType.HIGHLIGHT)n.click()})),t._on("toolbardensity",this.#Wr.bind(this)),i&&(t._on("annotationeditoruimanager",(({uiManager:e})=>{const t=this.#zr=new ColorPicker({uiManager:e});e.setMainHighlightColorPicker(t),i.append(t.renderMainDropdown())})),t._on("mainhighlightcolorpickerupdatecolor",(({value:e})=>{this.#zr?.updateColor(e)})))}#Kr({mode:e}){const{editorCommentButton:t,editorCommentParamsToolbar:i,editorFreeTextButton:n,editorFreeTextParamsToolbar:s,editorHighlightButton:a,editorHighlightParamsToolbar:o,editorInkButton:r,editorInkParamsToolbar:l,editorStampButton:d,editorStampParamsToolbar:h,editorSignatureButton:c,editorSignatureParamsToolbar:u}=this.#a;toggleExpandedBtn(t,e===AnnotationEditorType.POPUP,i),toggleExpandedBtn(n,e===AnnotationEditorType.FREETEXT,s),toggleExpandedBtn(a,e===AnnotationEditorType.HIGHLIGHT,o),toggleExpandedBtn(r,e===AnnotationEditorType.INK,l),toggleExpandedBtn(d,e===AnnotationEditorType.STAMP,h),toggleExpandedBtn(c,e===AnnotationEditorType.SIGNATURE,u),t.disabled=n.disabled=a.disabled=r.disabled=d.disabled=c.disabled=e===AnnotationEditorType.DISABLE}#xe(e=!1){const{pageNumber:t,pagesCount:i,pageScaleValue:n,pageScale:s}=this,a=this.#a;e&&(this.hasPageLabels?(a.pageNumber.type="text",a.numPages.setAttribute("data-l10n-id","pdfjs-page-of-pages")):(a.pageNumber.type="number",a.numPages.setAttribute("data-l10n-id","pdfjs-of-pages"),a.numPages.setAttribute("data-l10n-args",JSON.stringify({pagesCount:i}))),a.pageNumber.max=i),this.hasPageLabels?(a.pageNumber.value=this.pageLabel,a.numPages.setAttribute("data-l10n-args",JSON.stringify({pageNumber:t,pagesCount:i}))):a.pageNumber.value=t,a.previous.disabled=t<=1,a.next.disabled=t>=i,a.zoomOut.disabled=s<=.1,a.zoomIn.disabled=s>=10;let o=!1;for(const e of a.scaleSelect.options)e.value===n?(e.selected=!0,o=!0):e.selected=!1;o||(a.customScaleOption.selected=!0,a.customScaleOption.setAttribute("data-l10n-args",JSON.stringify({scale:Math.round(1e4*s)/100})))}updateLoadingIndicatorState(e=!1){const{pageNumber:t}=this.#a;t.classList.toggle("loading",e)}}const DEFAULT_VIEW_HISTORY_CACHE_SIZE=20;class ViewHistory{constructor(e,t=20){this.fingerprint=e,this.cacheSize=t,this._initializedPromise=this._readFromStorage().then((e=>{const t=JSON.parse(e||"{}");let i=-1;if(Array.isArray(t.files)){for(;t.files.length>=this.cacheSize;)t.files.shift();for(let e=0,n=t.files.length;e<n;e++){if(t.files[e].fingerprint===this.fingerprint){i=e;break}}}else t.files=[];-1===i&&(i=t.files.push({fingerprint:this.fingerprint})-1),this.file=t.files[i],this.database=t}))}async _writeToStorage(){const e=JSON.stringify(this.database);localStorage.setItem("pdfjs.history",e)}async _readFromStorage(){return localStorage.getItem("pdfjs.history")}async set(e,t){return await this._initializedPromise,this.file[e]=t,this._writeToStorage()}async setMultiple(e){await this._initializedPromise;for(const t in e)this.file[t]=e[t];return this._writeToStorage()}async get(e,t){await this._initializedPromise;const i=this.file[e];return void 0!==i?i:t}async getMultiple(e){await this._initializedPromise;const t=Object.create(null);for(const i in e){const n=this.file[i];t[i]=void 0!==n?n:e[i]}return t}}const SIDEBAR_WIDTH_VAR="--viewsManager-width",SIDEBAR_RESIZING_CLASS="viewsManagerResizing",UI_NOTIFICATION_CLASS="pdfSidebarNotification";class ViewsManager extends Sidebar{static#Tr=null;constructor({elements:{outerContainer:e,sidebarContainer:t,toggleButton:i,resizer:n,thumbnailButton:s,outlineButton:a,attachmentsButton:o,layersButton:r,thumbnailsView:l,outlinesView:d,attachmentsView:h,layersView:c,viewsManagerCurrentOutlineButton:u,viewsManagerSelectorButton:g,viewsManagerSelectorOptions:p,viewsManagerHeaderLabel:m},eventBus:f,l10n:b}){super({sidebar:t,resizer:n,toggleButton:i},"ltr"===b.getDirection(),!1),this.isOpen=!1,this.active=SidebarView.THUMBS,this.isInitialViewSet=!1,this.isInitialEventDispatched=!1,this.onToggled=null,this.onUpdateThumbnails=null,this.outerContainer=e,this.sidebarContainer=t,this.toggleButton=i,this.resizer=n,this.thumbnailButton=s,this.outlineButton=a,this.attachmentsButton=o,this.layersButton=r,this.thumbnailsView=l,this.outlinesView=d,this.attachmentsView=h,this.layersView=c,this.viewsManagerCurrentOutlineButton=u,this.viewsManagerHeaderLabel=m,this.eventBus=f,this.menu=new Menu(p,g,[s,a,o,r]),ViewsManager.#Tr||=Object.freeze({pagesTitle:"pdfjs-views-manager-pages-title",outlinesTitle:"pdfjs-views-manager-outlines-title",attachmentsTitle:"pdfjs-views-manager-attachments-title",layersTitle:"pdfjs-views-manager-layers-title",notificationButton:"pdfjs-toggle-views-manager-notification-button",toggleButton:"pdfjs-toggle-views-manager-button"}),this.#mi()}reset(){this.isInitialViewSet=!1,this.isInitialEventDispatched=!1,this.#$r(!0),this.switchView(SidebarView.THUMBS),this.outlineButton.disabled=this.attachmentsButton.disabled=this.layersButton.disabled=!1,this.viewsManagerCurrentOutlineButton.disabled=!0}get visibleView(){return this.isOpen?this.active:SidebarView.NONE}setInitialView(e=SidebarView.NONE){this.isInitialViewSet||(this.isInitialViewSet=!0,e!==SidebarView.NONE&&e!==SidebarView.UNKNOWN?(this.switchView(e,!0),this.isInitialEventDispatched||this.#Gr()):this.#Gr())}switchView(e,t=!1){const i=e!==this.active;let n=!1,s=null;switch(e){case SidebarView.NONE:return void(this.isOpen&&this.close());case SidebarView.THUMBS:s="pagesTitle",this.isOpen&&i&&(n=!0);break;case SidebarView.OUTLINE:if(s="outlinesTitle",this.outlineButton.disabled)return;break;case SidebarView.ATTACHMENTS:if(s="attachmentsTitle",this.attachmentsButton.disabled)return;break;case SidebarView.LAYERS:if(s="layersTitle",this.layersButton.disabled)return;break;default:return void console.error(`PDFSidebar.switchView: "${e}" is not a valid view.`)}this.viewsManagerCurrentOutlineButton.hidden=e!==SidebarView.OUTLINE,this.viewsManagerHeaderLabel.setAttribute("data-l10n-id",ViewsManager.#Tr[s]||""),this.active=e,toggleSelectedBtn(this.thumbnailButton,e===SidebarView.THUMBS,this.thumbnailsView),toggleSelectedBtn(this.outlineButton,e===SidebarView.OUTLINE,this.outlinesView),toggleSelectedBtn(this.attachmentsButton,e===SidebarView.ATTACHMENTS,this.attachmentsView),toggleSelectedBtn(this.layersButton,e===SidebarView.LAYERS,this.layersView),!t||this.isOpen?(n&&(this.onUpdateThumbnails(),this.onToggled()),i&&this.#Gr()):this.open()}open(){this.isOpen||(this.isOpen=!0,this.onResizing(this.width),this._sidebar.hidden=!1,toggleExpandedBtn(this.toggleButton,!0),this.switchView(this.active),queueMicrotask((()=>{this.outerContainer.classList.add("viewsManagerMoving","viewsManagerOpen")})),this.active===SidebarView.THUMBS&&this.onUpdateThumbnails(),this.onToggled(),this.#Gr(),this.#$r())}close(e=null){this.isOpen&&(this.isOpen=!1,this._sidebar.hidden=!0,toggleExpandedBtn(this.toggleButton,!1),this.outerContainer.classList.add("viewsManagerMoving"),this.outerContainer.classList.remove("viewsManagerOpen"),this.onToggled(),this.#Gr(),e?.detail>0&&this.toggleButton.blur())}toggle(e=null){super.toggle(),this.isOpen?this.close(e):this.open()}#Gr(){this.isInitialViewSet&&(this.isInitialEventDispatched||=!0),this.eventBus.dispatch("sidebarviewchanged",{source:this,view:this.visibleView})}#Xr(){this.toggleButton.setAttribute("data-l10n-id",ViewsManager.#Tr.notificationButton),this.isOpen||this.toggleButton.classList.add(UI_NOTIFICATION_CLASS)}#$r(e=!1){(this.isOpen||e)&&this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS),e&&this.toggleButton.setAttribute("data-l10n-id",ViewsManager.#Tr.toggleButton)}#mi(){const{eventBus:e,outerContainer:t}=this;this.sidebarContainer.addEventListener("transitionend",(i=>{i.target===this.sidebarContainer&&(t.classList.remove("viewsManagerMoving"),e.dispatch("resize",{source:this}))})),this.thumbnailButton.addEventListener("click",(()=>{this.switchView(SidebarView.THUMBS)})),this.outlineButton.addEventListener("click",(()=>{this.switchView(SidebarView.OUTLINE)})),this.outlineButton.addEventListener("dblclick",(()=>{e.dispatch("toggleoutlinetree",{source:this})})),this.attachmentsButton.addEventListener("click",(()=>{this.switchView(SidebarView.ATTACHMENTS)})),this.layersButton.addEventListener("click",(()=>{this.switchView(SidebarView.LAYERS)})),this.layersButton.addEventListener("dblclick",(()=>{e.dispatch("resetlayers",{source:this})})),this.viewsManagerCurrentOutlineButton.addEventListener("click",(()=>{e.dispatch("currentoutlineitem",{source:this})}));const i=(e,t,i)=>{t.disabled=!e,e?this.#Xr():this.active===i&&this.switchView(SidebarView.THUMBS)};e._on("outlineloaded",(e=>{i(e.outlineCount,this.outlineButton,SidebarView.OUTLINE),e.currentOutlineItemPromise.then((e=>{this.isInitialViewSet&&(this.viewsManagerCurrentOutlineButton.disabled=!e)}))})),e._on("attachmentsloaded",(e=>{i(e.attachmentsCount,this.attachmentsButton,SidebarView.ATTACHMENTS)})),e._on("layersloaded",(e=>{i(e.layersCount,this.layersButton,SidebarView.LAYERS)})),e._on("presentationmodechanged",(e=>{e.state===PresentationModeState.NORMAL&&this.visibleView===SidebarView.THUMBS&&this.onUpdateThumbnails()}))}onStartResizing(){this.outerContainer.classList.add("viewsManagerResizing")}onStopResizing(){this.eventBus.dispatch("resize",{source:this}),this.outerContainer.classList.remove("viewsManagerResizing")}onResizing(e){docStyle.setProperty(SIDEBAR_WIDTH_VAR,`${e}px`)}}const FORCE_PAGES_LOADED_TIMEOUT=1e4,ViewOnLoad={UNKNOWN:-1,PREVIOUS:0,INITIAL:1},PDFViewerApplication={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,pdfTextExtractor:null,pdfHistory:null,viewsManager:null,pdfOutlineViewer:null,pdfAttachmentViewer:null,pdfLayerViewer:null,pdfCursorTools:null,pdfScriptingManager:null,store:null,downloadManager:null,overlayManager:null,preferences:new Preferences,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,_printPermissionPromise:null,async initialize(e){this.appConfig=e;try{await this.preferences.initializedPromise}catch(e){console.error("initialize:",e)}let t;switch(AppOptions.get("pdfBugEnabled")&&await this._parseHashParams(),AppOptions.get("viewerCssTheme")){case 1:t="light";break;case 2:t="dark"}t&&docStyle.setProperty("color-scheme",t),this.l10n=await this.externalServices.createL10n(),document.getElementsByTagName("html")[0].dir=this.l10n.getDirection(),this.l10n.translate(e.appContainer||document.documentElement),this.isViewerEmbedded&&AppOptions.get("externalLinkTarget")===LinkTarget.NONE&&AppOptions.set("externalLinkTarget",LinkTarget.TOP),await this._initializeViewerComponents(),this.pdfTextExtractor=new PdfTextExtractor(this.externalServices),this.bindEvents(),this.bindWindowEvents(),this._initializedCapability.settled=!0,this._initializedCapability.resolve()},async _parseHashParams(){const e=document.location.hash.substring(1);if(!e)return;const{mainContainer:t,viewerContainer:i}=this.appConfig,n=parseQueryString(e),s=async()=>{if(this._PDFBug)return;const{PDFBug:e}=await import(AppOptions.get("debuggerSrc"));this._PDFBug=e};if("true"===n.get("disableworker"))try{GlobalWorkerOptions.workerSrc||=AppOptions.get("workerSrc"),await import(PDFWorker.workerSrc),AppOptions.set("workerPort",null)}catch(e){console.error("_parseHashParams:",e)}if(n.has("textlayer"))switch(n.get("textlayer")){case"off":AppOptions.set("textLayerMode",TextLayerMode.DISABLE);break;case"visible":case"shadow":case"hover":i.classList.add(`textLayer-${n.get("textlayer")}`);try{await s(),this._PDFBug.loadCSS()}catch(e){console.error("_parseHashParams:",e)}}if(n.has("pdfbug")){const e=n.get("pdfbug").split(",");try{await s(),this._PDFBug.init(t,e)}catch(e){console.error("_parseHashParams:",e)}const i={pdfBug:!0,fontExtraProperties:!0};globalThis.StepperManager?.enabled&&(i.minDurationToUpdateCanvas=0),AppOptions.setAll(i)}n.has("locale")&&AppOptions.set("localeProperties",{lang:n.get("locale")});const a={disableAutoFetch:e=>"true"===e,disableFontFace:e=>"true"===e,disableHistory:e=>"true"===e,disableRange:e=>"true"===e,disableStream:e=>"true"===e,verbosity:e=>0|e};for(const e in a){const t=a[e],i=e.toLowerCase();n.has(i)&&AppOptions.set(e,t(n.get(i)))}},async _initializeViewerComponents(){const{appConfig:e,externalServices:t,l10n:i,mlManager:n}=this,s=this._globalAbortController.signal,a=new EventBus;this.eventBus=AppOptions.eventBus=a,n?.setEventBus(a,s);const o=this.overlayManager=new OverlayManager,r=this.pdfRenderingQueue=new PDFRenderingQueue;r.onIdle=this._cleanup.bind(this);const l=this.pdfLinkService=new PDFLinkService({eventBus:a,externalLinkTarget:AppOptions.get("externalLinkTarget"),externalLinkRel:AppOptions.get("externalLinkRel"),ignoreDestinationZoom:AppOptions.get("ignoreDestinationZoom")}),d=this.downloadManager=new DownloadManager,h=this.findController=new PDFFindController({linkService:l,eventBus:a,updateMatchesCountOnProgress:!0}),c=this.pdfScriptingManager=new PDFScriptingManager({eventBus:a,externalServices:t,docProperties:this._scriptingDocProperties.bind(this)}),u=e.mainContainer,g=e.viewerContainer,p=AppOptions.get("annotationEditorMode"),m=AppOptions.get("forcePageColors")||window.matchMedia("(forced-colors: active)").matches,f=m?{background:AppOptions.get("pageColorsBackground"),foreground:AppOptions.get("pageColorsForeground")}:null;let b;b=AppOptions.get("enableUpdatedAddImage")?e.newAltTextDialog?new NewAltTextManager(e.newAltTextDialog,o,a):null:e.altTextDialog?new AltTextManager(e.altTextDialog,u,o,a):null,e.editorUndoBar&&(this.editorUndoBar=new EditorUndoBar(e.editorUndoBar,a));const v=AppOptions.get("enableSignatureEditor")&&e.addSignatureDialog?new SignatureManager(e.addSignatureDialog,e.editSignatureDialog,e.annotationEditorParams?.editorSignatureAddSignature||null,o,i,t.createSignatureStorage(a,s),a):null,w=!e.viewerContainer||"ltr"===getComputedStyle(e.viewerContainer).direction,E=AppOptions.get("enableComment")&&e.editCommentDialog?new CommentManager(e.editCommentDialog,{learnMoreUrl:AppOptions.get("commentLearnMoreUrl"),sidebar:e.annotationEditorParams?.editorCommentsSidebar||null,sidebarResizer:e.annotationEditorParams?.editorCommentsSidebarResizer||null,commentsList:e.annotationEditorParams?.editorCommentsSidebarList||null,commentCount:e.annotationEditorParams?.editorCommentsSidebarCount||null,sidebarTitle:e.annotationEditorParams?.editorCommentsSidebarTitle||null,closeButton:e.annotationEditorParams?.editorCommentsSidebarCloseButton||null,commentToolbarButton:e.toolbar?.editorCommentButton||null},a,l,o,w,m):null,y=AppOptions.get("enableHWA"),S=AppOptions.get("maxCanvasPixels"),C=AppOptions.get("maxCanvasDim"),T=AppOptions.get("capCanvasAreaFactor"),P=this.pdfViewer=new PDFViewer({container:u,viewer:g,viewerAlert:e.viewerAlert,eventBus:a,renderingQueue:r,linkService:l,downloadManager:d,altTextManager:b,commentManager:E,signatureManager:v,editorUndoBar:this.editorUndoBar,findController:h,scriptingManager:AppOptions.get("enableScripting")&&c,l10n:i,textLayerMode:AppOptions.get("textLayerMode"),annotationMode:AppOptions.get("annotationMode"),annotationEditorMode:p,annotationEditorHighlightColors:AppOptions.get("highlightEditorColors"),enableHighlightFloatingButton:AppOptions.get("enableHighlightFloatingButton"),enableUpdatedAddImage:AppOptions.get("enableUpdatedAddImage"),enableNewAltTextWhenAddingImage:AppOptions.get("enableNewAltTextWhenAddingImage"),imageResourcesPath:AppOptions.get("imageResourcesPath"),enablePrintAutoRotate:AppOptions.get("enablePrintAutoRotate"),maxCanvasPixels:S,maxCanvasDim:C,capCanvasAreaFactor:T,enableDetailCanvas:AppOptions.get("enableDetailCanvas"),enablePermissions:AppOptions.get("enablePermissions"),enableOptimizedPartialRendering:AppOptions.get("enableOptimizedPartialRendering"),pageColors:f,mlManager:n,abortSignal:s,enableHWA:y,supportsPinchToZoom:this.supportsPinchToZoom,enableAutoLinking:AppOptions.get("enableAutoLinking"),minDurationToUpdateCanvas:AppOptions.get("minDurationToUpdateCanvas")});if(r.setViewer(P),l.setViewer(P),c.setViewer(P),e.viewsManager?.thumbnailsView&&(this.pdfThumbnailViewer=new PDFThumbnailViewer({container:e.viewsManager.thumbnailsView,eventBus:a,renderingQueue:r,linkService:l,maxCanvasPixels:S,maxCanvasDim:C,pageColors:f,abortSignal:s,enableHWA:y,enableSplitMerge:AppOptions.get("enableSplitMerge"),manageMenu:e.viewsManager.manageMenu}),r.setThumbnailViewer(this.pdfThumbnailViewer)),this.isViewerEmbedded||AppOptions.get("disableHistory")||(this.pdfHistory=new PDFHistory({linkService:l,eventBus:a}),l.setHistory(this.pdfHistory)),!this.supportsIntegratedFind&&e.findBar&&(this.findBar=new PDFFindBar(e.findBar,e.principalContainer,a)),e.annotationEditorParams)if(p!==AnnotationEditorType.DISABLE){const t=e.toolbar?.editorSignatureButton;t&&AppOptions.get("enableSignatureEditor")&&(t.parentElement.hidden=!1);const i=e.toolbar?.editorCommentButton;i&&AppOptions.get("enableComment")&&(i.parentElement.hidden=!1),this.annotationEditorParams=new AnnotationEditorParams(e.annotationEditorParams,a)}else for(const e of["editorModeButtons","editorModeSeparator"])document.getElementById(e)?.classList.add("hidden");n&&e.secondaryToolbar?.imageAltTextSettingsButton&&(this.imageAltTextSettings=new ImageAltTextSettings(e.altTextSettingsDialog,o,a,n)),e.documentProperties&&(this.pdfDocumentProperties=new PDFDocumentProperties(e.documentProperties,o,a,i,(()=>this._docFilename),(()=>this._docTitle))),e.secondaryToolbar?.cursorHandToolButton&&(this.pdfCursorTools=new PDFCursorTools({container:u,eventBus:a,cursorToolOnLoad:AppOptions.get("cursorToolOnLoad")})),e.toolbar&&(this.toolbar=new Toolbar(e.toolbar,a,AppOptions.get("toolbarDensity"))),e.secondaryToolbar&&(AppOptions.get("enableAltText")&&(e.secondaryToolbar.imageAltTextSettingsButton?.classList.remove("hidden"),e.secondaryToolbar.imageAltTextSettingsSeparator?.classList.remove("hidden")),this.secondaryToolbar=new SecondaryToolbar(e.secondaryToolbar,a)),this.supportsFullscreen&&e.secondaryToolbar?.presentationModeButton&&(this.pdfPresentationMode=new PDFPresentationMode({container:u,pdfViewer:P,eventBus:a})),e.passwordOverlay&&(this.passwordPrompt=new PasswordPrompt(e.passwordOverlay,o,this.isViewerEmbedded)),e.viewsManager?.outlinesView&&(this.pdfOutlineViewer=new PDFOutlineViewer({container:e.viewsManager.outlinesView,eventBus:a,l10n:i,linkService:l,downloadManager:d})),e.viewsManager?.attachmentsView&&(this.pdfAttachmentViewer=new PDFAttachmentViewer({container:e.viewsManager.attachmentsView,eventBus:a,l10n:i,downloadManager:d})),e.viewsManager?.layersView&&(this.pdfLayerViewer=new PDFLayerViewer({container:e.viewsManager.layersView,eventBus:a,l10n:i})),e.viewsManager&&(this.viewsManager=new ViewsManager({elements:e.viewsManager,eventBus:a,l10n:i}),this.viewsManager.onToggled=this.forceRendering.bind(this),this.viewsManager.onUpdateThumbnails=()=>{for(const e of P.getCachedPageViews())e.renderingState===RenderingStates.FINISHED&&this.pdfThumbnailViewer.getThumbnail(e.id-1)?.setImage(e);this.pdfThumbnailViewer.scrollThumbnailIntoView(P.currentPageNumber)})},async run(e){await this.initialize(e);const{appConfig:t,eventBus:i}=this;let n;n=parseQueryString(document.location.search.substring(1)).get("file")??AppOptions.get("defaultUrl");try{n=new URL(n).href}catch{n=encodeURIComponent(n).replaceAll("%2F","/")}validateFileURL(n);const s=this._openFileInput=document.createElement("input");s.id="fileInput",s.hidden=!0,s.type="file",s.value=null,document.body.append(s),s.addEventListener("change",(function(e){const{files:t}=e.target;t&&0!==t.length&&i.dispatch("fileinputchange",{source:this,fileInput:e.target})})),t.mainContainer.addEventListener("dragover",(function(e){for(const t of e.dataTransfer.items)if("application/pdf"===t.type)return e.dataTransfer.dropEffect="copy"===e.dataTransfer.effectAllowed?"copy":"move",void stopEvent(e)})),t.mainContainer.addEventListener("drop",(function(e){"application/pdf"===e.dataTransfer.files?.[0].type&&(stopEvent(e),i.dispatch("fileinputchange",{source:this,fileInput:e.dataTransfer}))})),AppOptions.get("supportsDocumentFonts")||(AppOptions.set("disableFontFace",!0),this.l10n.get("pdfjs-web-fonts-disabled").then((e=>{console.warn(e)})));const a=e=>{t.toolbar?.print?.classList.toggle("hidden",!e),t.secondaryToolbar?.printButton.classList.toggle("hidden",!e)};this.supportsPrinting?i.on("printingallowed",(({isAllowed:e})=>a(e))):a(!1),this.supportsFullscreen||t.secondaryToolbar?.presentationModeButton.classList.add("hidden"),this.supportsIntegratedFind&&t.findBar?.toggleButton?.classList.add("hidden"),n?this.open({url:n}):this._hideViewBookmark()},get externalServices(){return shadow(this,"externalServices",new ExternalServices)},get initialized(){return this._initializedCapability.settled},get initializedPromise(){return this._initializedCapability.promise},updateZoom(e,t,i){this.pdfViewer.isInPresentationMode||this.pdfViewer.updateScale({drawingDelay:AppOptions.get("defaultZoomDelay"),steps:e,scaleFactor:t,origin:i})},zoomIn(){this.updateZoom(1)},zoomOut(){this.updateZoom(-1)},zoomReset(){this.pdfViewer.isInPresentationMode||(this.pdfViewer.currentScaleValue="auto")},touchPinchCallback(e,t,i){if(this.supportsPinchToZoom){const n=this._accumulateFactor(this.pdfViewer.currentScale,i/t,"_touchUnusedFactor");this.updateZoom(null,n,e)}else{const n=30,s=this._accumulateTicks((i-t)/n,"_touchUnusedTicks");this.updateZoom(s,null,e)}},touchPinchEndCallback(){this._touchUnusedTicks=0,this._touchUnusedFactor=1},get pagesCount(){return this.pdfDocument?this.pdfDocument.numPages:0},get page(){return this.pdfViewer.currentPageNumber},set page(e){this.pdfViewer.currentPageNumber=e},get supportsPrinting(){return shadow(this,"supportsPrinting",AppOptions.get("supportsPrinting")&&PDFPrintServiceFactory.supportsPrinting)},get supportsFullscreen(){return shadow(this,"supportsFullscreen",document.fullscreenEnabled)},get supportsPinchToZoom(){return shadow(this,"supportsPinchToZoom",AppOptions.get("supportsPinchToZoom"))},get supportsIntegratedFind(){return shadow(this,"supportsIntegratedFind",AppOptions.get("supportsIntegratedFind"))},get loadingBar(){const e=document.getElementById("loadingBar"),t=e?new ProgressBar(e):null;return shadow(this,"loadingBar",t)},get supportsMouseWheelZoomCtrlKey(){return shadow(this,"supportsMouseWheelZoomCtrlKey",AppOptions.get("supportsMouseWheelZoomCtrlKey"))},get supportsMouseWheelZoomMetaKey(){return shadow(this,"supportsMouseWheelZoomMetaKey",AppOptions.get("supportsMouseWheelZoomMetaKey"))},get supportsCaretBrowsingMode(){return AppOptions.get("supportsCaretBrowsingMode")},moveCaret(e,t){this._caretBrowsing||=new CaretBrowsingMode(this._globalAbortController.signal,this.appConfig.mainContainer,this.appConfig.viewerContainer,this.appConfig.toolbar?.container),this._caretBrowsing.moveCaret(e,t)},setTitleUsingUrl(e="",t=null){this.url=e,this.baseUrl=updateUrlHash(e,"",!0),t&&(this._downloadUrl=t===e?this.baseUrl:updateUrlHash(t,"",!0)),isDataScheme(e)&&this._hideViewBookmark();let i=pdfjs_getPdfFilenameFromUrl(e,"");if(!i)try{i=decodeURIComponent(getFilenameFromUrl(e))}catch{}this.setTitle(i||e)},setTitle(e=this._title){if(this._title=e,this.isViewerEmbedded)return;const t=this._hasAnnotationEditors&&!this.pdfRenderingQueue.printing;document.title=`${t?"* ":""}${e}`},get _docFilename(){return this._contentDispositionFilename||pdfjs_getPdfFilenameFromUrl(this.url)},get _docTitle(){const{documentInfo:e,metadata:t}=this,i=t?.get("dc:title");return i&&"Untitled"!==i&&!/[\\uFFF0-\\uFFFF]/g.test(i)?i:e.Title},_hideViewBookmark(){const{secondaryToolbar:e}=this.appConfig;e?.viewBookmarkButton.classList.add("hidden"),e?.presentationModeButton.classList.contains("hidden")&&document.getElementById("viewBookmarkSeparator")?.classList.add("hidden")},async close(){if(this._unblockDocumentLoadEvent(),this._hideViewBookmark(),!this.pdfLoadingTask)return;if(this.pdfDocument?.annotationStorage.size>0&&this._annotationStorageModified)try{await this.save()}catch{}const e=[];e.push(this.pdfLoadingTask.destroy()),this.pdfLoadingTask=null,this.pdfDocument&&(this.pdfDocument=null,this.pdfThumbnailViewer?.setDocument(null),this.pdfViewer.setDocument(null),this.pdfLinkService.setDocument(null),this.pdfDocumentProperties?.setDocument(null),this.pdfTextExtractor?.setViewer(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,e.push(this.pdfScriptingManager.destroyPromise,this.passwordPrompt.close()),this.setTitle(),this.viewsManager?.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(e)},async open(e){this.pdfLoadingTask&&await this.close();const t=AppOptions.getAll(OptionKind.WORKER);Object.assign(GlobalWorkerOptions,t),e.url&&this.setTitleUsingUrl(e.originalUrl||e.url,e.url);const i=AppOptions.getAll(OptionKind.API),n=getDocument({...i,...e});return this.pdfLoadingTask=n,n.onPassword=(e,t)=>{this.isViewerEmbedded&&this._unblockDocumentLoadEvent(),this.pdfLinkService.externalLinkEnabled=!1,this.passwordPrompt.setUpdateCallback(e,t),this.passwordPrompt.open()},n.onProgress=e=>this.progress(e.percent),n.promise.then((e=>{this.load(e)}),(e=>{if(n!==this.pdfLoadingTask)return;let t="pdfjs-loading-error";return e instanceof InvalidPDFException?t="pdfjs-invalid-file-error":e instanceof ResponseException&&(t=e.missing?"pdfjs-missing-file-error":"pdfjs-unexpected-response-error"),this._documentError(t,{message:e.message}).then((()=>{throw e}))}))},async download(){let e;try{e=await(this.pdfDocument?this.pdfDocument.getData():this.pdfLoadingTask.getData())}catch{}this.downloadManager.download(e,this._downloadUrl,this._docFilename)},async save(){if(this._saveInProgress)return;this._saveInProgress=!0,await this.pdfScriptingManager.dispatchWillSave();try{const e=await this.pdfDocument.saveDocument();this.downloadManager.download(e,this._downloadUrl,this._docFilename)}catch(e){console.error("Error when saving the document:",e),await this.download()}finally{await this.pdfScriptingManager.dispatchDidSave(),this._saveInProgress=!1}const e=this.pdfDocument?.annotationStorage.editorStats;e&&this.externalServices.reportTelemetry({type:"editing",data:{type:"save",stats:e}})},async downloadOrSave(){const{classList:e}=this.appConfig.appContainer;e.add("wait"),await(this.pdfDocument?.annotationStorage.size>0?this.save():this.download()),e.remove("wait")},async _documentError(e,t=null){this._unblockDocumentLoadEvent();const i=await this._otherError(e||"pdfjs-loading-error",t);this.eventBus.dispatch("documenterror",{source:this,message:i,reason:t?.message??null})},async _otherError(e,t=null){const i=await this.l10n.get(e),n=[`PDF.js v${version||"?"} (build: ${build||"?"})`];return t&&(n.push(`Message: ${t.message}`),t.stack?n.push(`Stack: ${t.stack}`):(t.filename&&n.push(`File: ${t.filename}`),t.lineNumber&&n.push(`Line: ${t.lineNumber}`))),console.error(`${i}\\n\\n${n.join("\\n")}`),i},progress(e){!this.loadingBar||e<=this.loadingBar.percent||(this.loadingBar.percent=e,(this.pdfDocument?.loadingParams.disableAutoFetch??AppOptions.get("disableAutoFetch"))&&this.loadingBar.setDisableAutoFetch())},load(e){this.pdfDocument=e,this._printPermissionPromise=new Promise((e=>{this.eventBus.on("printingallowed",(({isAllowed:t})=>{e(t)}),{once:!0})})),e.getDownloadInfo().then((({length:e})=>{this._contentLength=e,this.loadingBar?.hide(),a.then((()=>{this.eventBus.dispatch("documentloaded",{source:this})}))}));const t=e.getPageLayout().catch((()=>{})),i=e.getPageMode().catch((()=>{})),n=e.getOpenAction().catch((()=>{}));this.toolbar?.setPagesCount(e.numPages,!1),this.secondaryToolbar?.setPagesCount(e.numPages),this.pdfLinkService.setDocument(e),this.pdfDocumentProperties?.setDocument(e);const s=this.pdfViewer;s.setDocument(e),this.pdfTextExtractor.setViewer(s);const{firstPagePromise:a,onePageRendered:o,pagesPromise:r}=s;this.pdfThumbnailViewer?.setDocument(e);const l=(this.store=new ViewHistory(e.fingerprints[0])).getMultiple({page:null,zoom:"auto",scrollLeft:"0",scrollTop:"0",rotation:null,sidebarView:SidebarView.UNKNOWN,scrollMode:ScrollMode.UNKNOWN,spreadMode:SpreadMode.UNKNOWN}).catch((()=>{}));a.then((a=>{this.loadingBar?.setWidth(this.appConfig.viewerContainer),this._initializeAnnotationStorageCallbacks(e),Promise.all([animationStarted,l,t,i,n]).then((async([t,i,n,a,o])=>{const l=AppOptions.get("viewOnLoad");this._initializePdfHistory({fingerprint:e.fingerprints[0],viewOnLoad:l,initialDest:o?.dest});const d=this.initialBookmark,h=AppOptions.get("defaultZoomValue");let c=h?`zoom=${h}`:null,u=null,g=AppOptions.get("sidebarViewOnLoad"),p=AppOptions.get("scrollModeOnLoad"),m=AppOptions.get("spreadModeOnLoad");if(i?.page&&l!==ViewOnLoad.INITIAL&&(c=`page=${i.page}&zoom=${h||i.zoom},${i.scrollLeft},${i.scrollTop}`,u=parseInt(i.rotation,10),g===SidebarView.UNKNOWN&&(g=0|i.sidebarView),p===ScrollMode.UNKNOWN&&(p=0|i.scrollMode),m===SpreadMode.UNKNOWN&&(m=0|i.spreadMode)),a&&g===SidebarView.UNKNOWN&&(g=apiPageModeToSidebarView(a)),n&&p===ScrollMode.UNKNOWN&&m===SpreadMode.UNKNOWN){m=apiPageLayoutToViewerModes(n).spreadMode}this.setInitialView(c,{rotation:u,sidebarView:g,scrollMode:p,spreadMode:m}),this.eventBus.dispatch("documentinit",{source:this}),await Promise.race([r,new Promise((e=>{setTimeout(e,1e4)}))]),(d||c)&&(s.hasEqualPageSizes||(this.initialBookmark=d,s.currentScaleValue=s.currentScaleValue,this.setInitialView(c)))})).catch((()=>{this.setInitialView()})).then((function(){s.update()}))})),r.then((()=>{this._unblockDocumentLoadEvent(),this._initializeAutoPrint(e,n)}),(e=>{this._documentError("pdfjs-loading-error",{message:e.message})})),o.then((t=>{this.externalServices.reportTelemetry({type:"pageInfo",timestamp:t.timestamp}),this.pdfOutlineViewer&&e.getOutline().then((t=>{e===this.pdfDocument&&this.pdfOutlineViewer.render({outline:t,pdfDocument:e})})),this.pdfAttachmentViewer&&e.getAttachments().then((t=>{e===this.pdfDocument&&this.pdfAttachmentViewer.render({attachments:t})})),this.pdfLayerViewer&&s.optionalContentConfigPromise.then((t=>{e===this.pdfDocument&&this.pdfLayerViewer.render({optionalContentConfig:t,pdfDocument:e})}))})),this._initializePageLabels(e),this._initializeMetadata(e)},async _scriptingDocProperties(e){return(this.documentInfo||(await new Promise((e=>{this.eventBus._on("metadataloaded",e,{once:!0})})),e===this.pdfDocument))&&(this._contentLength||(await new Promise((e=>{this.eventBus._on("documentloaded",e,{once:!0})})),e===this.pdfDocument))?{...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}:null},async _initializeAutoPrint(e,t){const[i,n]=await Promise.all([t,this.pdfViewer.enableScripting?null:e.getJSActions()]);if(e!==this.pdfDocument)return;let s="Print"===i?.action;if(n){console.warn("Warning: JavaScript support is not enabled");for(const e in n){if(s)break;switch(e){case"WillClose":case"WillSave":case"DidSave":case"WillPrint":case"DidPrint":continue}s=n[e].some((e=>AutoPrintRegExp.test(e)))}}s&&this.triggerPrinting()},async _initializeMetadata(e){const{info:t,metadata:i,contentDispositionFilename:n,contentLength:s,hasStructTree:a}=await e.getMetadata();if(e!==this.pdfDocument)return;this.externalServices.reportTelemetry({type:"taggedPDF",data:a}),this.documentInfo=t,this.metadata=i,this._contentDispositionFilename??=n,this._contentLength??=s,console.log(`PDF ${e.fingerprints[0]} [${t.PDFFormatVersion} ${(i?.get("pdf:producer")||t.Producer||"-").trim()} / ${(i?.get("xmp:creatortool")||t.Creator||"-").trim()}] (PDF.js: ${version||"?"} [${build||"?"}])`);const o=this._docTitle;o?this.setTitle(`${o} - ${this._contentDispositionFilename||this._title}`):this._contentDispositionFilename&&this.setTitle(this._contentDispositionFilename),!t.IsXFAPresent||t.IsAcroFormPresent||e.isPureXfa?!t.IsAcroFormPresent&&!t.IsXFAPresent||this.pdfViewer.renderForms||console.warn("Warning: Interactive form support is not enabled"):e.loadingParams.enableXfa?console.warn("Warning: XFA Foreground documents are not supported"):console.warn("Warning: XFA support is not enabled"),t.IsSignaturesPresent&&console.warn("Warning: Digital signatures validation is not supported"),this.eventBus.dispatch("metadataloaded",{source:this})},async _initializePageLabels(e){const t=await e.getPageLabels();if(e!==this.pdfDocument)return;if(!t||AppOptions.get("disablePageLabels"))return;const i=t.length;let n=0,s=0;for(let e=0;e<i;e++){const i=t[e];if(i===(e+1).toString())n++;else{if(""!==i)break;s++}}if(n>=i||s>=i)return;const{pdfViewer:a,pdfThumbnailViewer:o,toolbar:r}=this;a.setPageLabels(t),o?.setPageLabels(t),r?.setPagesCount(i,!0),r?.setPageNumber(a.currentPageNumber,a.currentPageLabel)},_initializePdfHistory({fingerprint:e,viewOnLoad:t,initialDest:i=null}){this.pdfHistory&&(this.pdfHistory.initialize({fingerprint:e,resetHistory:t===ViewOnLoad.INITIAL,updateUrl:AppOptions.get("historyUpdateUrl")}),this.pdfHistory.initialBookmark&&(this.initialBookmark=this.pdfHistory.initialBookmark,this.initialRotation=this.pdfHistory.initialRotation),i&&!this.initialBookmark&&t===ViewOnLoad.UNKNOWN&&(this.initialBookmark=JSON.stringify(i),this.pdfHistory.push({explicitDest:i,pageNumber:null})))},_initializeAnnotationStorageCallbacks(e){if(e!==this.pdfDocument)return;const{annotationStorage:t}=e;t.onSetModified=()=>{window.addEventListener("beforeunload",beforeUnload),this._annotationStorageModified=!0},t.onResetModified=()=>{window.removeEventListener("beforeunload",beforeUnload),delete this._annotationStorageModified},t.onAnnotationEditor=e=>{this._hasAnnotationEditors=!!e,this.setTitle()}},setInitialView(e,{rotation:t,sidebarView:i,scrollMode:n,spreadMode:s}={}){const a=e=>{isValidRotation(e)&&(this.pdfViewer.pagesRotation=e)};this.isInitialViewSet=!0,this.viewsManager?.setInitialView(i),((e,t)=>{isValidScrollMode(e)&&(this.pdfViewer.scrollMode=e),isValidSpreadMode(t)&&(this.pdfViewer.spreadMode=t)})(n,s),this.initialBookmark?(a(this.initialRotation),delete this.initialRotation,this.pdfLinkService.setHash(this.initialBookmark),this.initialBookmark=null):e&&(a(t),this.pdfLinkService.setHash(e)),this.toolbar?.setPageNumber(this.pdfViewer.currentPageNumber,this.pdfViewer.currentPageLabel),this.secondaryToolbar?.setPageNumber(this.pdfViewer.currentPageNumber),this.pdfViewer.currentScaleValue||(this.pdfViewer.currentScaleValue="auto")},_cleanup(){this.pdfDocument&&(this.pdfViewer.cleanup(),this.pdfThumbnailViewer?.cleanup(),this.pdfDocument.cleanup(AppOptions.get("fontExtraProperties")))},forceRendering(){this.pdfRenderingQueue.printing=!!this.printService,this.pdfRenderingQueue.isThumbnailViewEnabled=this.viewsManager?.visibleView===SidebarView.THUMBS,this.pdfRenderingQueue.renderHighestPriority()},beforePrint(){this._printAnnotationStoragePromise=this.pdfScriptingManager.dispatchWillPrint().catch((()=>{})).then((()=>this.pdfDocument?.annotationStorage.print)),this.printService||(this.supportsPrinting&&this.pdfViewer.printingAllowed?this.pdfViewer.pageViewsReady?(this.printService=PDFPrintServiceFactory.createPrintService({pdfDocument:this.pdfDocument,pagesOverview:this.pdfViewer.getPagesOverview(),printContainer:this.appConfig.printContainer,printResolution:AppOptions.get("printResolution"),printAnnotationStoragePromise:this._printAnnotationStoragePromise}),this.forceRendering(),this.setTitle(),this.printService.layout(),this._hasAnnotationEditors&&this.externalServices.reportTelemetry({type:"editing",data:{type:"print",stats:this.pdfDocument?.annotationStorage.editorStats}})):this.l10n.get("pdfjs-printing-not-ready").then((e=>{window.alert(e)})):this._otherError("pdfjs-printing-not-supported"))},afterPrint(){this._printAnnotationStoragePromise&&(this._printAnnotationStoragePromise.then((()=>{this.pdfScriptingManager.dispatchDidPrint()})),this._printAnnotationStoragePromise=null),this.printService&&(this.printService.destroy(),this.printService=null,this.pdfDocument?.annotationStorage.resetModified()),this.forceRendering(),this.setTitle()},rotatePages(e){this.pdfViewer.pagesRotation+=e},requestPresentationMode(){this.pdfPresentationMode?.request()},async triggerPrinting(){this.supportsPrinting&&await this._printPermissionPromise&&window.print()},bindEvents(){if(this._eventBusAbortController)return;const e={signal:(this._eventBusAbortController=new AbortController).signal},{eventBus:t,externalServices:i,pdfDocumentProperties:n,pdfViewer:s,preferences:a}=this;t._on("resize",onResize.bind(this),e),t._on("hashchange",onHashchange.bind(this),e),t._on("beforeprint",this.beforePrint.bind(this),e),t._on("afterprint",this.afterPrint.bind(this),e),t._on("pagerender",onPageRender.bind(this),e),t._on("pagerendered",onPageRendered.bind(this),e),t._on("updateviewarea",onUpdateViewarea.bind(this),e),t._on("pagechanging",onPageChanging.bind(this),e),t._on("scalechanging",onScaleChanging.bind(this),e),t._on("rotationchanging",onRotationChanging.bind(this),e),t._on("sidebarviewchanged",onSidebarViewChanged.bind(this),e),t._on("pagemode",onPageMode.bind(this),e),t._on("namedaction",onNamedAction.bind(this),e),t._on("presentationmodechanged",(e=>s.presentationModeState=e.state),e),t._on("presentationmode",this.requestPresentationMode.bind(this),e),t._on("switchannotationeditormode",(e=>s.annotationEditorMode=e),e),t._on("print",this.triggerPrinting.bind(this),e),t._on("download",this.downloadOrSave.bind(this),e),t._on("firstpage",(()=>this.page=1),e),t._on("lastpage",(()=>this.page=this.pagesCount),e),t._on("nextpage",(()=>s.nextPage()),e),t._on("previouspage",(()=>s.previousPage()),e),t._on("zoomin",this.zoomIn.bind(this),e),t._on("zoomout",this.zoomOut.bind(this),e),t._on("zoomreset",this.zoomReset.bind(this),e),t._on("pagenumberchanged",onPageNumberChanged.bind(this),e),t._on("scalechanged",(e=>s.currentScaleValue=e.value),e),t._on("rotatecw",this.rotatePages.bind(this,90),e),t._on("rotateccw",this.rotatePages.bind(this,-90),e),t._on("optionalcontentconfig",(e=>s.optionalContentConfigPromise=e.promise),e),t._on("switchscrollmode",(e=>s.scrollMode=e.mode),e),t._on("scrollmodechanged",onViewerModesChanged.bind(this,"scrollMode"),e),t._on("switchspreadmode",(e=>s.spreadMode=e.mode),e),t._on("spreadmodechanged",onViewerModesChanged.bind(this,"spreadMode"),e),t._on("imagealttextsettings",onImageAltTextSettings.bind(this),e),t._on("documentproperties",(()=>n?.open()),e),t._on("findfromurlhash",onFindFromUrlHash.bind(this),e),t._on("updatefindmatchescount",onUpdateFindMatchesCount.bind(this),e),t._on("updatefindcontrolstate",onUpdateFindControlState.bind(this),e),t._on("fileinputchange",onFileInputChange.bind(this),e),t._on("openfile",onOpenFile.bind(this),e),t._on("pagesedited",this.onPagesEdited.bind(this),e),t._on("beforepagesedited",this.onBeforePagesEdited.bind(this),e),t._on("savepageseditedpdf",this.onSavePagesEditedPDF.bind(this),e)},bindWindowEvents(){if(this._windowAbortController)return;this._windowAbortController=new AbortController;const{eventBus:e,appConfig:{mainContainer:t},pdfViewer:i,_windowAbortController:{signal:n}}=this;if(this._touchManager=new TouchManager({container:window,isPinchingDisabled:()=>i.isInPresentationMode,isPinchingStopped:()=>this.overlayManager?.active,onPinching:this.touchPinchCallback.bind(this),onPinchEnd:this.touchPinchEndCallback.bind(this),signal:n}),function e(t=null){t&&i.refresh(),window.matchMedia(`(resolution: ${OutputScale.pixelRatio}dppx)`).addEventListener("change",e,{once:!0,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}),window.addEventListener("resize",(()=>e.dispatch("resize",{source:window})),{signal:n}),window.addEventListener("hashchange",(()=>{e.dispatch("hashchange",{source:window,hash:document.location.hash.substring(1)})}),{signal:n}),window.addEventListener("beforeprint",(()=>e.dispatch("beforeprint",{source:window})),{signal:n}),window.addEventListener("afterprint",(()=>e.dispatch("afterprint",{source:window})),{signal:n}),window.addEventListener("updatefromsandbox",(t=>{e.dispatch("updatefromsandbox",{source:window,detail:t.detail})}),{signal:n}),!("onscrollend"in document.documentElement))return;let s,a;({scrollTop:this._lastScrollTop,scrollLeft:this._lastScrollLeft}=t);const o=()=>{({scrollTop:this._lastScrollTop,scrollLeft:this._lastScrollLeft}=t),clearTimeout(s),this._isScrolling&&(a.abort(),a=null,this._isScrolling=!1)};t.addEventListener("scroll",(()=>{if(!this._isCtrlKeyDown&&(this._lastScrollTop!==t.scrollTop||this._lastScrollLeft!==t.scrollLeft)){if(!this._isScrolling){a=new AbortController;const e=AbortSignal.any([a.signal,n]);t.addEventListener("scrollend",o,{signal:e}),t.addEventListener("blur",o,{signal:e}),this._isScrolling=!0}clearTimeout(s),s=setTimeout(o,100)}}),{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()])},onBeforePagesEdited(e){this.pdfViewer.onBeforePagesEdited(e)},onPagesEdited(e){this.pdfViewer.onPagesEdited(e)},async onSavePagesEditedPDF({data:{includePages:e,excludePages:t,pageIndices:i}}){if(!this.pdfDocument)return;const n={document:null,includePages:e,excludePages:t,pageIndices:i},s=await this.pdfDocument.extractPages([n]);s?this.downloadManager.download(s,this._downloadUrl,this._docFilename):console.error("Something wrong happened when saving the edited PDF.\\nPlease file a bug.")},_accumulateTicks(e,t){(this[t]>0&&e<0||this[t]<0&&e>0)&&(this[t]=0),this[t]+=e;const i=Math.trunc(this[t]);return this[t]-=i,i},_accumulateFactor(e,t,i){if(1===t)return 1;(this[i]>1&&t<1||this[i]<1&&t>1)&&(this[i]=1);const n=Math.floor(e*t*this[i]*100)/(100*e);return this[i]=t/n,n},_unblockDocumentLoadEvent(){document.blockUnblockOnload?.(!1),this._unblockDocumentLoadEvent=()=>{}},get scriptingReady(){return this.pdfScriptingManager.ready}};initCom(PDFViewerApplication),PDFPrintServiceFactory.initGlobals(PDFViewerApplication);{const e=new Set(["null","http://mozilla.github.io","https://mozilla.github.io"]);var validateFileURL=function(t){if(!t)return;const i=URL.parse(window.location)?.origin||"null";if(e.has(i))return;const n=URL.parse(t,window.location)?.origin;if(n===i)return;const s=new Error("file origin does not match viewer\'s");throw PDFViewerApplication._documentError("pdfjs-loading-error",{message:s.message}),s},onFileInputChange=function(e){if(this.pdfViewer?.isInPresentationMode)return;const t=e.fileInput.files[0];this.open({url:URL.createObjectURL(t),originalUrl:encodeURIComponent(t.name)})},onOpenFile=function(e){this._openFileInput?.click()}}function onPageRender({pageNumber:e}){e===this.page&&this.toolbar?.updateLoadingIndicatorState(!0)}function onPageRendered({pageNumber:e,isDetailView:t,error:i}){if(e===this.page&&this.toolbar?.updateLoadingIndicatorState(!1),!t&&this.viewsManager?.visibleView===SidebarView.THUMBS){const t=this.pdfViewer.getPageView(e-1),i=this.pdfThumbnailViewer?.getThumbnail(e-1);t&&i?.setImage(t)}i&&this._otherError("pdfjs-rendering-error",i)}function onPageMode({mode:e}){let t;switch(e){case"thumbs":t=SidebarView.THUMBS;break;case"bookmarks":case"outline":t=SidebarView.OUTLINE;break;case"attachments":t=SidebarView.ATTACHMENTS;break;case"layers":t=SidebarView.LAYERS;break;case"none":t=SidebarView.NONE;break;default:return void console.error(\'Invalid "pagemode" hash parameter: \'+e)}this.viewsManager?.switchView(t,!0)}function onNamedAction(e){switch(e.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:e}){this.pdfRenderingQueue.isThumbnailViewEnabled=e===SidebarView.THUMBS,this.isInitialViewSet&&this.store?.set("sidebarView",e).catch((()=>{}))}function onUpdateViewarea({location:e}){this.isInitialViewSet&&this.store?.setMultiple({page:e.pageNumber,zoom:e.scale,scrollLeft:e.left,scrollTop:e.top,rotation:e.rotation}).catch((()=>{})),this.appConfig.secondaryToolbar&&(this.appConfig.secondaryToolbar.viewBookmarkButton.href=this.pdfLinkService.getAnchorUrl(e.pdfOpenParams))}function onViewerModesChanged(e,t){this.isInitialViewSet&&!this.pdfViewer.isInPresentationMode&&this.store?.set(e,t.mode).catch((()=>{}))}function onResize(){const{pdfDocument:e,pdfViewer:t,pdfRenderingQueue:i}=this;if(i.printing&&window.matchMedia("print").matches)return;if(!e)return;const n=t.currentScaleValue;"auto"!==n&&"page-fit"!==n&&"page-width"!==n||(t.currentScaleValue=n),t.update()}function onHashchange(e){const t=e.hash;t&&(this.isInitialViewSet?this.pdfHistory?.popStateInProgress||this.pdfLinkService.setHash(t):this.initialBookmark=t)}function onPageNumberChanged(e){const{pdfViewer:t}=this;""!==e.value&&this.pdfLinkService.goToPage(e.value),e.value!==t.currentPageNumber.toString()&&e.value!==t.currentPageLabel&&this.toolbar?.setPageNumber(t.currentPageNumber,t.currentPageLabel)}function onImageAltTextSettings(){this.imageAltTextSettings?.open({enableGuessAltText:AppOptions.get("enableGuessAltText"),enableNewAltTextWhenAddingImage:AppOptions.get("enableNewAltTextWhenAddingImage")})}function onFindFromUrlHash(e){this.eventBus.dispatch("find",{source:e.source,type:"",query:e.query,caseSensitive:!1,entireWord:!1,highlightAll:!0,findPrevious:!1,matchDiacritics:!0})}function onUpdateFindMatchesCount({matchesCount:e}){this.supportsIntegratedFind?this.externalServices.updateFindMatchesCount(e):this.findBar?.updateResultsCount(e)}function onUpdateFindControlState({state:e,previous:t,entireWord:i,matchesCount:n,rawQuery:s}){this.supportsIntegratedFind?this.externalServices.updateFindControlState({result:e,findPrevious:t,entireWord:i,matchesCount:n,rawQuery:s}):this.findBar?.updateUIState(e,t,n)}function onScaleChanging(e){this.toolbar?.setPageScale(e.presetValue,e.scale),this.pdfViewer.update()}function onRotationChanging(e){this.pdfThumbnailViewer&&(this.pdfThumbnailViewer.pagesRotation=e.pagesRotation),this.forceRendering(),this.pdfViewer.currentPageNumber=e.pageNumber}function onPageChanging({pageNumber:e,pageLabel:t}){this.toolbar?.setPageNumber(e,t),this.secondaryToolbar?.setPageNumber(e),this.viewsManager?.visibleView===SidebarView.THUMBS&&this.pdfThumbnailViewer?.scrollThumbnailIntoView(e);const i=this.pdfViewer.getPageView(e-1);this.toolbar?.updateLoadingIndicatorState(i?.renderingState===RenderingStates.RUNNING)}function onWheel(e){const{pdfViewer:t,supportsMouseWheelZoomCtrlKey:i,supportsMouseWheelZoomMetaKey:n,supportsPinchToZoom:s}=this;if(t.isInPresentationMode)return;const a=e.deltaMode;let o=Math.exp(-e.deltaY/100);const r=e.ctrlKey&&!this._isCtrlKeyDown&&a===WheelEvent.DOM_DELTA_PIXEL&&0===e.deltaX&&(Math.abs(o-1)<.05||!1)&&0===e.deltaZ,l=[e.clientX,e.clientY];if(r||e.ctrlKey&&i||e.metaKey&&n){if(e.preventDefault(),this._isScrolling||"hidden"===document.visibilityState||this.overlayManager.active)return;if(r&&s)o=this._accumulateFactor(t.currentScale,o,"_wheelUnusedFactor"),this.updateZoom(null,o,l);else{const t=normalizeWheelEventDirection(e);let i=0;if(a===WheelEvent.DOM_DELTA_LINE||a===WheelEvent.DOM_DELTA_PAGE)i=Math.abs(t)>=1?Math.sign(t):this._accumulateTicks(t,"_wheelUnusedTicks");else{const e=30;i=this._accumulateTicks(t/e,"_wheelUnusedTicks")}this.updateZoom(i,null,l)}}}function closeSecondaryToolbar({target:e}){if(!this.secondaryToolbar?.isOpen)return;const{toolbar:t,secondaryToolbar:i}=this.appConfig;(this.pdfViewer.containsElement(e)||t?.container.contains(e)&&!i?.toolbar.contains(e)&&!i?.toggleButton.contains(e))&&this.secondaryToolbar.close()}function closeEditorUndoBar(e){this.editorUndoBar?.isOpen&&this.appConfig.secondaryToolbar?.toolbar.contains(e.target)&&this.editorUndoBar.hide()}function onClick(e){closeSecondaryToolbar.call(this,e),closeEditorUndoBar.call(this,e)}function onKeyUp(e){"Control"===e.key&&(this._isCtrlKeyDown=!1)}function onKeyDown(e){if(this._isCtrlKeyDown="Control"===e.key,this.editorUndoBar?.isOpen&&9!==e.keyCode&&16!==e.keyCode&&(13!==e.keyCode&&32!==e.keyCode||getActiveOrFocusedElement()!==this.appConfig.editorUndoBar.undoButton)&&this.editorUndoBar.hide(),this.overlayManager.active)return;const{eventBus:t,pdfViewer:i}=this,n=i.isInPresentationMode;let s=!1,a=!1;const o=(e.ctrlKey?1:0)|(e.altKey?2:0)|(e.shiftKey?4:0)|(e.metaKey?8:0);if(1===o||8===o||5===o||12===o)switch(e.keyCode){case 70:this.supportsIntegratedFind||e.shiftKey||(this.findBar?.open(),s=!0);break;case 71:if(!this.supportsIntegratedFind){const{state:e}=this.findController;if(e){const i={source:window,type:"again",findPrevious:5===o||12===o};t.dispatch("find",{...e,...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:n||(setTimeout((()=>{this.zoomReset()})),s=!1);break;case 38:(n||this.page>1)&&(this.page=1,s=!0,a=!0);break;case 40:(n||this.page<this.pagesCount)&&(this.page=this.pagesCount,s=!0,a=!0)}if(1===o||8===o)switch(e.keyCode){case 83:t.dispatch("download",{source:window}),s=!0;break;case 79:t.dispatch("openfile",{source:window}),s=!0}if(3===o||10===o)switch(e.keyCode){case 80:this.requestPresentationMode(),s=!0,this.externalServices.reportTelemetry({type:"buttons",data:{id:"presentationModeKeyboard"}});break;case 71:this.appConfig.toolbar&&(this.appConfig.toolbar.pageNumber.select(),s=!0)}if(s)return a&&!n&&i.focus(),void e.preventDefault();const r=getActiveOrFocusedElement(),l=r?.tagName.toUpperCase();if(!("INPUT"===l||"TEXTAREA"===l||"SELECT"===l||"BUTTON"===l&&32===e.keyCode||r?.isContentEditable)||27===e.keyCode){if(0===o){let t=0,o=!1;switch(e.keyCode){case 38:if(this.supportsCaretBrowsingMode){this.moveCaret(!0,!1),s=!0;break}case 33:i.isVerticalScrollbarEnabled&&(o=!0),t=-1;break;case 8:n||(o=!0),t=-1;break;case 37:if(this.supportsCaretBrowsingMode)return;i.isHorizontalScrollbarEnabled&&(o=!0);case 75:case 80:t=-1;break;case 27:this.secondaryToolbar?.isOpen&&(this.secondaryToolbar.close(),s=!0),!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&&(o=!0),t=1;break;case 32:n||(o=!0),t=1;break;case 39:if(this.supportsCaretBrowsingMode)return;i.isHorizontalScrollbarEnabled&&(o=!0);case 74:case 78:t=1;break;case 36:(n||this.page>1)&&(this.page=1,s=!0,a=!0);break;case 35:(n||this.page<this.pagesCount)&&(this.page=this.pagesCount,s=!0,a=!0);break;case 83:this.pdfCursorTools?.switchTool(CursorTool.SELECT);break;case 72:this.pdfCursorTools?.switchTool(CursorTool.HAND);break;case 82:this.rotatePages(90);break;case 115:this.viewsManager?.toggle()}0===t||o&&"page-fit"!==i.currentScaleValue||(t>0?i.nextPage():i.previousPage(),s=!0)}if(4===o)switch(e.keyCode){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)}s||n||(e.keyCode>=33&&e.keyCode<=40||32===e.keyCode&&"BUTTON"!==l)&&(a=!0),a&&!i.containsElement(r)&&i.focus(),s&&e.preventDefault()}}function beforeUnload(e){return e.preventDefault(),e.returnValue="",!1}const AppConstants={LinkTarget:LinkTarget,RenderingStates:RenderingStates,ScrollMode:ScrollMode,SpreadMode:SpreadMode};function getViewerConfiguration(){return{appContainer:document.body,principalContainer:document.getElementById("mainContainer"),mainContainer:document.getElementById("viewerContainer"),viewerContainer:document.getElementById("viewer"),viewerAlert:document.getElementById("viewer-alert"),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("zoomInButton"),zoomOut:document.getElementById("zoomOutButton"),print:document.getElementById("printButton"),editorCommentButton:document.getElementById("editorCommentButton"),editorCommentParamsToolbar:document.getElementById("editorCommentParamsToolbar"),editorFreeTextButton:document.getElementById("editorFreeTextButton"),editorFreeTextParamsToolbar:document.getElementById("editorFreeTextParamsToolbar"),editorHighlightButton:document.getElementById("editorHighlightButton"),editorHighlightParamsToolbar:document.getElementById("editorHighlightParamsToolbar"),editorHighlightColorPicker:document.getElementById("editorHighlightColorPicker"),editorInkButton:document.getElementById("editorInkButton"),editorInkParamsToolbar:document.getElementById("editorInkParamsToolbar"),editorStampButton:document.getElementById("editorStampButton"),editorStampParamsToolbar:document.getElementById("editorStampParamsToolbar"),editorSignatureButton:document.getElementById("editorSignatureButton"),editorSignatureParamsToolbar:document.getElementById("editorSignatureParamsToolbar"),download:document.getElementById("downloadButton")},secondaryToolbar:{toolbar:document.getElementById("secondaryToolbar"),toggleButton:document.getElementById("secondaryToolbarToggleButton"),presentationModeButton:document.getElementById("presentationMode"),openFileButton:document.getElementById("secondaryOpenFile"),printButton:document.getElementById("secondaryPrint"),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")},viewsManager:{outerContainer:document.getElementById("outerContainer"),toggleButton:document.getElementById("viewsManagerToggleButton"),sidebarContainer:document.getElementById("viewsManager"),resizer:document.getElementById("viewsManagerResizer"),thumbnailButton:document.getElementById("thumbnailsViewMenu"),outlineButton:document.getElementById("outlinesViewMenu"),attachmentsButton:document.getElementById("attachmentsViewMenu"),layersButton:document.getElementById("layersViewMenu"),viewsManagerSelectorButton:document.getElementById("viewsManagerSelectorButton"),viewsManagerSelectorOptions:document.getElementById("viewsManagerSelectorOptions"),thumbnailsView:document.getElementById("thumbnailsView"),outlinesView:document.getElementById("outlinesView"),attachmentsView:document.getElementById("attachmentsView"),layersView:document.getElementById("layersView"),viewsManagerAddFileButton:document.getElementById("viewsManagerAddFileButton"),viewsManagerCurrentOutlineButton:document.getElementById("viewsManagerCurrentOutlineButton"),viewsManagerHeaderLabel:document.getElementById("viewsManagerHeaderLabel"),manageMenu:{button:document.getElementById("viewsManagerStatusActionButton"),menu:document.getElementById("viewsManagerStatusActionOptions"),copy:document.getElementById("viewsManagerStatusActionCopy"),cut:document.getElementById("viewsManagerStatusActionCut"),delete:document.getElementById("viewsManagerStatusActionDelete"),saveAs:document.getElementById("viewsManagerStatusActionSaveAs")}},findBar:{bar:document.getElementById("findbar"),toggleButton:document.getElementById("viewFindButton"),findField:document.getElementById("findInput"),highlightAllCheckbox:document.getElementById("findHighlightAll"),caseSensitiveCheckbox:document.getElementById("findMatchCase"),matchDiacriticsCheckbox:document.getElementById("findMatchDiacritics"),entireWordCheckbox:document.getElementById("findEntireWord"),findMsg:document.getElementById("findMsg"),findResultsCount:document.getElementById("findResultsCount"),findPreviousButton:document.getElementById("findPreviousButton"),findNextButton:document.getElementById("findNextButton")},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")},addSignatureDialog:{dialog:document.getElementById("addSignatureDialog"),panels:document.getElementById("addSignatureActionContainer"),typeButton:document.getElementById("addSignatureTypeButton"),typeInput:document.getElementById("addSignatureTypeInput"),drawButton:document.getElementById("addSignatureDrawButton"),drawSVG:document.getElementById("addSignatureDraw"),drawPlaceholder:document.getElementById("addSignatureDrawPlaceholder"),drawThickness:document.getElementById("addSignatureDrawThickness"),imageButton:document.getElementById("addSignatureImageButton"),imageSVG:document.getElementById("addSignatureImage"),imagePlaceholder:document.getElementById("addSignatureImagePlaceholder"),imagePicker:document.getElementById("addSignatureFilePicker"),imagePickerLink:document.getElementById("addSignatureImageBrowse"),description:document.getElementById("addSignatureDescription"),clearButton:document.getElementById("clearSignatureButton"),saveContainer:document.getElementById("addSignatureSaveContainer"),saveCheckbox:document.getElementById("addSignatureSaveCheckbox"),errorBar:document.getElementById("addSignatureError"),errorTitle:document.getElementById("addSignatureErrorTitle"),errorDescription:document.getElementById("addSignatureErrorDescription"),errorCloseButton:document.getElementById("addSignatureErrorCloseButton"),cancelButton:document.getElementById("addSignatureCancelButton"),addButton:document.getElementById("addSignatureAddButton")},editSignatureDialog:{dialog:document.getElementById("editSignatureDescriptionDialog"),description:document.getElementById("editSignatureDescription"),editSignatureView:document.getElementById("editSignatureView"),cancelButton:document.getElementById("editSignatureCancelButton"),updateButton:document.getElementById("editSignatureUpdateButton")},annotationEditorParams:{editorCommentsSidebar:document.getElementById("editorCommentsSidebar"),editorCommentsSidebarCount:document.getElementById("editorCommentsSidebarCount"),editorCommentsSidebarTitle:document.getElementById("editorCommentsSidebarTitle"),editorCommentsSidebarCloseButton:document.getElementById("editorCommentsSidebarCloseButton"),editorCommentsSidebarList:document.getElementById("editorCommentsSidebarList"),editorCommentsSidebarResizer:document.getElementById("editorCommentsSidebarResizer"),editorFreeTextFontSize:document.getElementById("editorFreeTextFontSize"),editorFreeTextColor:document.getElementById("editorFreeTextColor"),editorInkColor:document.getElementById("editorInkColor"),editorInkThickness:document.getElementById("editorInkThickness"),editorInkOpacity:document.getElementById("editorInkOpacity"),editorStampAddImage:document.getElementById("editorStampAddImage"),editorSignatureAddSignature:document.getElementById("editorSignatureAddSignature"),editorFreeHighlightThickness:document.getElementById("editorFreeHighlightThickness"),editorHighlightShowAll:document.getElementById("editorHighlightShowAll")},printContainer:document.getElementById("printContainer"),editorUndoBar:{container:document.getElementById("editorUndoBar"),message:document.getElementById("editorUndoBarMessage"),undoButton:document.getElementById("editorUndoBarUndoButton"),closeButton:document.getElementById("editorUndoBarCloseButton")},editCommentDialog:{dialog:document.getElementById("commentManagerDialog"),toolbar:document.getElementById("commentManagerToolbar"),title:document.getElementById("commentManagerTitle"),textInput:document.getElementById("commentManagerTextInput"),cancelButton:document.getElementById("commentManagerCancelButton"),saveButton:document.getElementById("commentManagerSaveButton")}}}function webViewerLoad(){const e=getViewerConfiguration(),t=new CustomEvent("webviewerloaded",{bubbles:!0,cancelable:!0,detail:{source:window}});try{parent.document.dispatchEvent(t)}catch(e){console.error("webviewerloaded:",e),document.dispatchEvent(t)}PDFViewerApplication.run(e)}window.PDFViewerApplication=PDFViewerApplication,window.PDFViewerApplicationConstants=AppConstants,window.PDFViewerApplicationOptions=AppOptions,document.blockUnblockOnload?.(!0),"interactive"===document.readyState||"complete"===document.readyState?webViewerLoad():document.addEventListener("DOMContentLoaded",webViewerLoad,!0);export{PDFViewerApplication,AppConstants as PDFViewerApplicationConstants,AppOptions as PDFViewerApplicationOptions};';
2
+ export {
3
+ e as default
4
+ };