dash-pdf-components 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -12
- package/dash_pdf_components/dash_pdf_components.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):"object"==typeof exports?exports.dash_pdf_components=e(require("react")):t.dash_pdf_components=e(t.React)}(self,t=>(()=>{"use strict";var e={810(t,e,i){var n=i(177),s=i.n(n),r=i(274),a=i.n(r)()(s());a.push([t.id,"/* Copyright 2014 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\n:root {\n --react-pdf-annotation-layer: 1;\n --annotation-unfocused-field-background: url(\"data:image/svg+xml;charset=UTF-8,<svg width='1px' height='1px' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' style='fill:rgba(0, 54, 255, 0.13);'/></svg>\");\n --input-focus-border-color: Highlight;\n --input-focus-outline: 1px solid Canvas;\n --input-unfocused-border-color: transparent;\n --input-disabled-border-color: transparent;\n --input-hover-border-color: black;\n --link-outline: none;\n}\n\n@media screen and (forced-colors: active) {\n :root {\n --input-focus-border-color: CanvasText;\n --input-unfocused-border-color: ActiveText;\n --input-disabled-border-color: GrayText;\n --input-hover-border-color: Highlight;\n --link-outline: 1.5px solid LinkText;\n }\n .annotationLayer .textWidgetAnnotation :is(input, textarea):required,\n .annotationLayer .choiceWidgetAnnotation select:required,\n .annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {\n outline: 1.5px solid selectedItem;\n }\n\n .annotationLayer .linkAnnotation:hover {\n backdrop-filter: invert(100%);\n }\n}\n\n.annotationLayer {\n position: absolute;\n top: 0;\n left: 0;\n pointer-events: none;\n transform-origin: 0 0;\n z-index: 3;\n}\n\n.annotationLayer[data-main-rotation='90'] .norotate {\n transform: rotate(270deg) translateX(-100%);\n}\n.annotationLayer[data-main-rotation='180'] .norotate {\n transform: rotate(180deg) translate(-100%, -100%);\n}\n.annotationLayer[data-main-rotation='270'] .norotate {\n transform: rotate(90deg) translateY(-100%);\n}\n\n.annotationLayer canvas {\n position: absolute;\n width: 100%;\n height: 100%;\n}\n\n.annotationLayer section {\n position: absolute;\n text-align: initial;\n pointer-events: auto;\n box-sizing: border-box;\n margin: 0;\n transform-origin: 0 0;\n}\n\n.annotationLayer .linkAnnotation {\n outline: var(--link-outline);\n}\n\n.textLayer.selecting ~ .annotationLayer section {\n pointer-events: none;\n}\n\n.annotationLayer :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a {\n position: absolute;\n font-size: 1em;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n}\n\n.annotationLayer :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a:hover {\n opacity: 0.2;\n background: rgba(255, 255, 0, 1);\n box-shadow: 0 2px 10px rgba(255, 255, 0, 1);\n}\n\n.annotationLayer .textAnnotation img {\n position: absolute;\n cursor: pointer;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea),\n.annotationLayer .choiceWidgetAnnotation select,\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input {\n background-image: var(--annotation-unfocused-field-background);\n border: 2px solid var(--input-unfocused-border-color);\n box-sizing: border-box;\n font: calc(9px * var(--total-scale-factor)) sans-serif;\n height: 100%;\n margin: 0;\n vertical-align: top;\n width: 100%;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea):required,\n.annotationLayer .choiceWidgetAnnotation select:required,\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {\n outline: 1.5px solid red;\n}\n\n.annotationLayer .choiceWidgetAnnotation select option {\n padding: 0;\n}\n\n.annotationLayer .buttonWidgetAnnotation.radioButton input {\n border-radius: 50%;\n}\n\n.annotationLayer .textWidgetAnnotation textarea {\n resize: none;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea)[disabled],\n.annotationLayer .choiceWidgetAnnotation select[disabled],\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input[disabled] {\n background: none;\n border: 2px solid var(--input-disabled-border-color);\n cursor: not-allowed;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea):hover,\n.annotationLayer .choiceWidgetAnnotation select:hover,\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:hover {\n border: 2px solid var(--input-hover-border-color);\n}\n.annotationLayer .textWidgetAnnotation :is(input, textarea):hover,\n.annotationLayer .choiceWidgetAnnotation select:hover,\n.annotationLayer .buttonWidgetAnnotation.checkBox input:hover {\n border-radius: 2px;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea):focus,\n.annotationLayer .choiceWidgetAnnotation select:focus {\n background: none;\n border: 2px solid var(--input-focus-border-color);\n border-radius: 2px;\n outline: var(--input-focus-outline);\n}\n\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) :focus {\n background-image: none;\n background-color: transparent;\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox :focus {\n border: 2px solid var(--input-focus-border-color);\n border-radius: 2px;\n outline: var(--input-focus-outline);\n}\n\n.annotationLayer .buttonWidgetAnnotation.radioButton :focus {\n border: 2px solid var(--input-focus-border-color);\n outline: var(--input-focus-outline);\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after,\n.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before {\n background-color: CanvasText;\n content: '';\n display: block;\n position: absolute;\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after {\n height: 80%;\n left: 45%;\n width: 1px;\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before {\n transform: rotate(45deg);\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after {\n transform: rotate(-45deg);\n}\n\n.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before {\n border-radius: 50%;\n height: 50%;\n left: 30%;\n top: 20%;\n width: 50%;\n}\n\n.annotationLayer .textWidgetAnnotation input.comb {\n font-family: monospace;\n padding-left: 2px;\n padding-right: 0;\n}\n\n.annotationLayer .textWidgetAnnotation input.comb:focus {\n /*\n * Letter spacing is placed on the right side of each character. Hence, the\n * letter spacing of the last character may be placed outside the visible\n * area, causing horizontal scrolling. We avoid this by extending the width\n * when the element has focus and revert this when it loses focus.\n */\n width: 103%;\n}\n\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input {\n appearance: none;\n}\n\n.annotationLayer .popupTriggerArea {\n height: 100%;\n width: 100%;\n}\n\n.annotationLayer .fileAttachmentAnnotation .popupTriggerArea {\n position: absolute;\n}\n\n.annotationLayer .popupWrapper {\n position: absolute;\n font-size: calc(9px * var(--total-scale-factor));\n width: 100%;\n min-width: calc(180px * var(--total-scale-factor));\n pointer-events: none;\n}\n\n.annotationLayer .popup {\n position: absolute;\n max-width: calc(180px * var(--total-scale-factor));\n background-color: rgba(255, 255, 153, 1);\n box-shadow: 0 calc(2px * var(--total-scale-factor)) calc(5px * var(--total-scale-factor))\n rgba(136, 136, 136, 1);\n border-radius: calc(2px * var(--total-scale-factor));\n padding: calc(6px * var(--total-scale-factor));\n margin-left: calc(5px * var(--total-scale-factor));\n cursor: pointer;\n font: message-box;\n white-space: normal;\n word-wrap: break-word;\n pointer-events: auto;\n}\n\n.annotationLayer .popup > * {\n font-size: calc(9px * var(--total-scale-factor));\n}\n\n.annotationLayer .popup h1 {\n display: inline-block;\n}\n\n.annotationLayer .popupDate {\n display: inline-block;\n margin-left: calc(5px * var(--total-scale-factor));\n}\n\n.annotationLayer .popupContent {\n border-top: 1px solid rgba(51, 51, 51, 1);\n margin-top: calc(2px * var(--total-scale-factor));\n padding-top: calc(2px * var(--total-scale-factor));\n}\n\n.annotationLayer .richText > * {\n white-space: pre-wrap;\n font-size: calc(9px * var(--total-scale-factor));\n}\n\n.annotationLayer .highlightAnnotation,\n.annotationLayer .underlineAnnotation,\n.annotationLayer .squigglyAnnotation,\n.annotationLayer .strikeoutAnnotation,\n.annotationLayer .freeTextAnnotation,\n.annotationLayer .lineAnnotation svg line,\n.annotationLayer .squareAnnotation svg rect,\n.annotationLayer .circleAnnotation svg ellipse,\n.annotationLayer .polylineAnnotation svg polyline,\n.annotationLayer .polygonAnnotation svg polygon,\n.annotationLayer .caretAnnotation,\n.annotationLayer .inkAnnotation svg polyline,\n.annotationLayer .stampAnnotation,\n.annotationLayer .fileAttachmentAnnotation {\n cursor: pointer;\n}\n\n.annotationLayer section svg {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n}\n\n.annotationLayer .annotationTextContent {\n position: absolute;\n width: 100%;\n height: 100%;\n opacity: 0;\n color: transparent;\n user-select: none;\n pointer-events: none;\n}\n\n.annotationLayer .annotationTextContent span {\n width: 100%;\n display: inline-block;\n}\n",""]);const o=a;i.d(e,["A",0,o])},808(t,e,i){var n=i(177),s=i.n(n),r=i(274),a=i.n(r)()(s());a.push([t.id,"/* Copyright 2014 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\n:root {\n --react-pdf-text-layer: 1;\n}\n\n[data-main-rotation='90'] {\n transform: rotate(90deg) translateY(-100%);\n}\n[data-main-rotation='180'] {\n transform: rotate(180deg) translate(-100%, -100%);\n}\n[data-main-rotation='270'] {\n transform: rotate(270deg) translateX(-100%);\n}\n\n.textLayer {\n color-scheme: only light;\n\n position: absolute;\n text-align: initial;\n inset: 0;\n overflow: clip;\n opacity: 1;\n line-height: 1;\n text-size-adjust: none;\n forced-color-adjust: none;\n transform-origin: 0 0;\n caret-color: CanvasText;\n z-index: 0;\n\n /* We multiply the font size by --min-font-size, and then scale the text\n * elements by 1/--min-font-size. This allows us to effectively ignore the\n * minimum font size enforced by the browser, so that the text layer <span>s\n * can always match the size of the text in the canvas. */\n --min-font-size: 1;\n --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size));\n --min-font-size-inv: calc(1 / var(--min-font-size));\n}\n\n.textLayer :is(span, br) {\n color: transparent;\n position: absolute;\n white-space: pre;\n cursor: text;\n margin: 0;\n transform-origin: 0 0;\n}\n\n.textLayer > :not(.markedContent),\n.textLayer .markedContent span:not(.markedContent) {\n z-index: 1;\n\n --font-height: 0; /* set by text_layer.js */\n font-size: calc(var(--text-scale-factor) * var(--font-height));\n\n --scale-x: 1;\n --rotate: 0deg;\n transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv));\n}\n\n.textLayer .markedContent {\n display: contents;\n}\n\n.textLayer span[role='img'] {\n user-select: none;\n cursor: default;\n}\n\n.textLayer .highlight {\n --highlight-bg-color: rgb(180 0 170 / 0.25);\n --highlight-selected-bg-color: rgb(0 100 0 / 0.25);\n --highlight-backdrop-filter: none;\n --highlight-selected-backdrop-filter: none;\n\n margin: -1px;\n padding: 1px;\n background-color: var(--highlight-bg-color);\n backdrop-filter: var(--highlight-backdrop-filter);\n border-radius: 4px;\n}\n\n@media screen and (forced-colors: active) {\n .textLayer .highlight {\n --highlight-bg-color: Highlight;\n --highlight-selected-bg-color: ButtonText;\n }\n}\n\n.textLayer .highlight.appended {\n position: initial;\n}\n\n.textLayer .highlight.begin {\n border-radius: 4px 0 0 4px;\n}\n\n.textLayer .highlight.end {\n border-radius: 0 4px 4px 0;\n}\n\n.textLayer .highlight.middle {\n border-radius: 0;\n}\n\n.textLayer .highlight.selected {\n background-color: var(--highlight-selected-bg-color);\n backdrop-filter: var(--highlight-selected-backdrop-filter);\n}\n\n.textLayer ::selection {\n background: rgba(0 0 255 / 0.25);\n}\n\n@supports (background: color-mix(in srgb, AccentColor, transparent 75%)) {\n .textLayer ::selection {\n background: color-mix(in srgb, AccentColor, transparent 75%);\n }\n}\n\n/* Avoids https://github.com/mozilla/pdf.js/issues/13840 in Chrome */\n.textLayer br::selection {\n background: transparent;\n}\n\n.textLayer .endOfContent {\n display: block;\n position: absolute;\n inset: 100% 0 0;\n z-index: 0;\n cursor: default;\n user-select: none;\n}\n\n.textLayer.selecting .endOfContent {\n top: 0;\n}\n\n.hiddenCanvasElement {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 0;\n display: none;\n}\n",""]);const o=a;i.d(e,["A",0,o])},274(t){t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var i="",n=void 0!==e[5];return e[4]&&(i+="@supports (".concat(e[4],") {")),e[2]&&(i+="@media ".concat(e[2]," {")),n&&(i+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),i+=t(e),n&&(i+="}"),e[2]&&(i+="}"),e[4]&&(i+="}"),i}).join("")},e.i=function(t,i,n,s,r){"string"==typeof t&&(t=[[null,t,void 0]]);var a={};if(n)for(var o=0;o<this.length;o++){var l=this[o][0];null!=l&&(a[l]=!0)}for(var h=0;h<t.length;h++){var c=[].concat(t[h]);n&&a[c[0]]||(void 0!==r&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=r),i&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=i):c[2]=i),s&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=s):c[4]="".concat(s)),e.push(c))}},e}},177(t){t.exports=function(t){return t[1]}},295(e){e.exports=t}};const i={};function n(t){const s=i[t];if(void 0!==s)return s.exports;const r=i[t]={id:t,exports:{}};return e[t](r,r.exports,n),r.exports}n.n=t=>{const e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.cw=t=>{var e;return()=>{if(t){var i=t;t=0,e={exports:{}},i.call(e.exports,e,e.exports)}return e.exports}},n.d=(t,e)=>{if(Array.isArray(e))for(var i=0;i<e.length;){var s=e[i++],r=e[i++],a=0===r?{enumerable:!0,value:e[i++]}:{enumerable:!0,get:r};n.o(t,s)||Object.defineProperty(t,s,a)}else for(var s in e)n.o(e,s)&&!n.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{let t;n.g.importScripts&&(t=n.g.location+"");const e=n.g.document;if(!t&&e&&("SCRIPT"===e.currentScript?.tagName.toUpperCase()&&(t=e.currentScript.src),!t)){const i=e.getElementsByTagName("script");if(i.length){let e=i.length-1;for(;e>-1&&(!t||!/^https?:/.test(t));)t=i[e--].src}}if(!t)throw new Error("Automatic publicPath is not supported in this browser");t=t.replace(/^blob:|[?#].*$/g,"").replace(/\/[^/]+$/,"/"),n.p=t})(),n.nc=void 0;let s={};n.r(s),n.d(s,{Document:()=>qr,Outline:()=>na,PDF:()=>Ma,Page:()=>Da,Thumbnail:()=>La});var r=n.cw(function(t,e){var i=[];function n(t){for(var e=-1,n=0;n<i.length;n++)if(i[n].identifier===t){e=n;break}return e}function s(t,e){for(var s={},a=[],o=0;o<t.length;o++){var l=t[o],h=e.base?l[0]+e.base:l[0],c=s[h]||0,d="".concat(h," ").concat(c);s[h]=c+1;var u=n(d),p={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==u)i[u].references++,i[u].updater(p);else{var g=r(p,e);e.byIndex=o,i.splice(o,0,{identifier:d,updater:g,references:1})}a.push(d)}return a}function r(t,e){var i=e.domAPI(e);i.update(t);return function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap&&e.supports===t.supports&&e.layer===t.layer)return;i.update(t=e)}else i.remove()}}t.exports=function(t,e){var r=s(t=t||[],e=e||{});return function(t){t=t||[];for(var a=0;a<r.length;a++){var o=n(r[a]);i[o].references--}for(var l=s(t,e),h=0;h<r.length;h++){var c=n(r[h]);0===i[c].references&&(i[c].updater(),i.splice(c,1))}r=l}}}),a=n.cw(function(t,e){var i={};t.exports=function(t,e){var n=function(t){if(void 0===i[t]){var e=document.querySelector(t);if(window.HTMLIFrameElement&&e instanceof window.HTMLIFrameElement)try{e=e.contentDocument.head}catch(t){e=null}i[t]=e}return i[t]}(t);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");n.appendChild(e)}}),o=n.cw(function(t,e){t.exports=function(t){var e=document.createElement("style");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}}),l=n.cw(function(t,e){t.exports=function(t){var e=n.nc;e&&t.setAttribute("nonce",e)}}),h=n.cw(function(t,e){t.exports=function(t){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var e=t.insertStyleElement(t);return{update:function(i){!function(t,e,i){var n="";i.supports&&(n+="@supports (".concat(i.supports,") {")),i.media&&(n+="@media ".concat(i.media," {"));var s=void 0!==i.layer;s&&(n+="@layer".concat(i.layer.length>0?" ".concat(i.layer):""," {")),n+=i.css,s&&(n+="}"),i.media&&(n+="}"),i.supports&&(n+="}");var r=i.sourceMap;r&&"undefined"!=typeof btoa&&(n+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r))))," */")),e.styleTagTransform(n,t,e.options)}(e,t,i)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}}),c=n.cw(function(t,e){t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}}),d=n.cw(function(t,e){var i=function(){};t.exports=i}),u={};n.r(u),n.d(u,{dU:()=>Es,ng:()=>L,EA:()=>sn,Tm:()=>Fn,SS:()=>nt,D6:()=>Rn,YE:()=>Ln});const p=window.ReactJSXRuntime||(window.ReactJSXRuntime=function(t){function e(e,i,n){var s={},r=null;if(null!=i)for(var a in void 0!==i.key&&(s.key=""+i.key),i)Object.prototype.hasOwnProperty.call(i,a)&&"key"!==a&&"__self"!==a&&"__source"!==a&&("children"===a?r=i[a]:s[a]=i[a]);return void 0!==n&&(s.key=""+n),null==r?t.createElement(e,s):Array.isArray(r)?t.createElement.apply(t,[e,s].concat(r)):t.createElement(e,s,r)}return{jsx:e,jsxs:e,jsxDEV:e,Fragment:t.Fragment}}(window.React));var g=n(295);function m(t){var e,i,n="";if("string"==typeof t||"number"==typeof t)n+=t;else if("object"==typeof t)if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(i=m(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}const f=function(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=m(t))&&(n&&(n+=" "),n+=e);return n};var b=Object.prototype.hasOwnProperty;function v(t,e,i){for(i of t.keys())if(y(i,e))return i}function y(t,e){var i,n,s;if(t===e)return!0;if(t&&e&&(i=t.constructor)===e.constructor){if(i===Date)return t.getTime()===e.getTime();if(i===RegExp)return t.toString()===e.toString();if(i===Array){if((n=t.length)===e.length)for(;n--&&y(t[n],e[n]););return-1===n}if(i===Set){if(t.size!==e.size)return!1;for(n of t){if((s=n)&&"object"==typeof s&&!(s=v(e,s)))return!1;if(!e.has(s))return!1}return!0}if(i===Map){if(t.size!==e.size)return!1;for(n of t){if((s=n[0])&&"object"==typeof s&&!(s=v(e,s)))return!1;if(!y(n[1],e.get(s)))return!1}return!0}if(i===ArrayBuffer)t=new Uint8Array(t),e=new Uint8Array(e);else if(i===DataView){if((n=t.byteLength)===e.byteLength)for(;n--&&t.getInt8(n)===e.getInt8(n););return-1===n}if(ArrayBuffer.isView(t)){if((n=t.byteLength)===e.byteLength)for(;n--&&t[n]===e[n];);return-1===n}if(!i||"object"==typeof t){for(i in n=0,t){if(b.call(t,i)&&++n&&!b.call(e,i))return!1;if(!(i in e)||!y(t[i],e[i]))return!1}return Object.keys(e).length===n}}return t!=t&&e!=e}function w(t){let e=!1;return{promise:new Promise((i,n)=>{t.then(t=>!e&&i(t)).catch(t=>!e&&n(t))}),cancel(){e=!0}}}const x=["onCopy","onCut","onPaste","onCompositionEnd","onCompositionStart","onCompositionUpdate","onFocus","onBlur","onInput","onInvalid","onReset","onSubmit","onLoad","onError","onKeyDown","onKeyPress","onKeyUp","onAbort","onCanPlay","onCanPlayThrough","onDurationChange","onEmptied","onEncrypted","onEnded","onError","onLoadedData","onLoadedMetadata","onLoadStart","onPause","onPlay","onPlaying","onProgress","onRateChange","onSeeked","onSeeking","onStalled","onSuspend","onTimeUpdate","onVolumeChange","onWaiting","onClick","onContextMenu","onDoubleClick","onMouseDown","onMouseEnter","onMouseLeave","onMouseMove","onMouseOut","onMouseOver","onMouseUp","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onSelect","onTouchCancel","onTouchEnd","onTouchMove","onTouchStart","onPointerDown","onPointerMove","onPointerUp","onPointerCancel","onGotPointerCapture","onLostPointerCapture","onPointerEnter","onPointerLeave","onPointerOver","onPointerOut","onScroll","onWheel","onAnimationStart","onAnimationEnd","onAnimationIteration","onTransitionEnd","onChange","onToggle"];function A(t,e){const i={};for(const n of x){const s=t[n];s&&(i[n]=e?t=>s(t,e(n)):s)}return i}const _=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),S=[.001,0,0,.001,0,0],C=1.35,E=1,T=2,k=4,M=16,D=32,P=64,I=128,R=256,L={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},B="pdfjs_internal_editor_",F={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},O={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},N=0,U=1,j=2,z=3,H=3,$=4,W={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},V={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},G=1,q=2,X=3,K=4,Y=5,J={ERRORS:0,WARNINGS:1,INFOS:5},Q={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},Z=0,tt=1,et=2,it=3,nt={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let st=J.WARNINGS;function rt(t){Number.isInteger(t)&&(st=t)}function at(){return st}function ot(t){st>=J.INFOS&&console.info(`Info: ${t}`)}function lt(t){st>=J.WARNINGS&&console.warn(`Warning: ${t}`)}function ht(t){throw new Error(t)}function ct(t,e){t||ht(e)}function dt(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=decodeURIComponent(escape(t))}catch{}}const n=e?URL.parse(t,e):URL.parse(t);return function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(n)?n:null}function ut(t,e,i=!1){const n=URL.parse(t);return n?(n.hash=e,n.href):i&&dt(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function pt(t,e,i,n=!1){return Object.defineProperty(t,e,{value:i,enumerable:!n,configurable:!0,writable:!1}),i}const gt=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class mt extends gt{constructor(t,e){super(t,"PasswordException"),this.code=e}}class ft extends gt{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class bt extends gt{constructor(t){super(t,"InvalidPDFException")}}class vt extends gt{constructor(t,e,i){super(t,"ResponseException"),this.status=e,this.missing=i}}class yt extends gt{constructor(t){super(t,"FormatError")}}class wt extends gt{constructor(t){super(t,"AbortException")}}function xt(t){"object"==typeof t&&void 0!==t?.length||ht("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const n=[];for(let s=0;s<e;s+=i){const r=Math.min(s+i,e),a=t.subarray(s,r);n.push(String.fromCharCode.apply(null,a))}return n.join("")}function At(t){"string"!=typeof t&&ht("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let n=0;n<e;++n)i[n]=255&t.charCodeAt(n);return i}class _t{static get isLittleEndian(){return pt(this,"isLittleEndian",function(){const t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return pt(this,"isEvalSupported",function(){try{return new Function(""),!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return pt(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return pt(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){const{platform:t,userAgent:e}=navigator;return pt(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCSSRoundSupported(){return pt(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const St=Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0"));class Ct{static makeHexColor(t,e,i){return`#${St[t]}${St[e]}${St[i]}`}static domMatrixToTransform(t){return[t.a,t.b,t.c,t.d,t.e,t.f]}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,i=0){const n=t[i],s=t[i+1];t[i]=n*e[0]+s*e[2]+e[4],t[i+1]=n*e[1]+s*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const n=e[0],s=e[1],r=e[2],a=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],c=t[i+e+1];t[i+e]=h*n+c*r+o,t[i+e+1]=h*s+c*a+l}}static applyInverseTransform(t,e){const i=t[0],n=t[1],s=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-n*e[2]+e[2]*e[5]-e[4]*e[3])/s,t[1]=(-i*e[1]+n*e[0]+e[4]*e[1]-e[5]*e[0])/s}static axialAlignedBoundingBox(t,e,i){const n=e[0],s=e[1],r=e[2],a=e[3],o=e[4],l=e[5],h=t[0],c=t[1],d=t[2],u=t[3];let p=n*h+o,g=p,m=n*d+o,f=m,b=a*c+l,v=b,y=a*u+l,w=y;if(0!==s||0!==r){const t=s*h,e=s*d,i=r*c,n=r*u;p+=i,f+=i,m+=n,g+=n,b+=t,w+=t,y+=e,v+=e}i[0]=Math.min(i[0],p,m,g,f),i[1]=Math.min(i[1],b,y,v,w),i[2]=Math.max(i[2],p,m,g,f),i[3]=Math.max(i[3],b,y,v,w)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const i=t[0],n=t[1],s=t[2],r=t[3],a=i**2+n**2,o=i*s+n*r,l=s**2+r**2,h=(a+l)/2,c=Math.sqrt(h**2-(a*l-o**2));e[0]=Math.sqrt(h+c||1),e[1]=Math.sqrt(h-c||1)}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),n=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>n)return null;const s=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return s>r?null:[i,s,n,r]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t),i[1]=Math.min(i[1],e),i[2]=Math.max(i[2],t),i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,n,s){s[0]=Math.min(s[0],t,i),s[1]=Math.min(s[1],e,n),s[2]=Math.max(s[2],t,i),s[3]=Math.max(s[3],e,n)}static#t(t,e,i,n,s,r,a,o,l,h){if(l<=0||l>=1)return;const c=1-l,d=l*l,u=d*l,p=c*(c*(c*t+3*l*e)+3*d*i)+u*n,g=c*(c*(c*s+3*l*r)+3*d*a)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,n,s,r,a,o,l,h,c,d){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,n,s,r,a,o,-c/h,d));const u=h**2-4*c*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,n,s,r,a,o,(-h+p)/g,d),this.#t(t,e,i,n,s,r,a,o,(-h-p)/g,d)}static bezierBoundingBox(t,e,i,n,s,r,a,o,l){l[0]=Math.min(l[0],t,a),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,a),l[3]=Math.max(l[3],e,o),this.#e(t,i,s,a,e,n,r,o,3*(3*(i-s)-t+a),6*(t-2*i+s),3*(i-t),l),this.#e(t,i,s,a,e,n,r,o,3*(3*(n-r)-e+o),6*(e-2*n+r),3*(n-e),l)}}let Et=null,Tt=null;function kt(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);return crypto.getRandomValues(t),xt(t)}const Mt="pdfjs_internal_id_";function Dt(t,e,i){return Math.min(Math.max(t,e),i)}function Pt(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(xt(t))}"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise(i=>{i(t(...e))})}),"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(t){return t.reduce((t,e)=>t+e,0)});class It{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let n=null;const s=i.name;if("#text"===s)n=i.value;else{if(!It.shouldBuildText(s))return;i?.attributes?.textContent?n=i.attributes.textContent:i.value&&(n=i.value)}if(null!==n&&e.push({str:n}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class Rt{static setupStorage(t,e,i,n,s){const r=n.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==r.value&&(t.textContent=r.value),"print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})});break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(r.value===i.attributes.xfaOn?t.setAttribute("checked",!0):r.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===s)break;t.addEventListener("change",t=>{n.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{if(null!==r.value&&t.setAttribute("value",r.value),"print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})})}break;case"select":if(null!==r.value){t.setAttribute("value",r.value);for(const t of i.children)t.attributes.value===r.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const i=t.target.options,s=-1===i.selectedIndex?"":i[i.selectedIndex].value;n.setValue(e,{value:s})})}}static setAttributes({html:t,element:e,storage:i=null,intent:n,linkService:s}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${n}`);for(const[e,i]of Object.entries(r))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!a||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}a&&s.addLinkAttributes(t,r.href,r.newWindow),i&&r.dataId&&this.setupStorage(t,r.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,n=t.xfaHtml,s=t.intent||"display",r=document.createElement(n.name);n.attributes&&this.setAttributes({html:r,element:n,intent:s,linkService:i});const a="richText"!==s,o=t.div;if(o.append(r),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}a&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===n.children.length){if(n.value){const t=document.createTextNode(n.value);r.append(t),a&&It.shouldBuildText(n.name)&&l.push(t)}return{textDivs:l}}const h=[[n,-1,r]];for(;h.length>0;){const[t,n,r]=h.at(-1);if(n+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);l.push(t),r.append(t);continue}const d=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);if(r.append(d),o.attributes&&this.setAttributes({html:d,element:o,storage:e,intent:s,linkService:i}),o.children?.length>0)h.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);a&&It.shouldBuildText(c)&&l.push(t),d.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const Lt="http://www.w3.org/2000/svg";class Bt{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Ft(t,e="text"){if(Ht(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise((i,n)=>{const s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE)if(200!==s.status&&0!==s.status)n(new Error(s.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void i(s.response)}i(s.responseText)}},s.send(null)})}class Ot{constructor({viewBox:t,userUnit:e,scale:i,rotation:n,offsetX:s=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t,this.userUnit=e,this.scale=i,this.rotation=n,this.offsetX=s,this.offsetY=r,i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,c,d,u,p,g,m,f;switch((n%=360)<0&&(n+=360),n){case 180:h=-1,c=0,d=0,u=1;break;case 90:h=0,c=1,d=1,u=0;break;case 270:h=0,c=-1,d=-1,u=0;break;case 0:h=1,c=0,d=0,u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,u=-u),0===h?(p=Math.abs(l-t[1])*i+s,g=Math.abs(o-t[0])*i+r,m=(t[3]-t[1])*i,f=(t[2]-t[0])*i):(p=Math.abs(o-t[0])*i+s,g=Math.abs(l-t[1])*i+r,m=(t[2]-t[0])*i,f=(t[3]-t[1])*i),this.transform=[h*i,c*i,d*i,u*i,p-h*i*o-d*i*l,g-c*i*o-u*i*l],this.width=m,this.height=f}get rawDims(){const t=this.viewBox;return pt(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:n=this.offsetY,dontFlip:s=!1}={}){return new Ot({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}convertToViewportPoint(t,e){const i=[t,e];return Ct.applyTransform(i,this.transform),i}convertToViewportRectangle(t){const e=[t[0],t[1]];Ct.applyTransform(e,this.transform);const i=[t[2],t[3]];return Ct.applyTransform(i,this.transform),[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){const i=[t,e];return Ct.applyInverseTransform(i,this.transform),i}}class Nt extends gt{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Ut(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function jt(t){return"string"==typeof t&&/\.pdf$/i.test(t)}class zt{started=Object.create(null);times=[];time(t){t in this.started&<(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||lt(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:n,end:s}of this.times)t.push(`${i.padEnd(e)} ${s-n}ms\n`);return t.join("")}}function Ht(t,e){const i=e?URL.parse(t,e):URL.parse(t);return"http:"===i?.protocol||"https:"===i?.protocol}function $t(t){t.preventDefault()}function Wt(t){t.preventDefault(),t.stopPropagation()}class Vt{static#i;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#i.exec(t);if(!e)return null;const i=parseInt(e[1],10);let n=parseInt(e[2],10);n=n>=1&&n<=12?n-1:0;let s=parseInt(e[3],10);s=s>=1&&s<=31?s:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let c=parseInt(e[9],10)||0;return c=c>=0&&c<=59?c:0,"-"===l?(r+=h,a+=c):"+"===l&&(r-=h,a-=c),new Date(Date.UTC(i,n,s,r,a,o))}}function Gt(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map(t=>parseInt(t)):t.startsWith("rgba(")?t.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(lt(`Not a valid color format: "${t}"`),[0,0,0])}function qt(t){const{a:e,b:i,c:n,d:s,e:r,f:a}=t.getTransform();return[e,i,n,s,r,a]}function Xt(t){const{a:e,b:i,c:n,d:s,e:r,f:a}=t.getTransform().invertSelf();return[e,i,n,s,r,a]}function Kt(t,e,i=!1,n=!0){if(e instanceof Ot){const{pageWidth:n,pageHeight:s}=e.rawDims,{style:r}=t,a=_t.isCSSRoundSupported,o=`var(--total-scale-factor) * ${n}px`,l=`var(--total-scale-factor) * ${s}px`,h=a?`round(down, ${o}, var(--scale-round-x))`:`calc(${o})`,c=a?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;i&&e.rotation%180!=0?(r.width=c,r.height=h):(r.width=h,r.height=c)}n&&t.setAttribute("data-main-rotation",e.rotation)}class Yt{constructor(){const{pixelRatio:t}=Yt;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,i,n,s=-1){let r=1/0,a=1/0,o=1/0;(i=Yt.capPixels(i,s))>0&&(r=Math.sqrt(i/(t*e))),-1!==n&&(a=n/t,o=n/e);const l=Math.min(r,a,o);return(this.sx>l||this.sy>l)&&(this.sx=l,this.sy=l,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}}const Jt=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class Qt{static get isDarkMode(){return pt(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}function Zt(t,e){const i=t[0]/255,n=t[1]/255,s=t[2]/255,r=Math.max(i,n,s),a=Math.min(i,n,s),o=(r+a)/2;if(r===a)e[0]=e[1]=0;else{const t=r-a;switch(e[1]=o<.5?t/(r+a):t/(2-r-a),r){case i:e[0]=60*((n-s)/t+(n<s?6:0));break;case n:e[0]=60*((s-i)/t+2);break;case s:e[0]=60*((i-n)/t+4)}}e[2]=o}function te(t,e){const i=t[0],n=t[1],s=t[2],r=(1-Math.abs(2*s-1))*n,a=r*(1-Math.abs(i/60%2-1)),o=s-r/2;switch(Math.floor(i/60)){case 0:e[0]=r+o,e[1]=a+o,e[2]=o;break;case 1:e[0]=a+o,e[1]=r+o,e[2]=o;break;case 2:e[0]=o,e[1]=r+o,e[2]=a+o;break;case 3:e[0]=o,e[1]=a+o,e[2]=r+o;break;case 4:e[0]=a+o,e[1]=o,e[2]=r+o;break;case 5:case 6:e[0]=r+o,e[1]=o,e[2]=a+o}}function ee(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function ie(t,e,i){te(t,i),i.map(ee);const n=.2126*i[0]+.7152*i[1]+.0722*i[2];te(e,i),i.map(ee);const s=.2126*i[0]+.7152*i[1]+.0722*i[2];return n>s?(n+.05)/(s+.05):(s+.05)/(n+.05)}const ne=new Map;function se({html:t,dir:e,className:i},n){const s=document.createDocumentFragment();if("string"==typeof t){const i=document.createElement("p");i.dir=e||"auto";const n=t.split(/(?:\r\n?|\n)/);for(let t=0,e=n.length;t<e;++t){const s=n[t];i.append(document.createTextNode(s)),t<e-1&&i.append(document.createElement("br"))}s.append(i)}else Rt.render({xfaHtml:t,div:s,intent:"richText"});s.firstChild.classList.add("richText",i),n.append(s)}class re{#n=null;#s=null;#r;#a=null;#o=null;#l=null;#h=null;#c=null;static#d=null;constructor(t){this.#r=t,re.#d||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#n=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#r._uiManager._signal;e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("contextmenu",$t,{signal:e}),t.addEventListener("pointerdown",re.#u,{signal:e}));const i=this.#a=document.createElement("div");i.className="buttons",t.append(i);const n=this.#r.toolbarPosition;if(n){const{style:e}=t,i="ltr"===this.#r._uiManager.direction?1-n[0]:n[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*n[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#n}static#u(t){t.stopPropagation()}#p(t){this.#r._focusEventsAllowed=!1,Wt(t)}#g(t){this.#r._focusEventsAllowed=!0,Wt(t)}#m(t){const e=this.#r._uiManager._signal;return e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("focusin",this.#p.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#g.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",$t,{signal:e}),!0)}hide(){this.#n.classList.add("hidden"),this.#s?.hideDropdown()}show(){this.#n.classList.remove("hidden"),this.#o?.shown(),this.#l?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#r,i=document.createElement("button");i.classList.add("basic","deleteButton"),i.tabIndex=0,i.setAttribute("data-l10n-id",re.#d[t]),this.#m(i)&&i.addEventListener("click",t=>{e.delete()},{signal:e._signal}),this.#a.append(i)}get#f(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#m(e),this.#a.append(e,this.#f),this.#o=t}addComment(t,e=null){if(this.#l)return;const i=t.renderForToolbar();if(!i)return;this.#m(i);const n=this.#h=this.#f;e?(this.#a.insertBefore(i,e),this.#a.insertBefore(n,e)):this.#a.append(i,n),this.#l=t,t.toolbar=this}addColorPicker(t){if(this.#s)return;this.#s=t;const e=t.renderButton();this.#m(e),this.#a.append(e,this.#f)}async addEditSignatureButton(t){const e=this.#c=await t.renderEditButton(this.#r);this.#m(e),this.#a.append(e,this.#f)}removeButton(t){if("comment"===t)this.#l?.removeToolbarCommentButton(),this.#l=null,this.#h?.remove(),this.#h=null}async addButton(t,e){switch(t){case"colorPicker":this.addColorPicker(e);break;case"altText":await this.addAltText(e);break;case"editSignature":await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":this.addComment(e)}}async addButtonBefore(t,e,i){const n=this.#a.querySelector(i);n&&"comment"===t&&this.addComment(e,n)}updateEditSignatureButton(t){this.#c&&(this.#c.title=t)}remove(){this.#n.remove(),this.#s?.destroy(),this.#s=null}}class ae{#a=null;#n=null;#b;constructor(t){this.#b=t}#v(){const t=this.#n=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar");const e=this.#b._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",$t,{signal:e});const i=this.#a=document.createElement("div");return i.className="buttons",t.append(i),this.#b.hasCommentManager()&&this.#y("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#b.commentSelection("floating_button")}),this.#y("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#b.highlightSelection("floating_button")}),t}#w(t,e){let i=0,n=0;for(const s of t){const t=s.y+s.height;if(t<i)continue;const r=s.x+(e?s.width:0);t>i?(n=r,i=t):e?r>n&&(n=r):r<n&&(n=r)}return[e?1-n:n,i]}show(t,e,i){const[n,s]=this.#w(e,i),{style:r}=this.#n||=this.#v();t.append(this.#n),r.insetInlineEnd=100*n+"%",r.top=`calc(${100*s}% + var(--editor-toolbar-vert-offset))`}hide(){this.#n.remove()}#y(t,e,i,n){const s=document.createElement("button");s.classList.add("basic",t),s.tabIndex=0,s.setAttribute("data-l10n-id",e);const r=document.createElement("span");s.append(r),r.className="visuallyHidden",r.setAttribute("data-l10n-id",i);const a=this.#b._signal;a instanceof AbortSignal&&!a.aborted&&(s.addEventListener("contextmenu",$t,{signal:a}),s.addEventListener("click",n,{signal:a})),this.#a.append(s)}}function oe(t,e,i){for(const n of i)e.addEventListener(n,t[n].bind(t))}class le{#x=0;get id(){return`${B}${this.#x++}`}}class he{#A=kt();#x=0;#_=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';return pt(this,"_isSVGFittingCanvas",e.decode().then(()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0])))}async#S(t,e){this.#_||=new Map;let i=this.#_.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#A}_${this.#x++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await Ft(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=he._isSVGFittingCanvas,n=new FileReader,s=new Image,r=new Promise((t,r)=>{s.onload=()=>{i.bitmap=s,i.isSvg=!0,t()},n.onload=async()=>{const t=i.svgUrl=n.result;s.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},s.onerror=n.onerror=r});n.readAsDataURL(t),await r}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){lt(t),i=null}return this.#_.set(t,i),i&&this.#_.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:n,type:s}=t;return this.#S(`${e}_${i}_${n}_${s}`,t)}async getFromUrl(t){return this.#S(t,t)}async getFromBlob(t,e){const i=await e;return this.#S(t,i)}async getFromId(t){this.#_||=new Map;const e=this.#_.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#_||=new Map;let i=this.#_.get(t);if(i?.bitmap)return i.refCounter+=1,i;const n=new OffscreenCanvas(e.width,e.height);return n.getContext("2d").drawImage(e,0,0),i={bitmap:n.transferToImageBitmap(),id:`image_${this.#A}_${this.#x++}`,refCounter:1,isSvg:!1},this.#_.set(t,i),this.#_.set(i.id,i),i}getSvgUrl(t){const e=this.#_.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#_||=new Map;const e=this.#_.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#A}_`)}}class ce{#C=[];#E=!1;#T;#k=-1;constructor(t=128){this.#T=t}add({cmd:t,undo:e,post:i,mustExec:n,type:s=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){if(n&&t(),this.#E)return;const o={cmd:t,undo:e,post:i,type:s};if(-1===this.#k)return this.#C.length>0&&(this.#C.length=0),this.#k=0,void this.#C.push(o);if(r&&this.#C[this.#k].type===s)return a&&(o.undo=this.#C[this.#k].undo),void(this.#C[this.#k]=o);const l=this.#k+1;l===this.#T?this.#C.splice(0,1):(this.#k=l,l<this.#C.length&&this.#C.splice(l)),this.#C.push(o)}undo(){if(-1===this.#k)return;this.#E=!0;const{undo:t,post:e}=this.#C[this.#k];t(),e?.(),this.#E=!1,this.#k-=1}redo(){if(this.#k<this.#C.length-1){this.#k+=1,this.#E=!0;const{cmd:t,post:e}=this.#C[this.#k];t(),e?.(),this.#E=!1}}hasSomethingToUndo(){return-1!==this.#k}hasSomethingToRedo(){return this.#k<this.#C.length-1}cleanType(t){if(-1!==this.#k){for(let e=this.#k;e>=0;e--)if(this.#C[e].type!==t)return this.#C.splice(e+1,this.#k-e),void(this.#k=e);this.#C.length=0,this.#k=-1}}destroy(){this.#C=null}}class de{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=_t.platform;for(const[i,n,s={}]of t)for(const t of i){const i=t.startsWith("mac+");e&&i?(this.callbacks.set(t.slice(4),{callback:n,options:s}),this.allKeys.add(t.split("+").at(-1))):e||i||(this.callbacks.set(t,{callback:n,options:s}),this.allKeys.add(t.split("+").at(-1)))}}#M(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#M(e));if(!i)return;const{callback:n,options:{bubbles:s=!1,args:r=[],checker:a=null}}=i;a&&!a(t,e)||(n.bind(t,...r,e)(),s||Wt(e))}}class ue{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return function(t){const e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(const i of t.keys()){e.style.color=i;const n=window.getComputedStyle(e).color;t.set(i,Gt(n))}e.remove()}(t),pt(this,"_colors",t)}convert(t){const e=Gt(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every((t,i)=>t===e[i]))return ue._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Ct.makeHexColor(...e):t}}class pe{#D=new AbortController;#P=null;#I=null;#R=new Map;#L=new Map;#B=null;#F=null;#O=null;#N=new ce;#U=null;#j=null;#z=null;#H=0;#$=new Set;#W=null;#V=null;#G=new Set;_editorUndoBar=null;#q=!1;#X=!1;#K=!1;#Y=null;#J=null;#Q=null;#Z=null;#tt=!1;#et=null;#it=new le;#nt=!1;#st=!1;#rt=!1;#at=null;#ot=null;#lt=null;#ht=null;#ct=null;#dt=F.NONE;#ut=new Set;#pt=null;#gt=null;#mt=null;#ft=null;#bt=null;#vt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#yt=[0,0];#wt=null;#xt=null;#At=null;#_t=null;#St=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=pe.prototype,e=t=>t.#xt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},n=this.TRANSLATE_SMALL,s=this.TRANSLATE_BIG;return pt(this,"_keyboardManager",new de([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#xt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#xt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}]]))}constructor(t,e,i,n,s,r,a,o,l,h,c,d,u,p,g,m){const f=this._signal=this.#D.signal;this.#xt=t,this.#At=e,this.#_t=i,this.#B=n,this.#U=s,this.#gt=r,this.#bt=o,this._eventBus=a,a._on("editingaction",this.onEditingAction.bind(this),{signal:f}),a._on("pagechanging",this.onPageChanging.bind(this),{signal:f}),a._on("scalechanging",this.onScaleChanging.bind(this),{signal:f}),a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:f}),a._on("setpreference",this.onSetPreference.bind(this),{signal:f}),a._on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),{signal:f}),window.addEventListener("pointerdown",()=>{this.#st=!0},{capture:!0,signal:f}),window.addEventListener("pointerup",()=>{this.#st=!1},{capture:!0,signal:f}),this.#Ct(),this.#Et(),this.#Tt(),this.#F=o.annotationStorage,this.#Y=o.filterFactory,this.#mt=l,this.#Z=h||null,this.#q=c,this.#X=d,this.#K=u,this.#ct=p||null,this.viewParameters={realScale:Bt.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=g||null,this._supportsPinchToZoom=!1!==m,s?.setSidebarUiManager(this)}destroy(){this.#St?.resolve(),this.#St=null,this.#D?.abort(),this.#D=null,this._signal=null;for(const t of this.#L.values())t.destroy();this.#L.clear(),this.#R.clear(),this.#G.clear(),this.#ht?.clear(),this.#P=null,this.#ut.clear(),this.#N.destroy(),this.#B?.destroy(),this.#U?.destroy(),this.#gt?.destroy(),this.#et?.hide(),this.#et=null,this.#lt?.destroy(),this.#lt=null,this.#I=null,this.#J&&(clearTimeout(this.#J),this.#J=null),this.#wt&&(clearTimeout(this.#wt),this.#wt=null),this._editorUndoBar?.destroy(),this.#bt=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#ct}get useNewAltTextFlow(){return this.#X}get useNewAltTextWhenAddingImage(){return this.#K}get hcmFilter(){return pt(this,"hcmFilter",this.#mt?this.#Y.addHCMFilter(this.#mt.foreground,this.#mt.background):"none")}get direction(){return pt(this,"direction",getComputedStyle(this.#xt).direction)}get _highlightColors(){return pt(this,"_highlightColors",this.#Z?new Map(this.#Z.split(",").map(t=>((t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase(),t))):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return pt(this,"highlightColors",null);const e=new Map,i=!!this.#mt;for(const[n,s]of t){const t=n.endsWith("_HCM");i&&t?e.set(n.replace("_HCM",""),s):i||t||e.set(n,s)}return pt(this,"highlightColors",e)}get highlightColorNames(){return pt(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#z=t}setMainHighlightColorPicker(t){this.#lt=t}editAltText(t,e=!1){this.#B?.editAltText(this,t,e)}hasCommentManager(){return!!this.#U}editComment(t,e,i,n){this.#U?.showDialog(this,t,e,i,n)}selectComment(t,e){const i=this.#L.get(t),n=i?.getEditorByUID(e);n?.toggleComment(!0,!0)}updateComment(t){this.#U?.updateComment(t.getData())}updatePopupColor(t){this.#U?.updatePopupColor(t)}removeComment(t){this.#U?.removeComments([t.uid])}toggleComment(t,e,i=void 0){this.#U?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#U?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#U?.dialogElement||null}async waitForEditorsRendered(t){if(this.#L.has(t-1))return;const{resolve:e,promise:i}=Promise.withResolvers(),n=i=>{i.pageNumber===t&&(this._eventBus._off("editorsrendered",n),e())};this._eventBus.on("editorsrendered",n),await i}getSignature(t){this.#gt?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#gt}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#K=e}onPageChanging({pageNumber:t}){this.#H=t-1}focusMainContainer(){this.#xt.focus()}findParent(t,e){for(const i of this.#L.values()){const{x:n,y:s,width:r,height:a}=i.div.getBoundingClientRect();if(t>=n&&t<=n+r&&e>=s&&e<=s+a)return i}return null}disableUserSelect(t=!1){this.#At.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#G.add(t)}removeShouldRescale(t){this.#G.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Bt.PDF_TO_CSS_UNITS;for(const t of this.#G)t.onScaleChanging();this.#z?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#kt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Mt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#L.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t="",e=!1){const i=document.getSelection();if(!i||i.isCollapsed)return;const{anchorNode:n,anchorOffset:s,focusNode:r,focusOffset:a}=i,o=i.toString(),l=this.#kt(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();const c=this.#Mt(l),d=this.#dt===F.NONE,u=()=>{const i=c?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:n,anchorOffset:s,focusNode:r,focusOffset:a,text:o});d&&this.showAllEditors("highlight",!0,!0),e&&i?.editComment()};d?this.switchToMode(F.HIGHLIGHT,u):u()}commentSelection(t=""){this.highlightSelection(t,!0)}#Dt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#kt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#et||=new ae(this),this.#et.show(e,i,"ltr"===this.direction))}getAndRemoveDataFromAnnotationStorage(t){if(!this.#F)return null;const e=`${B}${t}`,i=this.#F.getRawValue(e);return i&&this.#F.remove(e),i}addToAnnotationStorage(t){t.isEmpty()||!this.#F||this.#F.has(t.id)||this.#F.setValue(t.id,t)}a11yAlert(t,e=null){const i=this.#_t;i&&(i.setAttribute("data-l10n-id",t),e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args"))}#Pt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#pt&&(this.#et?.hide(),this.#pt=null,this.#It({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#pt)return;const i=this.#kt(t).closest(".textLayer");if(i){if(this.#et?.hide(),this.#pt=e,this.#It({hasSelectedText:!0}),(this.#dt===F.HIGHLIGHT||this.#dt===F.NONE)&&(this.#dt===F.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#tt=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#dt===F.HIGHLIGHT?this.#Mt(i):null;if(t?.toggleDrawing(),this.#st){const e=new AbortController,i=this.combinedSignal(e),n=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#Rt("main_toolbar"))};window.addEventListener("pointerup",n,{signal:i}),window.addEventListener("blur",n,{signal:i})}else t?.toggleDrawing(!0),this.#Rt("main_toolbar")}}else this.#pt&&(this.#et?.hide(),this.#pt=null,this.#It({hasSelectedText:!1}))}#Rt(t=""){this.#dt===F.HIGHLIGHT?this.highlightSelection(t):this.#q&&this.#Dt()}#Ct(){document.addEventListener("selectionchange",this.#Pt.bind(this),{signal:this._signal})}#Lt(){if(this.#Q)return;this.#Q=new AbortController;const t=this.combinedSignal(this.#Q);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Bt(){this.#Q?.abort(),this.#Q=null}blur(){if(this.isShiftKeyDown=!1,this.#tt&&(this.#tt=!1,this.#Rt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#ut)if(e.div.contains(t)){this.#ot=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#ot)return;const[t,e]=this.#ot;this.#ot=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#Tt(){if(this.#at)return;this.#at=new AbortController;const t=this.combinedSignal(this.#at);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Ft(){this.#at?.abort(),this.#at=null}#Ot(){if(this.#j)return;this.#j=new AbortController;const t=this.combinedSignal(this.#j);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Nt(){this.#j?.abort(),this.#j=null}#Et(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Tt(),this.#Ot()}removeEditListeners(){this.#Ft(),this.#Nt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#V)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#V)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#P?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#ut){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#V)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void lt(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const n=this.currentLayer;try{const t=[];for(const e of i){const i=await n.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#Ut(e);this.#jt(t)},s=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:s,mustExec:!0})}catch(t){lt(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#dt===F.NONE||this.isEditorHandlingKeyboard||pe._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#tt&&(this.#tt=!1,this.#Rt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}#It(t){Object.entries(t).some(([t,e])=>this.#vt[t]!==e)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#vt,t)}),this.#dt===F.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#zt([[O.HIGHLIGHT_FREE,!0]]))}#zt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Lt(),this.#Ot(),this.#It({isEditing:this.#dt!==F.NONE,isEmpty:this.#Ht(),hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:this.#N.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Bt(),this.#Nt(),this.#It({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#V){this.#V=t;for(const t of this.#V)this.#zt(t.defaultPropertiesToUpdate)}}getId(){return this.#it.id}get currentLayer(){return this.#L.get(this.#H)}getLayer(t){return this.#L.get(t)}get currentPageIndex(){return this.#H}addLayer(t){this.#L.set(t.pageIndex,t),this.#nt?t.enable():t.disable()}removeLayer(t){this.#L.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,n=!1,s=!1){if(this.#dt!==t&&(!this.#St||(await this.#St.promise,this.#St))){if(this.#St=Promise.withResolvers(),this.#z?.commitOrRemove(),this.#dt===F.POPUP&&this.#U?.hideSidebar(),this.#U?.destroyPopup(),this.#dt=t,t===F.NONE){this.setEditingState(!1),this.#$t();for(const t of this.#R.values())t.hideStandaloneCommentButton();return this._editorUndoBar?.hide(),this.toggleComment(null),void this.#St.resolve()}for(const t of this.#R.values())t.addStandaloneCommentButton();t===F.SIGNATURE&&await(this.#gt?.loadSignatures()),this.setEditingState(!0),await this.#Wt(),this.unselectAll();for(const e of this.#L.values())e.updateMode(t);if(t===F.POPUP){this.#I||=await this.#bt.getAnnotationsByType(new Set(this.#V.map(t=>t._editorType)));const t=new Set,e=[];for(const i of this.#R.values()){const{annotationElementId:n,hasComment:s,deleted:r}=i;n&&t.add(n),s&&!r&&e.push(i.getData())}for(const i of this.#I){const{id:n,popupRef:s,contentsObj:r}=i;s&&r?.str&&!t.has(n)&&!this.#$.has(n)&&e.push(i)}this.#U?.showSidebar(e)}if(!e)return i&&this.addNewEditorFromKeyboard(),void this.#St.resolve();for(const t of this.#R.values())t.uid===e?(this.setSelected(t),s?t.editComment():n?t.enterInEditMode():t.focus()):t.unselect();this.#St.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#dt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#V){switch(t){case O.CREATE:return void this.currentLayer.addNewEditor(e);case O.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#ft||=new Map).set(t,e),this.showAllEditors("highlight",e)}if(this.hasSelection)for(const i of this.#ut)i.updateParams(t,e);else for(const i of this.#V)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#R.values())i.editorType===t&&i.show(e);(this.#ft?.get(O.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#zt([[O.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#rt!==t){this.#rt=t;for(const e of this.#L.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Wt(){if(!this.#nt){this.#nt=!0;const t=[];for(const e of this.#L.values())t.push(e.enable());await Promise.all(t);for(const t of this.#R.values())t.enable()}}#$t(){if(this.unselectAll(),this.#nt){this.#nt=!1;for(const t of this.#L.values())t.disable();for(const t of this.#R.values())t.disable()}}*getEditors(t){for(const e of this.#R.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#R.get(t)}addEditor(t){this.#R.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#J&&clearTimeout(this.#J),this.#J=setTimeout(()=>{this.focusMainContainer(),this.#J=null},0)),this.#R.delete(t.id),t.annotationElementId&&this.#ht?.delete(t.annotationElementId),this.unselect(t),t.annotationElementId&&this.#$.has(t.annotationElementId)||this.#F?.remove(t.id)}addDeletedAnnotationElement(t){this.#$.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#$.has(t)}removeDeletedAnnotationElement(t){this.#$.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#Ut(t){const e=this.#L.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#P!==t&&(this.#P=t,t&&this.#zt(t.propertiesToUpdate))}get#Vt(){let t=null;for(t of this.#ut);return t}updateUI(t){this.#Vt===t&&this.#zt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#zt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#ut.has(t))return this.#ut.delete(t),t.unselect(),void this.#It({hasSelectedEditor:this.hasSelection});this.#ut.add(t),t.select(),this.#zt(t.propertiesToUpdate),this.#It({hasSelectedEditor:!0})}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.id}),this.#z?.commitOrRemove();for(const e of this.#ut)e!==t&&e.unselect();this.#ut.clear(),this.#ut.add(t),t.select(),this.#zt(t.propertiesToUpdate),this.#It({hasSelectedEditor:!0})}isSelected(t){return this.#ut.has(t)}get firstSelectedEditor(){return this.#ut.values().next().value}unselect(t){t.unselect(),this.#ut.delete(t),this.#It({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#ut.size}get isEnterHandled(){return 1===this.#ut.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#N.undo(),this.#It({hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Ht()}),this._editorUndoBar?.hide()}redo(){this.#N.redo(),this.#It({hasSomethingToUndo:!0,hasSomethingToRedo:this.#N.hasSomethingToRedo(),isEmpty:this.#Ht()})}addCommands(t){this.#N.add(t),this.#It({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Ht()})}cleanUndoStack(t){this.#N.cleanType(t)}#Ht(){if(0===this.#R.size)return!0;if(1===this.#R.size)for(const t of this.#R.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#ut],i=()=>{for(const t of e)this.#Ut(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo:i,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#jt(t){for(const t of this.#ut)t.unselect();this.#ut.clear();for(const e of t)e.isEmpty()||(this.#ut.add(e),e.select());this.#It({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#ut)t.commit();this.#jt(this.#R.values())}unselectAll(){if((!this.#P||(this.#P.commitOrRemove(),this.#dt===F.NONE))&&!this.#z?.commitOrRemove()&&this.hasSelection){for(const t of this.#ut)t.unselect();this.#ut.clear(),this.#It({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#yt[0]+=t,this.#yt[1]+=e;const[n,s]=this.#yt,r=[...this.#ut];this.#wt&&clearTimeout(this.#wt),this.#wt=setTimeout(()=>{this.#wt=null,this.#yt[0]=this.#yt[1]=0,this.addCommands({cmd:()=>{for(const t of r)this.#R.has(t.id)&&(t.translateInPage(n,s),t.translationDone())},undo:()=>{for(const t of r)this.#R.has(t.id)&&(t.translateInPage(-n,-s),t.translationDone())},mustExec:!1})},1e3);for(const i of r)i.translateInPage(t,e),i.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#W=new Map;for(const t of this.#ut)this.#W.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#W)return!1;this.disableUserSelect(!1);const t=this.#W;this.#W=null;let e=!1;for(const[{x:i,y:n,pageIndex:s},r]of t)r.newX=i,r.newY=n,r.newPageIndex=s,e||=i!==r.savedX||n!==r.savedY||s!==r.savedPageIndex;if(!e)return!1;const i=(t,e,i,n)=>{if(this.#R.has(t.id)){const s=this.#L.get(n);s?t._setParentAndPosition(s,e,i):(t.pageIndex=n,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:n,newY:s,newPageIndex:r}]of t)i(e,n,s,r)},undo:()=>{for(const[e,{savedX:n,savedY:s,savedPageIndex:r}]of t)i(e,n,s,r)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#W)for(const i of this.#W.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#ut.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#dt}isEditingMode(){return this.#dt!==F.NONE}get imageManager(){return pt(this,"imageManager",new he)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,n=e.rangeCount;i<n;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;const{x:i,y:n,width:s,height:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(t,e,a,o)=>({x:(e-n)/r,y:1-(t+a-i)/s,width:o/r,height:a/s});break;case"180":a=(t,e,a,o)=>({x:1-(t+a-i)/s,y:1-(e+o-n)/r,width:a/s,height:o/r});break;case"270":a=(t,e,a,o)=>({x:1-(e+o-n)/r,y:(t-i)/s,width:o/r,height:a/s});break;default:a=(t,e,a,o)=>({x:(t-i)/s,y:(e-n)/r,width:a/s,height:o/r})}const o=[];for(let t=0,i=e.rangeCount;t<i;t++){const i=e.getRangeAt(t);if(!i.collapsed)for(const{x:t,y:e,width:n,height:s}of i.getClientRects())0!==n&&0!==s&&o.push(a(t,e,n,s))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#O||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#O?.delete(t)}renderAnnotationElement(t){const e=this.#O?.get(t.data.id);if(!e)return;const i=this.#F.getRawValue(e);i&&(this.#dt!==F.NONE||i.hasBeenModified)&&i.renderAnnotationElement(t)}setMissingCanvas(t,e,i){const n=this.#ht?.get(t);n&&(n.setCanvas(e,i),this.#ht.delete(t))}addMissingCanvas(t,e){(this.#ht||=new Map).set(t,e)}}class ge{#o=null;#Gt=!1;#qt=null;#Xt=null;#Kt=null;#Yt=null;#Jt=!1;#Qt=null;#r=null;#Zt=null;#te=null;#ee=!1;static#ie=null;static _l10n=null;constructor(t){this.#r=t,this.#ee=t._uiManager.useNewAltTextFlow,ge.#ie||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){ge._l10n??=t}async render(){const t=this.#qt=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#Xt=document.createElement("span");t.append(e),this.#ee?(t.classList.add("new"),t.setAttribute("data-l10n-id",ge.#ie.missing),e.setAttribute("data-l10n-id",ge.#ie["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const i=this.#r._uiManager._signal;t.addEventListener("contextmenu",$t,{signal:i}),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const n=t=>{t.preventDefault(),this.#r._uiManager.editAltText(this.#r),this.#ee&&this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#ne}})};return t.addEventListener("click",n,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#Jt=!0,n(e))},{signal:i}),await this.#se(),t}get#ne(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){this.#qt&&(this.#qt.focus({focusVisible:this.#Jt}),this.#Jt=!1)}isEmpty(){return this.#ee?null===this.#o:!this.#o&&!this.#Gt}hasData(){return this.#ee?null!==this.#o||!!this.#Zt:this.isEmpty()}get guessedText(){return this.#Zt}async setGuessedText(t){null===this.#o&&(this.#Zt=t,this.#te=await ge._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#se())}toggleAltTextBadge(t=!1){if(!this.#ee||this.#o)return this.#Qt?.remove(),void(this.#Qt=null);if(!this.#Qt){const t=this.#Qt=document.createElement("div");t.className="noAltTextBadge",this.#r.div.append(t)}this.#Qt.classList.toggle("hidden",!t)}serialize(t){let e=this.#o;return t||this.#Zt!==e||(e=this.#te),{altText:e,decorative:this.#Gt,guessedText:this.#Zt,textWithDisclaimer:this.#te}}get data(){return{altText:this.#o,decorative:this.#Gt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:n,cancel:s=!1}){i&&(this.#Zt=i,this.#te=n),this.#o===t&&this.#Gt===e||(s||(this.#o=t,this.#Gt=e),this.#se())}toggle(t=!1){this.#qt&&(!t&&this.#Yt&&(clearTimeout(this.#Yt),this.#Yt=null),this.#qt.disabled=!t)}shown(){this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#ne}})}destroy(){this.#qt?.remove(),this.#qt=null,this.#Xt=null,this.#Kt=null,this.#Qt?.remove(),this.#Qt=null}async#se(){const t=this.#qt;if(!t)return;if(this.#ee){if(t.classList.toggle("done",!!this.#o),t.setAttribute("data-l10n-id",ge.#ie[this.#ne]),this.#Xt?.setAttribute("data-l10n-id",ge.#ie[`${this.#ne}-label`]),!this.#o)return void this.#Kt?.remove()}else{if(!this.#o&&!this.#Gt)return t.classList.remove("done"),void this.#Kt?.remove();t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#Kt;if(!e){this.#Kt=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#r.id}`;const i=100,n=this.#r._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#Yt),this.#Yt=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#Yt=setTimeout(()=>{this.#Yt=null,this.#Kt.classList.add("show"),this.#r._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#Yt&&(clearTimeout(this.#Yt),this.#Yt=null),this.#Kt?.classList.remove("show")},{signal:n})}this.#Gt?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#o),e.parentNode||t.append(e);const i=this.#r.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class me{#re=null;#ae=null;#oe=!1;#r=null;#le=null;#he=null;#ce=null;#de=null;#ue=!1;#pe=null;constructor(t){this.#r=t}renderForToolbar(){const t=this.#ae=document.createElement("button");return t.className="comment",this.#v(t,!1)}renderForStandalone(){const t=this.#re=document.createElement("button");t.className="annotationCommentButton";const e=this.#r.commentButtonPosition;if(e){const{style:i}=t;i.insetInlineEnd=`calc(${100*("ltr"===this.#r._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`,i.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const n=this.#r.commentButtonColor;n&&(i.backgroundColor=n)}return this.#v(t,!0)}focusButton(){setTimeout(()=>{(this.#re??this.#ae)?.focus()},0)}onUpdatedColor(){if(!this.#re)return;const t=this.#r.commentButtonColor;t&&(this.#re.style.backgroundColor=t),this.#r._uiManager.updatePopupColor(this.#r)}get commentButtonWidth(){return(this.#re?.getBoundingClientRect().width??0)/this.#r.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#pe)return this.#pe;if(!this.#re)return null;const{x:t,y:e,height:i}=this.#re.getBoundingClientRect(),{x:n,y:s,width:r,height:a}=this.#r.parent.boundingClientRect;return[(t-n)/r,(e+i-s)/a]}set commentPopupPositionInLayer(t){this.#pe=t}hasDefaultPopupPosition(){return null===this.#pe}removeStandaloneCommentButton(){this.#re?.remove(),this.#re=null}removeToolbarCommentButton(){this.#ae?.remove(),this.#ae=null}setCommentButtonStates({selected:t,hasPopup:e}){this.#re&&(this.#re.classList.toggle("selected",t),this.#re.ariaExpanded=e)}#v(t,e){if(!this.#r._uiManager.hasCommentManager())return null;t.tabIndex="0",t.ariaHasPopup="dialog",e?(t.ariaControls="commentPopup",t.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(t.ariaControlsElements=[this.#r._uiManager.getCommentDialogElement()],t.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-button"));const i=this.#r._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",$t,{signal:i}),e&&(t.addEventListener("focusin",t=>{this.#r._focusEventsAllowed=!1,Wt(t)},{capture:!0,signal:i}),t.addEventListener("focusout",t=>{this.#r._focusEventsAllowed=!0,Wt(t)},{capture:!0,signal:i})),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const n=e=>{e.preventDefault(),t===this.#ae?this.edit():this.#r.toggleComment(!0)};return t.addEventListener("click",n,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#oe=!0,n(e))},{signal:i}),t.addEventListener("pointerenter",()=>{this.#r.toggleComment(!1,!0)},{signal:i}),t.addEventListener("pointerleave",()=>{this.#r.toggleComment(!1,!1)},{signal:i}),t}edit(t){const e=this.commentPopupPositionInLayer;let i,n;if(e)[i,n]=e;else{[i,n]=this.#r.commentButtonPosition;const{width:t,height:e,x:s,y:r}=this.#r;i=s+i*t,n=r+n*e}const s=this.#r.parent.boundingClientRect,{x:r,y:a,width:o,height:l}=s;this.#r._uiManager.editComment(this.#r,r+i*o,a+n*l,{...t,parentDimensions:s})}finish(){this.#ae&&(this.#ae.focus({focusVisible:this.#oe}),this.#oe=!1)}isDeleted(){return this.#ue||""===this.#ce}isEmpty(){return null===this.#ce}hasBeenEdited(){return this.isDeleted()||this.#ce!==this.#le}serialize(){return this.data}get data(){return{text:this.#ce,richText:this.#he,date:this.#de,deleted:this.isDeleted()}}set data(t){if(t!==this.#ce&&(this.#he=null),null===t)return this.#ce="",void(this.#ue=!0);this.#ce=t,this.#de=new Date,this.#ue=!1}setInitialText(t,e=null){this.#le=t,this.data=t,this.#de=null,this.#he=e}shown(){}destroy(){this.#ae?.remove(),this.#ae=null,this.#re?.remove(),this.#re=null,this.#ce="",this.#he=null,this.#de=null,this.#r=null,this.#oe=!1,this.#ue=!1}}class fe{#xt;#ge=!1;#me=null;#fe;#be;#ve;#ye;#we=null;#xe;#Ae=null;#_e;#Se=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:n=null,onPinching:s=null,onPinchEnd:r=null,signal:a}){this.#xt=t,this.#me=i,this.#fe=e,this.#be=n,this.#ve=s,this.#ye=r,this.#_e=new AbortController,this.#xe=AbortSignal.any([a,this.#_e.signal]),t.addEventListener("touchstart",this.#Ce.bind(this),{passive:!1,signal:this.#xe})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Yt.pixelRatio}#Ce(t){if(this.#fe?.())return;if(1===t.touches.length){if(this.#we)return;const t=this.#we=new AbortController,e=AbortSignal.any([this.#xe,t.signal]),i=this.#xt,n={capture:!0,signal:e,passive:!1},s=t=>{"touch"===t.pointerType&&(this.#we?.abort(),this.#we=null)};return i.addEventListener("pointerdown",t=>{"touch"===t.pointerType&&(Wt(t),s(t))},n),i.addEventListener("pointerup",s,n),void i.addEventListener("pointercancel",s,n)}if(!this.#Se){this.#Se=new AbortController;const t=AbortSignal.any([this.#xe,this.#Se.signal]),e=this.#xt,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Ee.bind(this),i);const n=this.#Te.bind(this);e.addEventListener("touchend",n,i),e.addEventListener("touchcancel",n,i),i.capture=!0,e.addEventListener("pointerdown",Wt,i),e.addEventListener("pointermove",Wt,i),e.addEventListener("pointercancel",Wt,i),e.addEventListener("pointerup",Wt,i),this.#be?.()}if(Wt(t),2!==t.touches.length||this.#me?.())return void(this.#Ae=null);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]),this.#Ae={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#Ee(t){if(!this.#Ae||2!==t.touches.length)return;Wt(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:n,screenY:s}=e,{screenX:r,screenY:a}=i,o=this.#Ae,{touch0X:l,touch0Y:h,touch1X:c,touch1Y:d}=o,u=c-l,p=d-h,g=r-n,m=a-s,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#ge&&Math.abs(b-f)<=fe.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(o.touch0X=n,o.touch0Y=s,o.touch1X=r,o.touch1Y=a,!this.#ge)return void(this.#ge=!0);const v=[(n+r)/2,(s+a)/2];this.#ve?.(v,b,f)}#Te(t){t.touches.length>=2||(this.#Se&&(this.#Se.abort(),this.#Se=null,this.#ye?.()),this.#Ae&&(Wt(t),this.#Ae=null,this.#ge=!1))}destroy(){this.#_e?.abort(),this.#_e=null,this.#we?.abort(),this.#we=null}}class be{#ke=null;#Me=null;#o=null;#l=null;#re=null;#De=!1;#Pe=null;#Ie="";#Re=null;#Le=null;#Be=null;#Fe=null;#Oe=null;#Ne="";#Ue=!1;#je=null;#ze=!1;#He=!1;#$e=!1;#We=null;#Ve=0;#Ge=0;#qe=null;#Xe=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#Ke=!1;#Ye=be._zIndex++;static _borderLineWidth=-1;static _colorManager=new ue;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=be.prototype._resizeWithKeyboard,e=pe.TRANSLATE_SMALL,i=pe.TRANSLATE_BIG;return pt(this,"_resizerKeyboardManager",new de([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],be.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null,this.annotationElementId=t.annotationElementId||null,this.creationDate=t.creationDate||new Date,this.modificationDate=t.modificationDate||null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,n],this.pageTranslation=[s,r];const[a,o]=this.parentDimensions;this.x=t.x/a,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return pt(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new ve({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(be._l10n??=t,be._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),-1!==be._borderLineWidth)return;const i=getComputedStyle(document.documentElement);be._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){ht("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#Ke}set _isDraggable(t){this.#Ke=t,this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#Ye}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):(this.#Je(),this.#Fe?.remove(),this.#Fe=null),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ue?this.#Ue=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;e?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,n){const[s,r]=this.parentDimensions;[i,n]=this.screenToPageTranslation(i,n),this.x=(t+i)/s,this.y=(e+n)/r,this.fixAndSetPosition()}_moveAfterPaste(t,e){const[i,n]=this.parentDimensions;this.setAt(t*i,e*n,this.width*i,this.height*n),this._onTranslated()}#Qe([t,e],i,n){[i,n]=this.screenToPageTranslation(i,n),this.x+=i/t,this.y+=n/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#Qe(this.parentDimensions,t,e)}translateInPage(t,e){this.#je||=[this.x,this.y,this.width,this.height],this.#Qe(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#je||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[n,s]}=this;if(this.x+=t/n,this.y+=e/s,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:a}=this;const[o,l]=this.getBaseTranslation();r+=o,a+=l;const{style:h}=i;h.left=`${(100*r).toFixed(2)}%`,h.top=`${(100*a).toFixed(2)}%`,this._onTranslating(r,a),i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#je&&(this.#je[0]!==this.x||this.#je[1]!==this.y)}get _hasBeenResized(){return!!this.#je&&(this.#je[2]!==this.width||this.#je[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=be,n=i/t,s=i/e;switch(this.rotation){case 90:return[-n,s];case 180:return[n,s];case 270:return[n,-s];default:return[-n,-s]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,n]}=this;let{x:s,y:r,width:a,height:o}=this;if(a*=i,o*=n,s*=i,r*=n,this._mustFixPosition)switch(t){case 0:s=Dt(s,0,i-a),r=Dt(r,0,n-o);break;case 90:s=Dt(s,0,i-o),r=Dt(r,a,n);break;case 180:s=Dt(s,a,i),r=Dt(r,o,n);break;case 270:s=Dt(s,o,i),r=Dt(r,0,n-a)}this.x=s/=i,this.y=r/=n;const[l,h]=this.getBaseTranslation();s+=l,r+=h,e.left=`${(100*s).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#Ze(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return be.#Ze(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return be.#Ze(t,e,360-this.parentRotation)}#ti(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(){const{div:{style:t},width:e,height:i}=this;t.width=`${(100*e).toFixed(2)}%`,t.height=`${(100*i).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#ei(){if(this.#Re)return;this.#Re=document.createElement("div"),this.#Re.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#Re.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#ii.bind(this,i),{signal:e}),t.addEventListener("contextmenu",$t,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#Re)}#ii(t,e){e.preventDefault();const{isMac:i}=_t.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const n=this._isDraggable;this._isDraggable=!1,this.#Le=[e.screenX,e.screenY];const s=new AbortController,r=this._uiManager.combinedSignal(s);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#ni.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",Wt,{passive:!1,signal:r}),window.addEventListener("contextmenu",$t,{signal:r}),this.#Be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{s.abort(),this.parent.togglePointerEvents(!0),this.#o?.toggle(!0),this._isDraggable=n,this.parent.div.style.cursor=a,this.div.style.cursor=o,this.#si()};window.addEventListener("pointerup",l,{signal:r}),window.addEventListener("blur",l,{signal:r})}#ri(t,e,i,n){this.width=i,this.height=n,this.x=t,this.y=e,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#si(){if(!this.#Be)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:n}=this.#Be;this.#Be=null;const s=this.x,r=this.y,a=this.width,o=this.height;s===t&&r===e&&a===i&&o===n||this.addCommands({cmd:this.#ri.bind(this,s,r,a,o),undo:this.#ri.bind(this,t,e,i,n),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#ni(t,e){const[i,n]=this.parentDimensions,s=this.x,r=this.y,a=this.width,o=this.height,l=be.MIN_SIZE/i,h=be.MIN_SIZE/n,c=this.#ti(this.rotation),d=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],u=this.#ti(360-this.rotation);let p,g,m=!1,f=!1;switch(t){case"topLeft":m=!0,p=(t,e)=>[0,0],g=(t,e)=>[t,e];break;case"topMiddle":p=(t,e)=>[t/2,0],g=(t,e)=>[t/2,e];break;case"topRight":m=!0,p=(t,e)=>[t,0],g=(t,e)=>[0,e];break;case"middleRight":f=!0,p=(t,e)=>[t,e/2],g=(t,e)=>[0,e/2];break;case"bottomRight":m=!0,p=(t,e)=>[t,e],g=(t,e)=>[0,0];break;case"bottomMiddle":p=(t,e)=>[t/2,e],g=(t,e)=>[t/2,0];break;case"bottomLeft":m=!0,p=(t,e)=>[0,e],g=(t,e)=>[t,0];break;case"middleLeft":f=!0,p=(t,e)=>[0,e/2],g=(t,e)=>[t,e/2]}const b=p(a,o),v=g(a,o);let y=d(...v);const w=be._round(s+y[0]),x=be._round(r+y[1]);let A,_,S=1,C=1;if(e.fromKeyboard)({deltaX:A,deltaY:_}=e);else{const{screenX:t,screenY:i}=e,[n,s]=this.#Le;[A,_]=this.screenToPageTranslation(t-n,i-s),this.#Le[0]=t,this.#Le[1]=i}var E,T;if([A,_]=(E=A/i,T=_/n,[u[0]*E+u[2]*T,u[1]*E+u[3]*T]),m){const t=Math.hypot(a,o);S=C=Math.max(Math.min(Math.hypot(v[0]-b[0]-A,v[1]-b[1]-_)/t,1/a,1/o),l/a,h/o)}else f?S=Dt(Math.abs(v[0]-b[0]-A),l,1)/a:C=Dt(Math.abs(v[1]-b[1]-_),h,1)/o;const k=be._round(a*S),M=be._round(o*C);y=d(...g(k,M));const D=w-y[0],P=x-y[1];this.#je||=[this.x,this.y,this.width,this.height],this.width=k,this.height=M,this.x=D,this.y=P,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#He)return this._editToolbar;this._editToolbar=new re(this),this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,i]of t)await this._editToolbar.addButton(e,i);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#o?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#o||(ge.initialize(be._l10n),this.#o=new ge(this),this.#ke&&(this.#o.data=this.#ke,this.#ke=null)),this.#o}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}focusCommentButton(){this.#l?.focusButton()}addCommentButton(){return this.#l||=new me(this)}addStandaloneCommentButton(){this.#re?this._uiManager.isEditingMode()&&this.#re.classList.remove("hidden"):this.hasComment&&(this.#re=this.#l.renderForStandalone(),this.div.append(this.#re))}removeStandaloneCommentButton(){this.#l.removeStandaloneCommentButton(),this.#re=null}hideStandaloneCommentButton(){this.#re?.classList.add("hidden")}get comment(){const{data:{richText:t,text:e,date:i,deleted:n}}=this.#l;return{text:e,richText:t,date:i,deleted:n,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#l||=new me(this),this.#l.data=t,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:t,popupRef:e,richText:i}){if(!e)return;if(this.#l||=new me(this),this.#l.setInitialText(t,i),!this.annotationElementId)return;const n=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);n&&this.updateFromAnnotationLayer(n)}get hasEditedComment(){return this.#l?.hasBeenEdited()}get hasDeletedComment(){return this.#l?.isDeleted()}get hasComment(){return!!this.#l&&!this.#l.isEmpty()&&!this.#l.isDeleted()}async editComment(t){this.#l||=new me(this),this.#l.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#l.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,i=100,[,,,n]=t.rect,[s]=this.pageDimensions,[r]=this.pageTranslation,a=r+s+1,o=n-i,l=a+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,o,l,n]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#l.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#De?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#ai();const[e,i]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*i/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/i).toFixed(2)}%`);const[n,s]=this.getInitialTranslation();return this.translate(n,s),oe(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Xe||=new fe({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#oi.bind(this),onPinching:this.#li.bind(this),onPinchEnd:this.#hi.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),t}#oi(){this.#Be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#o?.toggle(!1),this.parent.togglePointerEvents(!1)}#li(t,e,i){let n=i/e*.7+1-.7;if(1===n)return;const s=this.#ti(this.rotation),r=(t,e)=>[s[0]*t+s[2]*e,s[1]*t+s[3]*e],[a,o]=this.parentDimensions,l=this.x,h=this.y,c=this.width,d=this.height,u=be.MIN_SIZE/a,p=be.MIN_SIZE/o;n=Math.max(Math.min(n,1/c,1/d),u/c,p/d);const g=be._round(c*n),m=be._round(d*n);if(g===c&&m===d)return;this.#je||=[l,h,c,d];const f=r(c/2,d/2),b=be._round(l+f[0]),v=be._round(h+f[1]),y=r(g/2,m/2);this.x=b-y[0],this.y=v-y[1],this.width=g,this.height=m,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#hi(){this.#o?.toggle(!0),this.parent.togglePointerEvents(!0),this.#si()}pointerdown(t){const{isMac:e}=_t.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#Ue=!0,this._isDraggable?this.#ci(t):this.#di(t))}#di(t){const{isMac:e}=_t.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#ci(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const n=new AbortController,s=this._uiManager.combinedSignal(n),r={capture:!0,passive:!1,signal:s},a=t=>{n.abort(),this.#Pe=null,this.#Ue=!1,this._uiManager.endDragSession()||this.#di(t),i&&this._onStopDragging()};e&&(this.#Ve=t.clientX,this.#Ge=t.clientY,this.#Pe=t.pointerId,this.#Ie=t.pointerType,window.addEventListener("pointermove",t=>{i||(i=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:e,clientY:n,pointerId:s}=t;if(s!==this.#Pe)return void Wt(t);const[r,a]=this.screenToPageTranslation(e-this.#Ve,n-this.#Ge);this.#Ve=e,this.#Ge=n,this._uiManager.dragSelectedEditors(r,a)},r),window.addEventListener("touchmove",Wt,r),window.addEventListener("pointerdown",t=>{t.pointerType===this.#Ie&&(this.#Xe||t.isPrimary)&&a(t),Wt(t)},r));const o=t=>{this.#Pe&&this.#Pe!==t.pointerId?Wt(t):a(t)};window.addEventListener("pointerup",o,{signal:s}),window.addEventListener("blur",o,{signal:s})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#We&&clearTimeout(this.#We),this.#We=setTimeout(()=>{this.#We=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,i=this.rotation){const n=this.parentScale,[s,r]=this.pageDimensions,[a,o]=this.pageTranslation,l=t/n,h=e/n,c=this.x*s,d=this.y*r,u=this.width*s,p=this.height*r;switch(i){case 0:return[c+l+a,r-d-h-p+o,c+l+u+a,r-d-h+o];case 90:return[c+h+a,r-d+l+o,c+h+p+a,r-d+l+u+o];case 180:return[c-l-u+a,r-d+h+o,c-l+a,r-d+h+p+o];case 270:return[c-h-p+a,r-d-l-u+o,c-h+a,r-d-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,n,s,r]=t,a=s-i,o=r-n;switch(this.rotation){case 0:return[i,e-r,a,o];case 90:return[i,e-n,o,a];case 180:return[s,e-n,a,o];case 270:return[s,e-r,o,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&be._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#l?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:i,opacity:n,deleted:s,richText:r},uid:a,pageIndex:o,creationDate:l,modificationDate:h}=this;return{id:a,pageIndex:o,rect:this.getPDFRect(),richText:r,contentsObj:{str:t},creationDate:l,modificationDate:i||h,popupRef:!s,color:e,opacity:n}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#He=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#He=!1,!0)}isInEditMode(){return this.#He}shouldGetKeyboardEvents(){return this.#$e}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:n}=this.getClientDimensions(),{innerHeight:s,innerWidth:r}=window;return e<r&&n>0&&t<s&&i>0}#ai(){if(this.#Oe||!this.div)return;this.#Oe=new AbortController;const t=this._uiManager.combinedSignal(this.#Oe);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#ai()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,i){const n=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});n.rotation=t.rotation,n.#ke=t.accessibilityData,n._isCopy=t.isCopy||!1;const[s,r]=n.pageDimensions,[a,o,l,h]=n.getRectInCurrentCoords(t.rect,r);return n.x=a/s,n.y=o/r,n.width=l/s,n.height=h/r,n}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#Oe?.abort(),this.#Oe=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#We&&(clearTimeout(this.#We),this.#We=null),this.#Je(),this.removeEditToolbar(),this.#qe){for(const t of this.#qe.values())clearTimeout(t);this.#qe=null}this.parent=null,this.#Xe?.destroy(),this.#Xe=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#ei(),this.#Re.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[i,n,s,r]=this.getPDFRect();return[be._round(i+(s-i)*t),be._round(n+(r-n)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#l.commentPopupPositionInLayer}set commentPopupPosition(t){this.#l.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#l.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#l.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#l.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Re.children;if(!this.#Me){this.#Me=Array.from(e);const t=this.#ui.bind(this),i=this.#pi.bind(this),n=this._uiManager._signal;for(const e of this.#Me){const s=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:n}),e.addEventListener("blur",i,{signal:n}),e.addEventListener("focus",this.#gi.bind(this,s),{signal:n}),e.setAttribute("data-l10n-id",be._l10nResizer[s])}}const i=this.#Me[0];let n=0;for(const t of e){if(t===i)break;n++}const s=(360-this.rotation+this.parentRotation)%360/90*(this.#Me.length/4);if(s!==n){if(s<n)for(let t=0;t<n-s;t++)this.#Re.append(this.#Re.firstChild);else if(s>n)for(let t=0;t<s-n;t++)this.#Re.firstChild.before(this.#Re.lastChild);let t=0;for(const i of e){const e=this.#Me[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",be._l10nResizer[e])}}this.#mi(0),this.#$e=!0,this.#Re.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#ui(t){be._resizerKeyboardManager.exec(this,t)}#pi(t){this.#$e&&t.relatedTarget?.parentNode!==this.#Re&&this.#Je()}#gi(t){this.#Ne=this.#$e?t:""}#mi(t){if(this.#Me)for(const e of this.#Me)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#$e&&this.#ni(this.#Ne,{deltaX:t,deltaY:e,fromKeyboard:!0})}#Je(){this.#$e=!1,this.#mi(-1),this.#si()}_stopResizingWithKeyboard(){this.#Je(),this.div.focus()}select(){this.isSelected&&this._editToolbar?this._editToolbar.show():(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),this._editToolbar?(this._editToolbar?.show(),this.#o?.toggleAltTextBadge(!1)):this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#Re?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#o?.toggleAltTextBadge(!0),this.hasComment&&this._uiManager.toggleComment(this,!1,!1))}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){"BUTTON"!==t.target.nodeName&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.id}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#ze}set isEditing(t){this.#ze=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#qe||=new Map;const{action:e}=t;let i=this.#qe.get(e);return i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#qe.delete(e),0===this.#qe.size&&(this.#qe=null)},be._telemetryTimeout),void this.#qe.set(e,i)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#De=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#De=!0}updateFakeAnnotationElement(t){if(this.#Fe||this.deleted)return this.deleted?(this.#Fe.remove(),void(this.#Fe=null)):void((this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#Fe.updateEdited({rect:this.getPDFRect(),popup:this.comment}));this.#Fe=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class ve extends be{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const ye=3285377520,we=4294901760,xe=65535;class Ae{constructor(t){this.h1=t?4294967295&t:ye,this.h2=t?4294967295&t:ye}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let n=0,s=t.length;n<s;n++){const s=t.charCodeAt(n);s<=255?e[i++]=s:(e[i++]=s>>>8,e[i++]=255&s)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const n=i>>2,s=i-4*n,r=new Uint32Array(e.buffer,0,n);let a=0,o=0,l=this.h1,h=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let t=0;t<n;t++)1&t?(a=r[t],a=a*c&we|a*u&xe,a=a<<15|a>>>17,a=a*d&we|a*p&xe,l^=a,l=l<<13|l>>>19,l=5*l+3864292196):(o=r[t],o=o*c&we|o*u&xe,o=o<<15|o>>>17,o=o*d&we|o*p&xe,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(a=0,s){case 3:a^=e[4*n+2]<<16;case 2:a^=e[4*n+1]<<8;case 1:a^=e[4*n],a=a*c&we|a*u&xe,a=a<<15|a>>>17,a=a*d&we|a*p&xe,1&n?l^=a:h^=a}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&we|36045*t&xe,e=4283543511*e&we|(2950163797*(e<<16|t>>>16)&we)>>>16,t^=e>>>1,t=444984403*t&we|60499*t&xe,e=3301882366*e&we|(3120437893*(e<<16|t>>>16)&we)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const _e=Object.freeze({map:null,hash:"",transfer:void 0});class Se{#fi=!1;#bi=null;#vi=null;#yi=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const i=this.#yi.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#yi.get(t)}remove(t){const e=this.#yi.get(t);if(void 0!==e&&(e instanceof be&&this.#vi.delete(e.annotationElementId),this.#yi.delete(t),0===this.#yi.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor)){for(const t of this.#yi.values())if(t instanceof be)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#yi.get(t);let n=!1;if(void 0!==i)for(const[t,s]of Object.entries(e))i[t]!==s&&(n=!0,i[t]=s);else n=!0,this.#yi.set(t,e);n&&this.#wi(),e instanceof be&&((this.#vi||=new Map).set(e.annotationElementId,e),"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type))}has(t){return this.#yi.has(t)}get size(){return this.#yi.size}#wi(){this.#fi||(this.#fi=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#fi&&(this.#fi=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new Ce(this)}get serializable(){if(0===this.#yi.size)return _e;const t=new Map,e=new Ae,i=[],n=Object.create(null);let s=!1;for(const[i,r]of this.#yi){const a=r instanceof be?r.serialize(!1,n):r;a&&(t.set(i,a),e.update(`${i}:${JSON.stringify(a)}`),s||=!!a.bitmap)}if(s)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:_e}get editorStats(){let t=null;const e=new Map;let i=0,n=0;for(const s of this.#yi.values()){if(!(s instanceof be)){s.popup&&(s.popup.deleted?n+=1:i+=1);continue}s.isCommentDeleted?n+=1:s.hasEditedComment&&(i+=1);const r=s.telemetryFinalData;if(!r)continue;const{type:a}=r;e.has(a)||e.set(a,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const o=t[a]||=new Map;for(const[t,e]of Object.entries(r)){if("type"===t)continue;let i=o.get(t);i||(i=new Map,o.set(t,i));const n=i.get(e)??0;i.set(e,n+1)}}if((n>0||i>0)&&(t||=Object.create(null),t.comments={deleted:n,edited:i}),!t)return null;for(const[i,n]of e)t[i]=n.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#bi=null}updateEditor(t,e){const i=this.#vi?.get(t);return!!i&&(i.updateFromAnnotationLayer(e),!0)}getEditor(t){return this.#vi?.get(t)||null}get modifiedIds(){if(this.#bi)return this.#bi;const t=[];if(this.#vi)for(const e of this.#vi.values())e.serialize()&&t.push(e.annotationElementId);return this.#bi={ids:new Set(t),hash:t.join(",")}}[Symbol.iterator](){return this.#yi.entries()}}class Ce extends Se{#xi;constructor(t){super();const{map:e,hash:i,transfer:n}=t.serializable,s=structuredClone(e,n?{transfer:n}:null);this.#xi={map:s,hash:i,transfer:n}}get print(){ht("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#xi}get modifiedIds(){return pt(this,"modifiedIds",{ids:new Set,hash:""})}}class Ee{#Ai=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#Ai.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#Ai.has(t.loadedName)){if(ct(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:e,src:n,style:s}=t,r=new FontFace(e,n,s);this.addNativeFontFace(r);try{await r.load(),this.#Ai.add(e),i?.(t)}catch{lt(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}ht("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){throw lt(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return pt(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return pt(this,"isSyncFontLoadingSupported",_||_t.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(ct(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return pt(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function n(t,e,i,n){return t.substring(0,e)+n+t.substring(e+i)}let s,r;const a=this._document.createElement("canvas");a.width=1,a.height=1;const o=a.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=n(c,976,h.length,h);const d=1482184792;let u=i(c,16);for(s=0,r=h.length-3;s<r;s+=4)u=u-d+i(h,s)|0;var p;s<h.length&&(u=u-d+i(h+"XXX",s)|0),c=n(c,16,4,(p=u,String.fromCharCode(p>>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${h}";src:${`url(data:font/opentype;base64,${btoa(c)});`}}`;this.insertRule(g);const m=this._document.createElement("div");m.style.visibility="hidden",m.style.width=m.style.height="10px",m.style.position="absolute",m.style.top=m.style.left="0px";for(const e of[t.loadedName,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,i){if(++l>30)return lt("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,()=>{m.remove(),e.complete()})}}class Te{#_i;constructor(t,e=null,i,n){this.compiledGlyphs=Object.create(null),this.#_i=t,this._inspectFont=e,i&&Object.assign(this,i),n&&(this.charProcOperatorList=n)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Pt(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let n;try{n=t.get(i)}catch(t){lt(`getPathGenerator - ignoring character: "${t}".`)}const s=new Path2D(n||"");return this.fontExtraProperties||t.delete(i),this.compiledGlyphs[e]=s}get black(){return this.#_i.black}get bold(){return this.#_i.bold}get disableFontFace(){return this.#_i.disableFontFace??!1}get fontExtraProperties(){return this.#_i.fontExtraProperties??!1}get isInvalidPDFjsFont(){return this.#_i.isInvalidPDFjsFont}get isType3Font(){return this.#_i.isType3Font}get italic(){return this.#_i.italic}get missingFile(){return this.#_i.missingFile}get remeasure(){return this.#_i.remeasure}get vertical(){return this.#_i.vertical}get ascent(){return this.#_i.ascent}get defaultWidth(){return this.#_i.defaultWidth}get descent(){return this.#_i.descent}get bbox(){return this.#_i.bbox}get fontMatrix(){return this.#_i.fontMatrix}get fallbackName(){return this.#_i.fallbackName}get loadedName(){return this.#_i.loadedName}get mimetype(){return this.#_i.mimetype}get name(){return this.#_i.name}get data(){return this.#_i.data}clearData(){this.#_i.clearData()}get cssFontInfo(){return this.#_i.cssFontInfo}get systemFontInfo(){return this.#_i.systemFontInfo}get defaultVMetrics(){return this.#_i.defaultVMetrics}}function ke(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const Me=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,De=function(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[n,s,...r]=i;if(!t(n)&&!Number.isInteger(n))return!1;if(!e(s))return!1;const a=r.length;let o=!0;switch(s.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return 0===a;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(4!==a)return!1;o=!1;break;default:return!1}for(const t of r)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,Me,t=>"object"==typeof t&&"string"==typeof t?.name);class Pe{#Si=new Map;#Ci=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#Ci.then(()=>{for(const[t]of this.#Si)t.call(this,i)})}addEventListener(t,e,i=null){let n=null;if(i?.signal instanceof AbortSignal){const{signal:s}=i;if(s.aborted)return void lt("LoopbackPort - cannot use an `aborted` signal.");const r=()=>this.removeEventListener(t,e);n=()=>s.removeEventListener("abort",r),s.addEventListener("abort",r)}this.#Si.set(e,n)}removeEventListener(t,e){const i=this.#Si.get(e);i?.(),this.#Si.delete(e)}terminate(){for(const[,t]of this.#Si)t?.();this.#Si.clear()}}const Ie=1,Re=2,Le=1,Be=2,Fe=3,Oe=4,Ne=5,Ue=6,je=7,ze=8;function He(){}function $e(t){if(t instanceof wt||t instanceof bt||t instanceof mt||t instanceof vt||t instanceof ft)return t;switch(t instanceof Error||"object"==typeof t&&null!==t||ht('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new wt(t.message);case"InvalidPDFException":return new bt(t.message);case"PasswordException":return new mt(t.message,t.code);case"ResponseException":return new vt(t.message,t.status,t.missing);case"UnknownErrorException":return new ft(t.message,t.details)}return new ft(t.message,t.toString())}class We{#Ei=new AbortController;constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),i.addEventListener("message",this.#Ti.bind(this),{signal:this.#Ei.signal})}#Ti({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#ki(t);if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===Ie)i.resolve(t.data);else{if(t.callback!==Re)throw new Error("Unexpected callback case");i.reject($e(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,n=t.sourceName,s=this.comObj;return void Promise.try(e,t.data).then(function(e){s.postMessage({sourceName:i,targetName:n,callback:Ie,callbackId:t.callbackId,data:e})},function(e){s.postMessage({sourceName:i,targetName:n,callback:Re,callbackId:t.callbackId,reason:$e(e)})})}t.streamId?this.#Mi(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const n=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[n]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:n,data:e},i)}catch(t){s.reject(t)}return s.promise}sendWithStream(t,e,i,n){const s=this.streamId++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[s]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:r,targetName:a,action:t,streamId:s,data:e,desiredSize:i.desiredSize},n),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[s].pullCall=e,o.postMessage({sourceName:r,targetName:a,stream:Ue,streamId:s,desiredSize:t.desiredSize}),e.promise},cancel:t=>{ct(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[s].cancelCall=e,this.streamControllers[s].isClosed=!0,o.postMessage({sourceName:r,targetName:a,stream:Le,streamId:s,reason:$e(t)}),e.promise}},i)}#Mi(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,r=this,a=this.actionHandler[t.action],o={enqueue(t,r=1,a){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=r,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),s.postMessage({sourceName:i,targetName:n,stream:Oe,streamId:e,chunk:t},a)},close(){this.isCancelled||(this.isCancelled=!0,s.postMessage({sourceName:i,targetName:n,stream:Fe,streamId:e}),delete r.streamSinks[e])},error(t){ct(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,s.postMessage({sourceName:i,targetName:n,stream:Ne,streamId:e,reason:$e(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,Promise.try(a,t.data,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:ze,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:ze,streamId:e,reason:$e(t)})})}#ki(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case ze:t.success?r.startCall.resolve():r.startCall.reject($e(t.reason));break;case je:t.success?r.pullCall.resolve():r.pullCall.reject($e(t.reason));break;case Ue:if(!a){s.postMessage({sourceName:i,targetName:n,stream:je,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=t.desiredSize,Promise.try(a.onPull||He).then(function(){s.postMessage({sourceName:i,targetName:n,stream:je,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:je,streamId:e,reason:$e(t)})});break;case Oe:if(ct(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Fe:if(ct(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#Di(r,e);break;case Ne:ct(r,"error should have stream controller"),r.controller.error($e(t.reason)),this.#Di(r,e);break;case Be:t.success?r.cancelCall.resolve():r.cancelCall.reject($e(t.reason)),this.#Di(r,e);break;case Le:if(!a)break;const o=$e(t.reason);Promise.try(a.onCancel||He,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:Be,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:Be,streamId:e,reason:$e(t)})}),a.sinkCapability.reject(o),a.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#Di(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#Ei?.abort(),this.#Ei=null}}class Ve{#Pi=!1;constructor({enableHWA:t=!1}){this.#Pi=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#Pi})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){ht("Abstract method `_createCanvas` called.")}}class Ge extends Ve{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}}class qe{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(t=>({cMapData:t,isCompressed:this.isCompressed})).catch(t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){ht("Abstract method `_fetch` called.")}}class Xe extends qe{async _fetch(t){const e=await Ft(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):At(e)}}class Ke{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,n,s){return"none"}destroy(t=!1){}}class Ye extends Ke{#Ii;#Ri;#Li;#Bi;#Fi;#Oi;#x=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#Bi=t,this.#Fi=e}get#_(){return this.#Ri||=new Map}get#Ni(){return this.#Oi||=new Map}get#Ui(){if(!this.#Li){const t=this.#Fi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#Fi.createElementNS(Lt,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#Li=this.#Fi.createElementNS(Lt,"defs"),t.append(i),i.append(this.#Li),this.#Fi.body.append(t)}return this.#Li}#ji(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const n=i.join(",");return[n,n,n]}const[e,i,n]=t,s=new Array(256),r=new Array(256),a=new Array(256);for(let t=0;t<256;t++)s[t]=e[t]/255,r[t]=i[t]/255,a[t]=n[t]/255;return[s.join(","),r.join(","),a.join(",")]}#zi(t){if(void 0===this.#Ii){this.#Ii="";const t=this.#Fi.URL;t!==this.#Fi.baseURI&&(Ut(t)?lt('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ii=ut(t,""))}return`url(${this.#Ii}#${t})`}addFilter(t){if(!t)return"none";let e=this.#_.get(t);if(e)return e;const[i,n,s]=this.#ji(t),r=1===t.length?i:`${i}${n}${s}`;if(e=this.#_.get(r),e)return this.#_.set(t,e),e;const a=`g_${this.#Bi}_transfer_map_${this.#x++}`,o=this.#zi(a);this.#_.set(t,o),this.#_.set(r,o);const l=this.#Hi(a);return this.#$i(i,n,s,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,n="base";let s=this.#Ni.get(n);if(s?.key===i)return s.url;if(s?(s.filter?.remove(),s.key=i,s.url="none",s.filter=null):(s={key:i,url:"none",filter:null},this.#Ni.set(n,s)),!t||!e)return s.url;const r=this.#Wi(t);t=Ct.makeHexColor(...r);const a=this.#Wi(e);if(e=Ct.makeHexColor(...a),this.#Ui.style.color="","#000000"===t&&"#ffffff"===e||t===e)return s.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#Bi}_hcm_filter`,c=s.filter=this.#Hi(h);this.#$i(l,l,l,c),this.#Vi(c);const d=(t,e)=>{const i=r[t]/255,n=a[t]/255,s=new Array(e+1);for(let t=0;t<=e;t++)s[t]=i+t/e*(n-i);return s.join(",")};return this.#$i(d(0,5),d(1,5),d(2,5),c),s.url=this.#zi(h),s.url}addAlphaFilter(t){let e=this.#_.get(t);if(e)return e;const[i]=this.#ji([t]),n=`alpha_${i}`;if(e=this.#_.get(n),e)return this.#_.set(t,e),e;const s=`g_${this.#Bi}_alpha_map_${this.#x++}`,r=this.#zi(s);this.#_.set(t,r),this.#_.set(n,r);const a=this.#Hi(s);return this.#Gi(i,a),r}addLuminosityFilter(t){let e,i,n=this.#_.get(t||"luminosity");if(n)return n;if(t?([e]=this.#ji([t]),i=`luminosity_${e}`):i="luminosity",n=this.#_.get(i),n)return this.#_.set(t,n),n;const s=`g_${this.#Bi}_luminosity_map_${this.#x++}`,r=this.#zi(s);this.#_.set(t,r),this.#_.set(i,r);const a=this.#Hi(s);return this.#qi(a),t&&this.#Gi(e,a),r}addHighlightHCMFilter(t,e,i,n,s){const r=`${e}-${i}-${n}-${s}`;let a=this.#Ni.get(t);if(a?.key===r)return a.url;if(a?(a.filter?.remove(),a.key=r,a.url="none",a.filter=null):(a={key:r,url:"none",filter:null},this.#Ni.set(t,a)),!e||!i)return a.url;const[o,l]=[e,i].map(this.#Wi.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,u]=[n,s].map(this.#Wi.bind(this));c<h&&([h,c,d,u]=[c,h,u,d]),this.#Ui.style.color="";const p=(t,e,i)=>{const n=new Array(256),s=(c-h)/i,r=t/255,a=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*s),i=r+t*a;for(let t=o;t<=e;t++)n[t]=i;o=e+1}for(let t=o;t<256;t++)n[t]=n[o-1];return n.join(",")},g=`g_${this.#Bi}_hcm_${t}_filter`,m=a.filter=this.#Hi(g);return this.#Vi(m),this.#$i(p(d[0],u[0],5),p(d[1],u[1],5),p(d[2],u[2],5),m),a.url=this.#zi(g),a.url}destroy(t=!1){t&&this.#Oi?.size||(this.#Li?.parentNode.parentNode.remove(),this.#Li=null,this.#Ri?.clear(),this.#Ri=null,this.#Oi?.clear(),this.#Oi=null,this.#x=0)}#qi(t){const e=this.#Fi.createElementNS(Lt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#Vi(t){const e=this.#Fi.createElementNS(Lt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#Hi(t){const e=this.#Fi.createElementNS(Lt,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#Ui.append(e),e}#Xi(t,e,i){const n=this.#Fi.createElementNS(Lt,e);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),t.append(n)}#$i(t,e,i,n){const s=this.#Fi.createElementNS(Lt,"feComponentTransfer");n.append(s),this.#Xi(s,"feFuncR",t),this.#Xi(s,"feFuncG",e),this.#Xi(s,"feFuncB",i)}#Gi(t,e){const i=this.#Fi.createElementNS(Lt,"feComponentTransfer");e.append(i),this.#Xi(i,"feFuncA",t)}#Wi(t){return this.#Ui.style.color=t,Gt(getComputedStyle(this.#Ui).getPropertyValue("color"))}}class Je{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){ht("Abstract method `_fetch` called.")}}class Qe extends Je{async _fetch(t){const e=await Ft(t,"arraybuffer");return new Uint8Array(e)}}class Ze{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!t)throw new Error("Wasm filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load wasm data at: ${e}`)})}async _fetch(t){ht("Abstract method `_fetch` called.")}}class ti extends Ze{async _fetch(t){const e=await Ft(t,"arraybuffer");return new Uint8Array(e)}}async function ei(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}_&<("Please use the `legacy` build in Node.js environments.");class ii extends Ke{}class ni extends Ve{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire("file:///home/ubuntu/projects/dash-pdf-components/node_modules/.pnpm/pdfjs-dist@5.4.296/node_modules/pdfjs-dist/build/pdf.mjs")("@napi-rs/canvas").createCanvas(t,e)}}class si extends qe{async _fetch(t){return ei(t)}}class ri extends Je{async _fetch(t){return ei(t)}}class ai extends Ze{async _fetch(t){return ei(t)}}const oi="__forcedDependency",{floor:li,ceil:hi}=Math;function ci(t,e,i,n,s,r){t[4*e+0]=Math.min(t[4*e+0],i),t[4*e+1]=Math.min(t[4*e+1],n),t[4*e+2]=Math.max(t[4*e+2],s),t[4*e+3]=Math.max(t[4*e+3],r)}const di=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class ui{#Ki;#Yi;constructor(t,e){this.#Ki=t,this.#Yi=e}get length(){return this.#Ki.length}isEmpty(t){return this.#Ki[t]===di}minX(t){return this.#Yi[4*t+0]/256}minY(t){return this.#Yi[4*t+1]/256}maxX(t){return(this.#Yi[4*t+2]+1)/256}maxY(t){return(this.#Yi[4*t+3]+1)/256}}const pi=(t,e)=>{if(!t)return;let i=t.get(e);return i||(i={dependencies:new Set,isRenderingOperation:!1},t.set(e,i)),i};class gi{#Ji={__proto__:null};#Qi={__proto__:null,transform:[],moveText:[],sameLineText:[],[oi]:[]};#Zi=new Map;#tn=[];#en=[];#in=[[1,0,0,1,0,0]];#nn=[-1/0,-1/0,1/0,1/0];#sn=new Float64Array([1/0,1/0,-1/0,-1/0]);#rn=-1;#an=new Set;#on=new Map;#ln=new Map;#hn;#cn;#dn;#Ki;#un;constructor(t,e,i=!1){this.#hn=t.width,this.#cn=t.height,this.#pn(e),i&&(this.#un=new Map)}growOperationsCount(t){t>=this.#Ki.length&&this.#pn(t,this.#Ki)}#pn(t,e){const i=new ArrayBuffer(4*t);this.#dn=new Uint8ClampedArray(i),this.#Ki=new Uint32Array(i),e&&e.length>0?(this.#Ki.set(e),this.#Ki.fill(di,e.length)):this.#Ki.fill(di)}save(t){return this.#Ji={__proto__:this.#Ji},this.#Qi={__proto__:this.#Qi,transform:{__proto__:this.#Qi.transform},moveText:{__proto__:this.#Qi.moveText},sameLineText:{__proto__:this.#Qi.sameLineText},[oi]:{__proto__:this.#Qi[oi]}},this.#nn={__proto__:this.#nn},this.#tn.push(t),this}restore(t){const e=Object.getPrototypeOf(this.#Ji);if(null===e)return this;this.#Ji=e,this.#Qi=Object.getPrototypeOf(this.#Qi),this.#nn=Object.getPrototypeOf(this.#nn);const i=this.#tn.pop();return void 0!==i&&(pi(this.#un,t)?.dependencies.add(i),this.#Ki[t]=this.#Ki[i]),this}recordOpenMarker(t){return this.#tn.push(t),this}getOpenMarker(){return 0===this.#tn.length?null:this.#tn.at(-1)}recordCloseMarker(t){const e=this.#tn.pop();return void 0!==e&&(pi(this.#un,t)?.dependencies.add(e),this.#Ki[t]=this.#Ki[e]),this}beginMarkedContent(t){return this.#en.push(t),this}endMarkedContent(t){const e=this.#en.pop();return void 0!==e&&(pi(this.#un,t)?.dependencies.add(e),this.#Ki[t]=this.#Ki[e]),this}pushBaseTransform(t){return this.#in.push(Ct.multiplyByDOMMatrix(this.#in.at(-1),t.getTransform())),this}popBaseTransform(){return this.#in.length>1&&this.#in.pop(),this}recordSimpleData(t,e){return this.#Ji[t]=e,this}recordIncrementalData(t,e){return this.#Qi[t].push(e),this}resetIncrementalData(t,e){return this.#Qi[t].length=0,this}recordNamedData(t,e){return this.#Zi.set(t,e),this}recordSimpleDataFromNamed(t,e,i){this.#Ji[t]=this.#Zi.get(e)??i}recordFutureForcedDependency(t,e){return this.recordIncrementalData(oi,e),this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Ji&&this.recordFutureForcedDependency(e,this.#Ji[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#an)this.recordFutureForcedDependency(oi,t);return this}resetBBox(t){return this.#rn!==t&&(this.#rn=t,this.#sn[0]=1/0,this.#sn[1]=1/0,this.#sn[2]=-1/0,this.#sn[3]=-1/0),this}recordClipBox(t,e,i,n,s,r){const a=Ct.multiplyByDOMMatrix(this.#in.at(-1),e.getTransform()),o=[1/0,1/0,-1/0,-1/0];Ct.axialAlignedBoundingBox([i,s,n,r],a,o);const l=Ct.intersect(this.#nn,o);return l?(this.#nn[0]=l[0],this.#nn[1]=l[1],this.#nn[2]=l[2],this.#nn[3]=l[3]):(this.#nn[0]=this.#nn[1]=1/0,this.#nn[2]=this.#nn[3]=-1/0),this}recordBBox(t,e,i,n,s,r){const a=this.#nn;if(a[0]===1/0)return this;const o=Ct.multiplyByDOMMatrix(this.#in.at(-1),e.getTransform());if(a[0]===-1/0)return Ct.axialAlignedBoundingBox([i,s,n,r],o,this.#sn),this;const l=[1/0,1/0,-1/0,-1/0];return Ct.axialAlignedBoundingBox([i,s,n,r],o,l),this.#sn[0]=Math.min(this.#sn[0],Math.max(l[0],a[0])),this.#sn[1]=Math.min(this.#sn[1],Math.max(l[1],a[1])),this.#sn[2]=Math.max(this.#sn[2],Math.min(l[2],a[2])),this.#sn[3]=Math.max(this.#sn[3],Math.min(l[3],a[3])),this}recordCharacterBBox(t,e,i,n=1,s=0,r=0,a){const o=i.bbox;let l,h;if(o&&(l=o[2]!==o[0]&&o[3]!==o[1]&&this.#ln.get(i),!1!==l&&(h=[0,0,0,0],Ct.axialAlignedBoundingBox(o,i.fontMatrix,h),1===n&&0===s&&0===r||Ct.scaleMinMax([n,0,0,-n,s,r],h),l)))return this.recordBBox(t,e,h[0],h[2],h[1],h[3]);if(!a)return this.recordFullPageBBox(t);const c=a();return o&&h&&void 0===l&&(l=h[0]<=s-c.actualBoundingBoxLeft&&h[2]>=s+c.actualBoundingBoxRight&&h[1]<=r-c.actualBoundingBoxAscent&&h[3]>=r+c.actualBoundingBoxDescent,this.#ln.set(i,l),l)?this.recordBBox(t,e,h[0],h[2],h[1],h[3]):this.recordBBox(t,e,s-c.actualBoundingBoxLeft,s+c.actualBoundingBoxRight,r-c.actualBoundingBoxAscent,r+c.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#sn[0]=Math.max(0,this.#nn[0]),this.#sn[1]=Math.max(0,this.#nn[1]),this.#sn[2]=Math.min(this.#hn,this.#nn[2]),this.#sn[3]=Math.min(this.#cn,this.#nn[3]),this}getSimpleIndex(t){return this.#Ji[t]}recordDependencies(t,e){const i=this.#an,n=this.#Ji,s=this.#Qi;for(const t of e)t in this.#Ji?i.add(n[t]):t in s&&s[t].forEach(i.add,i);return this}recordNamedDependency(t,e){return this.#Zi.has(e)&&this.#an.add(this.#Zi.get(e)),this}recordOperation(t,e=!1){if(this.recordDependencies(t,[oi]),this.#un){const e=pi(this.#un,t),{dependencies:i}=e;this.#an.forEach(i.add,i),this.#tn.forEach(i.add,i),this.#en.forEach(i.add,i),i.delete(t),e.isRenderingOperation=!0}if(this.#rn===t){const i=li(256*this.#sn[0]/this.#hn),n=li(256*this.#sn[1]/this.#cn),s=hi(256*this.#sn[2]/this.#hn),r=hi(256*this.#sn[3]/this.#cn);ci(this.#dn,t,i,n,s,r);for(const e of this.#an)e!==t&&ci(this.#dn,e,i,n,s,r);for(const e of this.#tn)e!==t&&ci(this.#dn,e,i,n,s,r);for(const e of this.#en)e!==t&&ci(this.#dn,e,i,n,s,r);e||(this.#an.clear(),this.#rn=-1)}return this}recordShowTextOperation(t,e=!1){const i=Array.from(this.#an);this.recordOperation(t,e),this.recordIncrementalData("sameLineText",t);for(const t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){return this.#rn===t&&(this.#rn=-1,this.#nn[0]=Math.max(this.#nn[0],this.#sn[0]),this.#nn[1]=Math.max(this.#nn[1],this.#sn[1]),this.#nn[2]=Math.min(this.#nn[2],this.#sn[2]),this.#nn[3]=Math.min(this.#nn[3],this.#sn[3]),e||this.#an.clear()),this}_takePendingDependencies(){const t=this.#an;return this.#an=new Set,t}_extractOperation(t){const e=this.#on.get(t);return this.#on.delete(t),e}_pushPendingDependencies(t){for(const e of t)this.#an.add(e)}take(){return this.#ln.clear(),new ui(this.#Ki,this.#dn)}takeDebugMetadata(){return this.#un}}class mi{#gn;#mn;#fn;#bn=0;#vn=0;constructor(t,e,i){if(t instanceof mi&&t.#fn===!!i)return t;this.#gn=t,this.#mn=e,this.#fn=!!i}growOperationsCount(){throw new Error("Unreachable")}save(t){return this.#vn++,this.#gn.save(this.#mn),this}restore(t){return this.#vn>0&&(this.#gn.restore(this.#mn),this.#vn--),this}recordOpenMarker(t){return this.#bn++,this}getOpenMarker(){return this.#bn>0?this.#mn:this.#gn.getOpenMarker()}recordCloseMarker(t){return this.#bn--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#gn.pushBaseTransform(t),this}popBaseTransform(){return this.#gn.popBaseTransform(),this}recordSimpleData(t,e){return this.#gn.recordSimpleData(t,this.#mn),this}recordIncrementalData(t,e){return this.#gn.recordIncrementalData(t,this.#mn),this}resetIncrementalData(t,e){return this.#gn.resetIncrementalData(t,this.#mn),this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){return this.#gn.recordSimpleDataFromNamed(t,e,this.#mn),this}recordFutureForcedDependency(t,e){return this.#gn.recordFutureForcedDependency(t,this.#mn),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#gn.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#gn.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#fn||this.#gn.resetBBox(this.#mn),this}recordClipBox(t,e,i,n,s,r){return this.#fn||this.#gn.recordClipBox(this.#mn,e,i,n,s,r),this}recordBBox(t,e,i,n,s,r){return this.#fn||this.#gn.recordBBox(this.#mn,e,i,n,s,r),this}recordCharacterBBox(t,e,i,n,s,r,a){return this.#fn||this.#gn.recordCharacterBBox(this.#mn,e,i,n,s,r,a),this}recordFullPageBBox(t){return this.#fn||this.#gn.recordFullPageBBox(this.#mn),this}getSimpleIndex(t){return this.#gn.getSimpleIndex(t)}recordDependencies(t,e){return this.#gn.recordDependencies(this.#mn,e),this}recordNamedDependency(t,e){return this.#gn.recordNamedDependency(this.#mn,e),this}recordOperation(t){return this.#gn.recordOperation(this.#mn,!0),this}recordShowTextOperation(t){return this.#gn.recordShowTextOperation(this.#mn,!0),this}bboxToClipBoxDropOperation(t){return this.#fn||this.#gn.bboxToClipBoxDropOperation(this.#mn,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const fi=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],bi=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],vi=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],yi=["filter","fillColor","fillAlpha"],wi=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],xi=["transform"],Ai=["transform","fillColor"],_i="Fill",Si="Stroke",Ci="Shading";function Ei(t,e){if(!e)return;const i=e[2]-e[0],n=e[3]-e[1],s=new Path2D;s.rect(e[0],e[1],i,n),t.clip(s)}class Ti{isModifyingCurrentTransform(){return!1}getPattern(){ht("Abstract method `getPattern` called.")}}class ki extends Ti{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,n){let s;if(n===Si||n===_i){const r=e.current.getClippedPathBoundingBox(n,qt(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,o=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",a,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-r[0],-r[1]),i=Ct.transform(i,[1,0,0,1,r[0],r[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),Ei(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),s=t.createPattern(l.canvas,"no-repeat");const c=new DOMMatrix(i);s.setTransform(c)}else Ei(t,this._bbox),s=this._createGradient(t);return s}}function Mi(t,e,i,n,s,r,a,o){const l=e.coords,h=e.colors,c=t.data,d=4*t.width;let u;l[i+1]>l[n+1]&&(u=i,i=n,n=u,u=r,r=a,a=u),l[n+1]>l[s+1]&&(u=n,n=s,s=u,u=a,a=o,o=u),l[i+1]>l[n+1]&&(u=i,i=n,n=u,u=r,r=a,a=u);const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[n]+e.offsetX)*e.scaleX,f=(l[n+1]+e.offsetY)*e.scaleY,b=(l[s]+e.offsetX)*e.scaleX,v=(l[s+1]+e.offsetY)*e.scaleY;if(g>=v)return;const y=h[r],w=h[r+1],x=h[r+2],A=h[a],_=h[a+1],S=h[a+2],C=h[o],E=h[o+1],T=h[o+2],k=Math.round(g),M=Math.round(v);let D,P,I,R,L,B,F,O;for(let t=k;t<=M;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);D=p-(p-m)*e,P=y-(y-A)*e,I=w-(w-_)*e,R=x-(x-S)*e}else{let e;e=t>v?1:f===v?0:(f-t)/(f-v),D=m-(m-b)*e,P=A-(A-C)*e,I=_-(_-E)*e,R=S-(S-T)*e}let e;e=t<g?0:t>v?1:(g-t)/(g-v),L=p-(p-b)*e,B=y-(y-C)*e,F=w-(w-E)*e,O=x-(x-T)*e;const i=Math.round(Math.min(D,L)),n=Math.round(Math.max(D,L));let s=d*t+4*i;for(let t=i;t<=n;t++)e=(D-t)/(D-L),e<0?e=0:e>1&&(e=1),c[s++]=P-(P-B)*e|0,c[s++]=I-(I-F)*e|0,c[s++]=R-(R-O)*e|0,c[s++]=255}}function Di(t,e,i){const n=e.coords,s=e.colors;let r,a;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(n.length/o)-1,h=o-1;for(r=0;r<l;r++){let e=r*o;for(let r=0;r<h;r++,e++)Mi(t,i,n[e],n[e+1],n[e+o],s[e],s[e+1],s[e+o]),Mi(t,i,n[e+o+1],n[e+1],n[e+o],s[e+o+1],s[e+1],s[e+o])}break;case"triangles":for(r=0,a=n.length;r<a;r+=3)Mi(t,i,n[r],n[r+1],n[r+2],s[r],s[r+1],s[r+2]);break;default:throw new Error("illegal figure")}}class Pi extends Ti{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null}_createMeshCanvas(t,e,i){const n=Math.floor(this._bounds[0]),s=Math.floor(this._bounds[1]),r=Math.ceil(this._bounds[2])-n,a=Math.ceil(this._bounds[3])-s,o=Math.min(Math.ceil(Math.abs(r*t[0]*1.1)),3e3),l=Math.min(Math.ceil(Math.abs(a*t[1]*1.1)),3e3),h=r/o,c=a/l,d={coords:this._coords,colors:this._colors,offsetX:-n,offsetY:-s,scaleX:1/h,scaleY:1/c},u=o+4,p=l+4,g=i.getCanvas("mesh",u,p),m=g.context,f=m.createImageData(o,l);if(e){const t=f.data;for(let i=0,n=t.length;i<n;i+=4)t[i]=e[0],t[i+1]=e[1],t[i+2]=e[2],t[i+3]=255}for(const t of this._figures)Di(f,t,d);m.putImageData(f,2,2);return{canvas:g.canvas,offsetX:n-2*h,offsetY:s-2*c,scaleX:h,scaleY:c}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,n){Ei(t,this._bbox);const s=new Float32Array(2);if(n===Ci)Ct.singularValueDecompose2dScale(qt(t),s);else if(this.matrix){Ct.singularValueDecompose2dScale(this.matrix,s);const[t,i]=s;Ct.singularValueDecompose2dScale(e.baseTransform,s),s[0]*=t,s[1]*=i}else Ct.singularValueDecompose2dScale(e.baseTransform,s);const r=this._createMeshCanvas(s,n===Ci?null:this._background,e.cachedCanvases);return n!==Ci&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class Ii extends Ti{getPattern(){return"hotpink"}}const Ri=1,Li=2;class Bi{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,n){this.color=t[1],this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.ctx=e,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t,e){const{bbox:i,operatorList:n,paintType:s,tilingType:r,color:a,canvasGraphicsFactory:o}=this;let{xstep:l,ystep:h}=this;l=Math.abs(l),h=Math.abs(h),ot("TilingType: "+r);const c=i[0],d=i[1],u=i[2],p=i[3],g=u-c,m=p-d,f=new Float32Array(2);Ct.singularValueDecompose2dScale(this.matrix,f);const[b,v]=f;Ct.singularValueDecompose2dScale(this.baseTransform,f);const y=b*f[0],w=v*f[1];let x=g,A=m,_=!1,S=!1;const C=Math.ceil(l*y),E=Math.ceil(h*w);C>=Math.ceil(g*y)?x=l:_=!0,E>=Math.ceil(m*w)?A=h:S=!0;const T=this.getSizeAndScale(x,this.ctx.canvas.width,y),k=this.getSizeAndScale(A,this.ctx.canvas.height,w),M=t.cachedCanvases.getCanvas("pattern",T.size,k.size),D=M.context,P=o.createCanvasGraphics(D,e);if(P.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(P,s,a),D.translate(-T.scale*c,-k.scale*d),P.transform(0,T.scale,0,0,k.scale,0,0),D.save(),P.dependencyTracker?.save(),this.clipBbox(P,c,d,u,p),P.baseTransform=qt(P.ctx),P.executeOperatorList(n),P.endDrawing(),P.dependencyTracker?.restore(),D.restore(),_||S){const e=M.canvas;_&&(x=l),S&&(A=h);const i=this.getSizeAndScale(x,this.ctx.canvas.width,y),n=this.getSizeAndScale(A,this.ctx.canvas.height,w),s=i.size,r=n.size,a=t.cachedCanvases.getCanvas("pattern-workaround",s,r),o=a.context,u=_?Math.floor(g/l):0,p=S?Math.floor(m/h):0;for(let t=0;t<=u;t++)for(let i=0;i<=p;i++)o.drawImage(e,s*t,r*i,s,r,0,0,s,r);return{canvas:a.canvas,scaleX:i.scale,scaleY:n.scale,offsetX:c,offsetY:d}}return{canvas:M.canvas,scaleX:T.scale,scaleY:k.scale,offsetX:c,offsetY:d}}getSizeAndScale(t,e,i){const n=Math.max(Bi.MAX_PATTERN_SIZE,e);let s=Math.ceil(t*i);return s>=n?s=n:i=s/t,{scale:i,size:s}}clipBbox(t,e,i,n,s){const r=n-e,a=s-i;t.ctx.rect(e,i,r,a),Ct.axialAlignedBoundingBox([e,i,n,s],qt(t.ctx),t.current.minMax),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const n=t.ctx,s=t.current;switch(e){case Ri:const{fillStyle:t,strokeStyle:r}=this.ctx;n.fillStyle=s.fillColor=t,n.strokeStyle=s.strokeColor=r;break;case Li:n.fillStyle=n.strokeStyle=i,s.fillColor=s.strokeColor=i;break;default:throw new yt(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,n,s){let r=i;n!==Ci&&(r=Ct.transform(r,e.baseTransform),this.matrix&&(r=Ct.transform(r,this.matrix)));const a=this.createPatternCanvas(e,s);let o=new DOMMatrix(r);o=o.translate(a.offsetX,a.offsetY),o=o.scale(1/a.scaleX,1/a.scaleY);const l=t.createPattern(a.canvas,"repeat");return l.setTransform(o),l}}function Fi({src:t,srcPos:e=0,dest:i,width:n,height:s,nonBlackColor:r=4294967295,inverseDecode:a=!1}){const o=_t.isLittleEndian?4278190080:255,[l,h]=a?[r,o]:[o,r],c=n>>3,d=7&n,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let n=0;n<s;n++){for(const n=e+c;e<n;e++){const n=e<u?t[e]:255;i[p++]=128&n?h:l,i[p++]=64&n?h:l,i[p++]=32&n?h:l,i[p++]=16&n?h:l,i[p++]=8&n?h:l,i[p++]=4&n?h:l,i[p++]=2&n?h:l,i[p++]=1&n?h:l}if(0===d)continue;const n=e<u?t[e++]:255;for(let t=0;t<d;t++)i[p++]=n&1<<7-t?h:l}return{srcPos:e,destPos:p}}const Oi=16,Ni=new DOMMatrix,Ui=new Float32Array(2),ji=new Float32Array([1/0,1/0,-1/0,-1/0]);class zi{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,i){let n;return void 0!==this.cache[t]?(n=this.cache[t],this.canvasFactory.reset(n,e,i)):(n=this.canvasFactory.create(e,i),this.cache[t]=n),n}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function Hi(t,e,i,n,s,r,a,o,l,h){const[c,d,u,p,g,m]=qt(t);if(0===d&&0===u){const f=a*c+g,b=Math.round(f),v=o*p+m,y=Math.round(v),w=(a+l)*c+g,x=Math.abs(Math.round(w)-b)||1,A=(o+h)*p+m,_=Math.abs(Math.round(A)-y)||1;return t.setTransform(Math.sign(c),0,0,Math.sign(p),b,y),t.drawImage(e,i,n,s,r,0,0,x,_),t.setTransform(c,d,u,p,g,m),[x,_]}if(0===c&&0===p){const f=o*u+g,b=Math.round(f),v=a*d+m,y=Math.round(v),w=(o+h)*u+g,x=Math.abs(Math.round(w)-b)||1,A=(a+l)*d+m,_=Math.abs(Math.round(A)-y)||1;return t.setTransform(0,Math.sign(d),Math.sign(u),0,b,y),t.drawImage(e,i,n,s,r,0,0,_,x),t.setTransform(c,d,u,p,g,m),[_,x]}t.drawImage(e,i,n,s,r,a,o,l,h);return[Math.hypot(c,d)*l,Math.hypot(u,p)*h]}class $i{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=S;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=N;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(t,e,i){i?.(this),this.clipBox=new Float32Array([0,0,t,e]),this.minMax=ji.slice()}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t}getPathBoundingBox(t=_i,e=null){const i=this.minMax.slice();if(t===Si){e||ht("Stroke bounding box must include transform."),Ct.singularValueDecompose2dScale(e,Ui);const t=Ui[0]*this.lineWidth/2,n=Ui[1]*this.lineWidth/2;i[0]-=t,i[1]-=n,i[2]+=t,i[3]+=n}return i}updateClipFromPath(){const t=Ct.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(ji,0)}getClippedPathBoundingBox(t=_i,e=null){return Ct.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function Wi(t,e){if(e instanceof ImageData)return void t.putImageData(e,0,0);const i=e.height,n=e.width,s=i%Oi,r=(i-s)/Oi,a=0===s?r:r+1,o=t.createImageData(n,Oi);let l,h=0;const c=e.data,d=o.data;let u,p,g,m;if(e.kind===W.GRAYSCALE_1BPP){const e=c.byteLength,i=new Uint32Array(d.buffer,0,d.byteLength>>2),m=i.length,f=n+7>>3,b=4294967295,v=_t.isLittleEndian?4278190080:255;for(u=0;u<a;u++){for(g=u<r?Oi:s,l=0,p=0;p<g;p++){const t=e-h;let s=0;const r=t>f?n:8*t-7,a=-8&r;let o=0,d=0;for(;s<a;s+=8)d=c[h++],i[l++]=128&d?b:v,i[l++]=64&d?b:v,i[l++]=32&d?b:v,i[l++]=16&d?b:v,i[l++]=8&d?b:v,i[l++]=4&d?b:v,i[l++]=2&d?b:v,i[l++]=1&d?b:v;for(;s<r;s++)0===o&&(d=c[h++],o=128),i[l++]=d&o?b:v,o>>=1}for(;l<m;)i[l++]=0;t.putImageData(o,0,u*Oi)}}else if(e.kind===W.RGBA_32BPP){for(p=0,m=n*Oi*4,u=0;u<r;u++)d.set(c.subarray(h,h+m)),h+=m,t.putImageData(o,0,p),p+=Oi;u<a&&(m=n*s*4,d.set(c.subarray(h,h+m)),t.putImageData(o,0,p))}else{if(e.kind!==W.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=Oi,m=n*g,u=0;u<a;u++){for(u>=r&&(g=s,m=n*g),l=0,p=m;p--;)d[l++]=c[h++],d[l++]=c[h++],d[l++]=c[h++],d[l++]=255;t.putImageData(o,0,u*Oi)}}}function Vi(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,n=e.width,s=i%Oi,r=(i-s)/Oi,a=0===s?r:r+1,o=t.createImageData(n,Oi);let l=0;const h=e.data,c=o.data;for(let e=0;e<a;e++){const i=e<r?Oi:s;({srcPos:l}=Fi({src:h,srcPos:l,dest:c,width:n,height:i,nonBlackColor:0})),t.putImageData(o,0,e*Oi)}}function Gi(t,e){const i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const n of i)void 0!==t[n]&&(e[n]=t[n]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function qi(t){t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0);const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function Xi(t,e){if(e)return!0;Ct.singularValueDecompose2dScale(t,Ui);const i=Math.fround(Yt.pixelRatio*Bt.PDF_TO_CSS_UNITS);return Ui[0]<=i&&Ui[1]<=i}const Ki=["butt","round","square"],Yi=["miter","round","bevel"],Ji={},Qi={};class Zi{constructor(t,e,i,n,s,{optionalContentConfig:r,markedContentStack:a=null},o,l,h){this.ctx=t,this.current=new $i(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=i,this.canvasFactory=n,this.filterFactory=s,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=a||[],this.optionalContentConfig=r,this.cachedCanvases=new zi(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=h??null}getObject(t,e,i=null){return"string"==typeof e?(this.dependencyTracker?.recordNamedDependency(t,e),e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)):i}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:n=null}){const s=this.ctx.canvas.width,r=this.ctx.canvas.height,a=this.ctx.fillStyle;if(this.ctx.fillStyle=n||"#ffffff",this.ctx.fillRect(0,0,s,r),this.ctx.fillStyle=a,i){const t=this.cachedCanvases.getCanvas("transparent",s,r);this.compositeCtx=this.ctx,this.transparentCanvas=t.canvas,this.ctx=t.context,this.ctx.save(),this.ctx.transform(...qt(this.compositeCtx))}this.ctx.save(),qi(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=qt(this.ctx)}executeOperatorList(t,e,i,n,s){const r=t.argsArray,a=t.fnArray;let o=e||0;const l=r.length;if(l===o)return o;const h=l-o>10&&"function"==typeof i,c=h?Date.now()+15:0;let d=0;const u=this.commonObjs,p=this.objs;let g,m;for(;;){if(void 0!==n&&o===n.nextBreakPoint)return n.breakIt(o,i),o;if(!s||s(o))if(g=a[o],m=r[o]??null,g!==Q.dependency)null===m?this[g](o):this[g](o,...m);else for(const t of m){this.dependencyTracker?.recordNamedData(t,o);const e=t.startsWith("g_")?u:p;if(!e.has(t))return e.get(t,i),o}if(o++,o===l)return o;if(h&&++d>10){if(Date.now()>c)return i(),o;d=0}}}#yn(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#yn(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#wn()}#wn(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,n=t.height??t.displayHeight;let s,r,a=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=n,c="prescale1";for(;a>2&&l>1||o>2&&h>1;){let e=l,i=h;a>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),a/=l/e),o>2&&h>1&&(i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/i),s=this.cachedCanvases.getCanvas(c,e,i),r=s.context,r.clearRect(0,0,e,i),r.drawImage(t,0,0,l,h,0,0,e,i),t=s.canvas,l=e,h=i,c="prescale1"===c?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t,e){const i=this.ctx,{width:n,height:s}=e,r=this.current.fillColor,a=this.current.patternFill,o=qt(i);let l,h,c,d;if((e.bitmap||e.data)&&e.count>1){const i=e.bitmap||e.data.buffer;h=JSON.stringify(a?o:[o.slice(0,4),r]),l=this._cachedBitmapsMap.get(i),l||(l=new Map,this._cachedBitmapsMap.set(i,l));const n=l.get(h);if(n&&!a){const e=Math.round(Math.min(o[0],o[2])+o[4]),i=Math.round(Math.min(o[1],o[3])+o[5]);return this.dependencyTracker?.recordDependencies(t,Ai),{canvas:n,offsetX:e,offsetY:i}}c=n}c||(d=this.cachedCanvases.getCanvas("maskCanvas",n,s),Vi(d.context,e));let u=Ct.transform(o,[1/n,0,0,-1/s,0,0]);u=Ct.transform(u,[1,0,0,1,0,-s]);const p=ji.slice();Ct.axialAlignedBoundingBox([0,0,n,s],u,p);const[g,m,f,b]=p,v=Math.round(f-g)||1,y=Math.round(b-m)||1,w=this.cachedCanvases.getCanvas("fillCanvas",v,y),x=w.context,A=g,_=m;x.translate(-A,-_),x.transform(...u),c||(c=this._scaleImage(d.canvas,Xt(x)),c=c.img,l&&a&&l.set(h,c)),x.imageSmoothingEnabled=Xi(qt(x),e.interpolate),Hi(x,c,0,0,c.width,c.height,0,0,n,s),x.globalCompositeOperation="source-in";const S=Ct.transform(Xt(x),[1,0,0,1,-A,-_]);return x.fillStyle=a?r.getPattern(i,this,S,_i,t):r,x.fillRect(0,0,n,s),l&&!a&&(this.cachedCanvases.delete("fillCanvas"),l.set(h,w.canvas)),this.dependencyTracker?.recordDependencies(t,Ai),{canvas:w.canvas,offsetX:Math.round(A),offsetY:Math.round(_)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t),e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=Ki[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=Yi[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=e}setDash(t,e,i){this.dependencyTracker?.recordSimpleData("dash",t);const n=this.ctx;void 0!==n.setLineDash&&(n.setLineDash(e),n.lineDashOffset=i)}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[i,n]of e)switch(i){case"LW":this.setLineWidth(t,n);break;case"LC":this.setLineCap(t,n);break;case"LJ":this.setLineJoin(t,n);break;case"ML":this.setMiterLimit(t,n);break;case"D":this.setDash(t,n[0],n[1]);break;case"RI":this.setRenderingIntent(t,n);break;case"FL":this.setFlatness(t,n);break;case"Font":this.setFont(t,n[0],n[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=n;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=n;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=n;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=n?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(n)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const e=this.ctx.canvas.width,i=this.ctx.canvas.height,n="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(n,e,i);this.suspendedCtx=this.ctx;const r=this.ctx=s.context;r.setTransform(this.suspendedCtx.getTransform()),Gi(this.suspendedCtx,r),function(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,n,s,r,a){e.transform(t,i,n,s,r,a),this.__originalTransform(t,i,n,s,r,a)},t.setTransform=function(t,i,n,s,r,a){e.setTransform(t,i,n,s,r,a),this.__originalSetTransform(t,i,n,s,r,a)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,n,s,r,a){e.bezierCurveTo(t,i,n,s,r,a),this.__originalBezierCurveTo(t,i,n,s,r,a)},t.rect=function(t,i,n,s){e.rect(t,i,n,s),this.__originalRect(t,i,n,s)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(r,this.suspendedCtx),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Gi(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,n){const s=n[0],r=n[1],a=n[2]-s,o=n[3]-r;0!==a&&0!==o&&(this.genericComposeSMask(e.context,i,a,o,e.subtype,e.backdrop,e.transferMap,s,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,n,s,r,a,o,l,h,c){let d=t.canvas,u=o-h,p=l-c;if(r)if(u<0||p<0||u+i>d.width||p+n>d.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,n),e=t.context;e.drawImage(d,-u,-p),e.globalCompositeOperation="destination-atop",e.fillStyle=r,e.fillRect(0,0,i,n),e.globalCompositeOperation="source-over",d=t.canvas,u=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,n),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=r,t.fillRect(u,p,i,n),t.restore()}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===s&&a?e.filter=this.filterFactory.addAlphaFilter(a):"Luminosity"===s&&(e.filter=this.filterFactory.addLuminosityFilter(a));const g=new Path2D;g.rect(o,l,i,n),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(d,u,p,i,n,o,l,i,n),e.restore()}save(t){this.inSMaskMode&&Gi(this.ctx,this.suspendedCtx),this.ctx.save();const e=this.current;this.stateStack.push(e),this.current=e.clone(),this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t),0!==this.stateStack.length?(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&Gi(this.suspendedCtx,this.ctx),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,n,s,r,a){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(e,i,n,s,r,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,n){let[s]=i;if(!n)return s||=i[0]=new Path2D,void this[e](t,s);if(null!==this.dependencyTracker){const i=e===Q.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,n[0]-i,n[2]+i,n[1]-i,n[3]+i).recordDependencies(t,["transform"])}if(!(s instanceof Path2D)){const t=i[0]=new Path2D;for(let e=0,i=s.length;e<i;)switch(s[e++]){case Z:t.moveTo(s[e++],s[e++]);break;case tt:t.lineTo(s[e++],s[e++]);break;case et:t.bezierCurveTo(s[e++],s[e++],s[e++],s[e++],s[e++],s[e++]);break;case it:t.closePath();break;default:lt(`Unrecognized drawing path operator: ${s[e-1]}`)}s=t}Ct.axialAlignedBoundingBox(n,qt(this.ctx),this.current.minMax),this[e](t,s),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){const n=this.ctx,s=this.current.strokeColor;if(n.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof s&&s?.getPattern){const i=s.isModifyingCurrentTransform()?n.getTransform():null;if(n.save(),n.strokeStyle=s.getPattern(n,this,Xt(n),Si,t),i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i)),e=t}this.rescaleAndStroke(e,!1),n.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,fi),i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(Si,qt(this.ctx))),n.globalAlpha=this.current.fillAlpha}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){const n=this.ctx,s=this.current.fillColor;let r=!1;if(this.current.patternFill){const i=s.isModifyingCurrentTransform()?n.getTransform():null;if(this.dependencyTracker?.save(t),n.save(),n.fillStyle=s.getPattern(n,this,Xt(n),_i,t),i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i)),e=t}r=!0}const a=this.current.getClippedPathBoundingBox();this.contentVisible&&null!==a&&(this.pendingEOFill?(n.fill(e,"evenodd"),this.pendingEOFill=!1):n.fill(e)),this.dependencyTracker?.recordDependencies(t,bi),r&&(n.restore(),this.dependencyTracker?.restore(t)),i&&this.consumePath(t,e,a)}eoFill(t,e){this.pendingEOFill=!0,this.fill(t,e)}fillStroke(t,e){this.fill(t,e,!1),this.stroke(t,e,!1),this.consumePath(t,e)}eoFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){this.ctx.fill(e),this.dependencyTracker?.recordDependencies(t,yi).recordOperation(t)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Ji}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Qi}beginText(t){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,i=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;void 0!==e&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t),i.recordCloseMarker(t)}if(void 0!==e){const t=new Path2D,n=i.getTransform().invertSelf();for(const{transform:i,x:s,y:r,fontSize:a,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(n).translate(s,r).scale(a,-a));i.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-e}setFont(t,e,i){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);const n=this.commonObjs.get(e),s=this.current;if(!n)throw new Error(`Can't find font for ${e}`);if(s.fontMatrix=n.fontMatrix||S,0!==s.fontMatrix[0]&&0!==s.fontMatrix[3]||lt("Invalid font matrix for font "+e),i<0?(i=-i,s.fontDirection=-1):s.fontDirection=1,this.current.font=n,this.current.fontSize=i,n.isType3Font)return;const r=n.loadedName||"sans-serif",a=n.systemFontInfo?.css||`"${r}", ${n.fallbackName}`;let o="normal";n.black?o="900":n.bold&&(o="bold");const l=n.italic?"italic":"normal";let h=i;i<16?h=16:i>100&&(h=100),this.current.fontSizeScale=i/h,this.ctx.font=`${l} ${o} ${h}px ${a}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=e}moveText(t,e,i){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=i}setLeadingMoveText(t,e,i){this.setLeading(t,-i),this.moveText(t,e,i)}setTextMatrix(t,e){this.dependencyTracker?.recordSimpleData("textMatrix",t);const{current:i}=this;i.textMatrix=e,i.textMatrixScale=Math.hypot(e[0],e[1]),i.x=i.lineX=0,i.y=i.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#xn(t,e,i){const n=new Path2D;return n.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e)),n}paintChar(t,e,i,n,s,r){const a=this.ctx,o=this.current,l=o.font,h=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,d=h&H,u=!!(h&$),p=o.patternFill&&!l.missingFile,g=o.patternStroke&&!l.missingFile;let m;if((l.disableFontFace||u||p||g)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,e)),m&&(l.disableFontFace||p||g)){let e;if(a.save(),a.translate(i,n),a.scale(c,-c),this.dependencyTracker?.recordCharacterBBox(t,a,l),d===N||d===j)if(s){e=a.getTransform(),a.setTransform(...s);const t=this.#xn(m,e,s);a.fill(t)}else a.fill(m);if(d===U||d===j)if(r){e||=a.getTransform(),a.setTransform(...r);const{a:t,b:i,c:n,d:s}=e,o=Ct.inverseTransform(r),l=Ct.transform([t,i,n,s,0,0],o);Ct.singularValueDecompose2dScale(l,Ui),a.lineWidth*=Math.max(Ui[0],Ui[1])/c,a.stroke(this.#xn(m,e,r))}else a.lineWidth/=c,a.stroke(m);a.restore()}else d!==N&&d!==j||(a.fillText(e,i,n),this.dependencyTracker?.recordCharacterBBox(t,a,l,c,i,n,()=>a.measureText(e))),d!==U&&d!==j||(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,a,l,c,i,n,()=>a.measureText(e)).recordDependencies(t,fi),a.strokeText(e,i,n));if(u){(this.pendingTextPaths||=[]).push({transform:qt(a),x:i,y:n,fontSize:c,path:m}),this.dependencyTracker?.recordCharacterBBox(t,a,l,c,i,n)}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){i=!0;break}return pt(this,"isFontSubpixelAAEnabled",i)}showText(t,e){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,wi).resetBBox(t),this.current.textRenderingMode&$&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());const i=this.current,n=i.font;if(n.isType3Font)return this.showType3Text(t,e),void this.dependencyTracker?.recordShowTextOperation(t);const s=i.fontSize;if(0===s)return void this.dependencyTracker?.recordOperation(t);const r=this.ctx,a=i.fontSizeScale,o=i.charSpacing,l=i.wordSpacing,h=i.fontDirection,c=i.textHScale*h,d=e.length,u=n.vertical,p=u?1:-1,g=n.defaultVMetrics,m=s*i.fontMatrix[0],f=i.textRenderingMode===N&&!n.disableFontFace&&!i.patternFill;let b,v;if(r.save(),i.textMatrix&&r.transform(...i.textMatrix),r.translate(i.x,i.y+i.textRise),h>0?r.scale(c,-1):r.scale(c,1),i.patternFill){r.save();const e=i.fillColor.getPattern(r,this,Xt(r),_i,t);b=qt(r),r.restore(),r.fillStyle=e}if(i.patternStroke){r.save();const e=i.strokeColor.getPattern(r,this,Xt(r),Si,t);v=qt(r),r.restore(),r.strokeStyle=e}let y=i.lineWidth;const w=i.textMatrixScale;if(0===w||0===y){const t=i.textRenderingMode&H;t!==U&&t!==j||(y=this.getSinglePixelWidth())}else y/=w;if(1!==a&&(r.scale(a,a),y/=a),r.lineWidth=y,n.isInvalidPDFjsFont){const n=[];let s=0;for(const t of e)n.push(t.unicode),s+=t.width;const a=n.join("");if(r.fillText(a,0,0),null!==this.dependencyTracker){const e=r.measureText(a);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}return i.x+=s*m*c,r.restore(),void this.compose()}let x,A=0;for(x=0;x<d;++x){const i=e[x];if("number"==typeof i){A+=p*i*s/1e3;continue}let c=!1;const d=(i.isSpace?l:0)+o,y=i.fontChar,w=i.accent;let _,S,C,E=i.width;if(u){const t=i.vmetric||g,e=-(i.vmetric?t[1]:.5*E)*m,n=t[2]*m;E=t?-t[0]:E,_=e/a,S=(A+n)/a}else _=A/a,S=0;if(n.remeasure&&E>0){C=r.measureText(y);const t=1e3*C.width/s*a;if(E<t&&this.isFontSubpixelAAEnabled){const e=E/t;c=!0,r.save(),r.scale(e,1),_/=e}else E!==t&&(_+=(E-t)/2e3*s/a)}if(this.contentVisible&&(i.isInFont||n.missingFile))if(f&&!w)r.fillText(y,_,S),this.dependencyTracker?.recordCharacterBBox(t,r,C?{bbox:null}:n,s/a,_,S,()=>C??r.measureText(y));else if(this.paintChar(t,y,_,S,b,v),w){const e=_+s*w.offset.x/a,i=S-s*w.offset.y/a;this.paintChar(t,w.fontChar,e,i,b,v)}A+=u?E*m-d*h:E*m+d*h,c&&r.restore()}u?i.y-=A:i.x+=A*c,r.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(t)}showType3Text(t,e){const i=this.ctx,n=this.current,s=n.font,r=n.fontSize,a=n.fontDirection,o=s.vertical?1:-1,l=n.charSpacing,h=n.wordSpacing,c=n.textHScale*a,d=n.fontMatrix||S,u=e.length;let p,g,m,f;if(n.textRenderingMode===z||0===r)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,i.save(),n.textMatrix&&i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),i.scale(c,a);const b=this.dependencyTracker;for(this.dependencyTracker=b?new mi(b,t):null,p=0;p<u;++p){if(g=e[p],"number"==typeof g){f=o*g*r/1e3,this.ctx.translate(f,0),n.x+=f*c;continue}const t=(g.isSpace?h:0)+l,a=s.charProcOperatorList[g.operatorListId];a?this.contentVisible&&(this.save(),i.scale(r,r),i.transform(...d),this.executeOperatorList(a),this.restore()):lt(`Type3 character "${g.operatorListId}" is not available.`);const u=[g.width,0];Ct.applyTransform(u,d),m=u[0]*r+t,i.translate(m,0),n.x+=m*c}i.restore(),b&&(this.dependencyTracker=b)}setCharWidth(t,e,i){}setCharWidthAndBounds(t,e,i,n,s,r,a){const o=new Path2D;o.rect(n,s,r-n,a-s),this.ctx.clip(o),this.dependencyTracker?.recordBBox(t,this.ctx,n,r,s,a).recordClipBox(t,this.ctx,n,r,s,a),this.endPath(t)}getColorN_Pattern(t,e){let i;if("TilingPattern"===e[0]){const t=this.baseTransform||qt(this.ctx),n={createCanvasGraphics:(t,e)=>new Zi(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new mi(this.dependencyTracker,e,!0):null)};i=new Bi(e,this.ctx,n,t)}else i=this._getPattern(t,e[1],e[2]);return i}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,e),this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.current.fillColor=this.getColorN_Pattern(t,e),this.current.patternFill=!0}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=e,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=e,this.current.patternFill=!1}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e,i=null){let n;return this.cachedPatterns.has(e)?n=this.cachedPatterns.get(e):(n=function(t){switch(t[0]){case"RadialAxial":return new ki(t);case"Mesh":return new Pi(t);case"Dummy":return new Ii}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e)),this.cachedPatterns.set(e,n)),i&&(n.matrix=i),n}shadingFill(t,e){if(!this.contentVisible)return;const i=this.ctx;this.save(t);const n=this._getPattern(t,e);i.fillStyle=n.getPattern(i,this,Xt(i),Ci,t);const s=Xt(i);if(s){const{width:t,height:e}=i.canvas,n=ji.slice();Ct.axialAlignedBoundingBox([0,0,t,e],s,n);const[r,a,o,l]=n;this.ctx.fillRect(r,a,o-r,l-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,xi).recordDependencies(t,bi).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t)}beginInlineImage(){ht("Should not call beginInlineImage")}beginImageData(){ht("Should not call beginImageData")}paintFormXObjectBegin(t,e,i){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),e&&this.transform(t,...e),this.baseTransform=qt(this.ctx),i)){Ct.axialAlignedBoundingBox(i,this.baseTransform,this.current.minMax);const[e,n,s,r]=i,a=new Path2D;a.rect(e,n,s-e,r-n),this.ctx.clip(a),this.dependencyTracker?.recordClipBox(t,this.ctx,e,s,n,r),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,e){if(!this.contentVisible)return;this.save(t),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const i=this.ctx;e.isolated||ot("TODO: Support non-isolated groups."),e.knockout&<("Knockout groups not supported.");const n=qt(i);if(e.matrix&&i.transform(...e.matrix),!e.bbox)throw new Error("Bounding box is required.");let s=ji.slice();Ct.axialAlignedBoundingBox(e.bbox,qt(i),s);const r=[0,0,i.canvas.width,i.canvas.height];s=Ct.intersect(s,r)||[0,0,0,0];const a=Math.floor(s[0]),o=Math.floor(s[1]),l=Math.max(Math.ceil(s[2])-a,1),h=Math.max(Math.ceil(s[3])-o,1);this.current.startNewPathAndClipBox([0,0,l,h]);let c="groupAt"+this.groupLevel;e.smask&&(c+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(c,l,h),u=d.context;u.translate(-a,-o),u.transform(...n);let p=new Path2D;const[g,m,f,b]=e.bbox;if(p.rect(g,m,f-g,b-m),e.matrix){const t=new Path2D;t.addPath(p,new DOMMatrix(e.matrix)),p=t}u.clip(p),e.smask&&this.smaskStack.push({canvas:d.canvas,context:u,offsetX:a,offsetY:o,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}),e.smask&&!this.dependencyTracker||(i.setTransform(1,0,0,1,0,0),i.translate(a,o),i.save()),Gi(i,u),this.ctx=u,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(i),this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const i=this.ctx,n=this.groupStack.pop();if(this.ctx=n,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),e.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&this.ctx.restore();else{this.ctx.restore();const e=qt(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...e);const n=ji.slice();Ct.axialAlignedBoundingBox([0,0,i.canvas.width,i.canvas.height],e,n),this.ctx.drawImage(i.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,i,n,s,r){if(this.#yn(),qi(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),i){const s=i[2]-i[0],a=i[3]-i[1];if(r&&this.annotationCanvasMap){(n=n.slice())[4]-=i[0],n[5]-=i[1],(i=i.slice())[0]=i[1]=0,i[2]=s,i[3]=a,Ct.singularValueDecompose2dScale(qt(this.ctx),Ui);const{viewportScale:t}=this,r=Math.ceil(s*this.outputScaleX*t),o=Math.ceil(a*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(r,o);const{canvas:l,context:h}=this.annotationCanvas;this.annotationCanvasMap.set(e,l),this.annotationCanvas.savedCtx=this.ctx,this.ctx=h,this.ctx.save(),this.ctx.setTransform(Ui[0],0,0,-Ui[1],0,a*Ui[1]),qi(this.ctx)}else{qi(this.ctx),this.endPath(t);const e=new Path2D;e.rect(i[0],i[1],s,a),this.ctx.clip(e)}}this.current=new $i(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(t,...n),this.transform(t,...s)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#wn(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const i=e.count;(e=this.getObject(t,e.data,e)).count=i;const n=this.ctx,s=this._createMaskCanvas(t,e),r=s.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(r,s.offsetX,s.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,s.offsetX,s.offsetX+r.width,s.offsetY,s.offsetY+r.height).recordOperation(t),n.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i,n=0,s=0,r,a){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.ctx;o.save();const l=qt(o);o.transform(i,n,s,r,0,0);const h=this._createMaskCanvas(t,e);o.setTransform(1,0,0,1,h.offsetX-l[4],h.offsetY-l[5]),this.dependencyTracker?.resetBBox(t);for(let e=0,c=a.length;e<c;e+=2){const c=Ct.transform(l,[i,n,s,r,a[e],a[e+1]]);o.drawImage(h.canvas,c[4],c[5]),this.dependencyTracker?.recordBBox(t,this.ctx,c[4],c[4]+h.canvas.width,c[5],c[5]+h.canvas.height)}o.restore(),this.compose(),this.dependencyTracker?.recordOperation(t)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.ctx,n=this.current.fillColor,s=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,Ai);for(const r of e){const{data:e,width:a,height:o,transform:l}=r,h=this.cachedCanvases.getCanvas("maskCanvas",a,o),c=h.context;c.save();Vi(c,this.getObject(t,e,r)),c.globalCompositeOperation="source-in",c.fillStyle=s?n.getPattern(c,this,Xt(i),_i,t):n,c.fillRect(0,0,a,o),c.restore(),i.save(),i.transform(...l),i.scale(1,-1),Hi(i,h.canvas,0,0,a,o,0,-1,1,1),this.dependencyTracker?.recordBBox(t,i,0,a,0,o),i.restore()}this.compose(),this.dependencyTracker?.recordOperation(t)}paintImageXObject(t,e){if(!this.contentVisible)return;const i=this.getObject(t,e);i?this.paintInlineImageXObject(t,i):lt("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,i,n,s){if(!this.contentVisible)return;const r=this.getObject(t,e);if(!r)return void lt("Dependent image isn't ready yet");const a=r.width,o=r.height,l=[];for(let t=0,e=s.length;t<e;t+=2)l.push({transform:[i,0,0,n,s[t],s[t+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(t,r,l)}applyTransferMapsToCanvas(t){return"none"!==this.current.transferMaps&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return t.bitmap;const{bitmap:e,width:i,height:n}=t,s=this.cachedCanvases.getCanvas("inlineImage",i,n),r=s.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",s.canvas}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const i=e.width,n=e.height,s=this.ctx;this.save(t);const{filter:r}=s;let a;if("none"!==r&&""!==r&&(s.filter="none"),s.scale(1/i,-1/n),e.bitmap)a=this.applyTransferMapsToBitmap(e);else if("function"==typeof HTMLElement&&e instanceof HTMLElement||!e.data)a=e;else{const t=this.cachedCanvases.getCanvas("inlineImage",i,n).context;Wi(t,e),a=this.applyTransferMapsToCanvas(t)}const o=this._scaleImage(a,Xt(s));s.imageSmoothingEnabled=Xi(qt(s),e.interpolate),this.dependencyTracker?.resetBBox(t).recordBBox(t,s,0,i,-n,0).recordDependencies(t,vi).recordOperation(t),Hi(s,o.img,0,0,o.paintWidth,o.paintHeight,0,-n,i,n),this.compose(),this.restore(t)}paintInlineImageXObjectGroup(t,e,i){if(!this.contentVisible)return;const n=this.ctx;let s;if(e.bitmap)s=e.bitmap;else{const t=e.width,i=e.height,n=this.cachedCanvases.getCanvas("inlineImage",t,i).context;Wi(n,e),s=this.applyTransferMapsToCanvas(n)}this.dependencyTracker?.resetBBox(t);for(const e of i)n.save(),n.transform(...e.transform),n.scale(1,-1),Hi(n,s,e.x,e.y,e.w,e.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,n,0,1,-1,0),n.restore();this.dependencyTracker?.recordOperation(t),this.compose()}paintSolidColorImageMask(t){this.contentVisible&&(this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,bi).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t,e){}markPointProps(t,e,i){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,i){this.dependencyTracker?.beginMarkedContent(t),"OC"===e?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(i)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,i){const n=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(i);const s=this.ctx;this.pendingClip?(n||(this.pendingClip===Qi?s.clip(e,"evenodd"):s.clip(e)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)):this.dependencyTracker?.recordOperation(t),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=qt(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),i=Math.hypot(t[0],t[2]),n=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,n)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:i,c:n,d:s}=this.ctx.getTransform();let r,a;if(0===i&&0===n){const i=Math.abs(e),n=Math.abs(s);if(i===n)if(0===t)r=a=1/i;else{const e=i*t;r=a=e<1?1/e:1}else if(0===t)r=1/i,a=1/n;else{const e=i*t,s=n*t;r=e<1?1/e:1,a=s<1?1/s:1}}else{const o=Math.abs(e*s-i*n),l=Math.hypot(e,i),h=Math.hypot(n,s);if(0===t)r=h/o,a=l/o;else{const e=t*o;r=h>e?h/e:1,a=l>e?l/e:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:n}}=this,[s,r]=this.getScaleForStroking();if(s===r)return i.lineWidth=(n||1)*s,void i.stroke(t);const a=i.getLineDash();e&&i.save(),i.scale(s,r),Ni.a=1/s,Ni.d=1/r;const o=new Path2D;if(o.addPath(t,Ni),a.length>0){const t=Math.max(s,r);i.setLineDash(a.map(e=>e/t)),i.lineDashOffset/=t}i.lineWidth=n||1,i.stroke(o),e&&i.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in Q)void 0!==Zi.prototype[t]&&(Zi.prototype[Q[t]]=Zi.prototype[t]);class tn{#An;#_n;#Sn;static strings=["fontFamily","fontWeight","italicAngle"];static write(t){const e=new TextEncoder,i={};let n=0;for(const s of tn.strings){const r=e.encode(t[s]);i[s]=r,n+=4+r.length}const s=new ArrayBuffer(n),r=new Uint8Array(s),a=new DataView(s);let o=0;for(const t of tn.strings){const e=i[t],n=e.length;a.setUint32(o,n),r.set(e,o+4),o+=4+n}return ct(o===s.byteLength,"CssFontInfo.write: Buffer overflow"),s}constructor(t){this.#An=t,this.#_n=new DataView(this.#An),this.#Sn=new TextDecoder}#Cn(t){ct(t<tn.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#_n.getUint32(e)+4;const i=this.#_n.getUint32(e);return this.#Sn.decode(new Uint8Array(this.#An,e+4,i))}get fontFamily(){return this.#Cn(0)}get fontWeight(){return this.#Cn(1)}get italicAngle(){return this.#Cn(2)}}class en{#An;#_n;#Sn;static strings=["css","loadedName","baseFontName","src"];static write(t){const e=new TextEncoder,i={};let n=0;for(const s of en.strings){const r=e.encode(t[s]);i[s]=r,n+=4+r.length}n+=4;let s,r,a=1+n;t.style&&(s=e.encode(t.style.style),r=e.encode(t.style.weight),a+=4+s.length+4+r.length);const o=new ArrayBuffer(a),l=new Uint8Array(o),h=new DataView(o);let c=0;h.setUint8(c++,t.guessFallback?1:0),h.setUint32(c,0),c+=4,n=0;for(const t of en.strings){const e=i[t],s=e.length;n+=4+s,h.setUint32(c,s),l.set(e,c+4),c+=4+s}return h.setUint32(c-n-4,n),t.style&&(h.setUint32(c,s.length),l.set(s,c+4),c+=4+s.length,h.setUint32(c,r.length),l.set(r,c+4),c+=4+r.length),ct(c<=o.byteLength,"SubstitionInfo.write: Buffer overflow"),o.transferToFixedLength(c)}constructor(t){this.#An=t,this.#_n=new DataView(this.#An),this.#Sn=new TextDecoder}get guessFallback(){return 0!==this.#_n.getUint8(0)}#Cn(t){ct(t<en.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#_n.getUint32(e)+4;const i=this.#_n.getUint32(e);return this.#Sn.decode(new Uint8Array(this.#An,e+4,i))}get css(){return this.#Cn(0)}get loadedName(){return this.#Cn(1)}get baseFontName(){return this.#Cn(2)}get src(){return this.#Cn(3)}get style(){let t=1;t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t),i=this.#Sn.decode(new Uint8Array(this.#An,t+4,e));t+=4+e;const n=this.#_n.getUint32(t);return{style:i,weight:this.#Sn.decode(new Uint8Array(this.#An,t+4,n))}}}class nn{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static#En=Math.ceil(2*this.bools.length/8);static#Tn=this.#En+8*this.numbers.length;static#kn=this.#Tn+1+8;static#Mn=this.#kn+1+48;static#Dn=this.#Mn+1+6;#An;#Sn;#_n;constructor({data:t,extra:e}){this.#An=t,this.#Sn=new TextDecoder,this.#_n=new DataView(this.#An),e&&Object.assign(this,e)}#Pn(t){ct(t<nn.bools.length,"Invalid boolean index");const e=Math.floor(t/4),i=2*t%8,n=this.#_n.getUint8(e)>>i&3;return 0===n?void 0:2===n}get black(){return this.#Pn(0)}get bold(){return this.#Pn(1)}get disableFontFace(){return this.#Pn(2)}get fontExtraProperties(){return this.#Pn(3)}get isInvalidPDFjsFont(){return this.#Pn(4)}get isType3Font(){return this.#Pn(5)}get italic(){return this.#Pn(6)}get missingFile(){return this.#Pn(7)}get remeasure(){return this.#Pn(8)}get vertical(){return this.#Pn(9)}#In(t){return ct(t<nn.numbers.length,"Invalid number index"),this.#_n.getFloat64(nn.#En+8*t)}get ascent(){return this.#In(0)}get defaultWidth(){return this.#In(1)}get descent(){return this.#In(2)}get bbox(){let t=nn.#Tn;if(0===this.#_n.getUint8(t))return;t+=1;const e=[];for(let i=0;i<4;i++)e.push(this.#_n.getInt16(t,!0)),t+=2;return e}get fontMatrix(){let t=nn.#kn;if(0===this.#_n.getUint8(t))return;t+=1;const e=[];for(let i=0;i<6;i++)e.push(this.#_n.getFloat64(t,!0)),t+=8;return e}get defaultVMetrics(){let t=nn.#Mn;if(0===this.#_n.getUint8(t))return;t+=1;const e=[];for(let i=0;i<3;i++)e.push(this.#_n.getInt16(t,!0)),t+=2;return e}#Cn(t){ct(t<nn.strings.length,"Invalid string index");let e=nn.#Dn+4;for(let i=0;i<t;i++)e+=this.#_n.getUint32(e)+4;const i=this.#_n.getUint32(e),n=new Uint8Array(i);return n.set(new Uint8Array(this.#An,e+4,i)),this.#Sn.decode(n)}get fallbackName(){return this.#Cn(0)}get loadedName(){return this.#Cn(1)}get mimetype(){return this.#Cn(2)}get name(){return this.#Cn(3)}get data(){let t=nn.#Dn;t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t);if(0!==e)return new Uint8Array(this.#An,t+4,e)}clearData(){let t=nn.#Dn;t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t);new Uint8Array(this.#An,t+4,e).fill(0),this.#_n.setUint32(t,0)}get cssFontInfo(){let t=nn.#Dn;t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);return i.set(new Uint8Array(this.#An,t+4,e)),new tn(i.buffer)}get systemFontInfo(){let t=nn.#Dn;t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);return i.set(new Uint8Array(this.#An,t+4,e)),new en(i.buffer)}static write(t){const e=t.systemFontInfo?en.write(t.systemFontInfo):null,i=t.cssFontInfo?tn.write(t.cssFontInfo):null,n=new TextEncoder,s={};let r=0;for(const e of nn.strings)s[e]=n.encode(t[e]),r+=4+s[e].length;const a=nn.#Dn+4+r+4+(e?e.byteLength:0)+4+(i?i.byteLength:0)+4+(t.data?t.data.length:0),o=new ArrayBuffer(a),l=new Uint8Array(o),h=new DataView(o);let c=0;const d=nn.bools.length;let u=0,p=0;for(let e=0;e<d;e++){const i=t[nn.bools[e]];u|=(void 0===i?0:i?2:1)<<p,p+=2,8!==p&&e!==d-1||(h.setUint8(c++,u),u=0,p=0)}ct(c===nn.#En,"FontInfo.write: Boolean properties offset mismatch");for(const e of nn.numbers)h.setFloat64(c,t[e]),c+=8;if(ct(c===nn.#Tn,"FontInfo.write: Number properties offset mismatch"),t.bbox){h.setUint8(c++,4);for(const e of t.bbox)h.setInt16(c,e,!0),c+=2}else h.setUint8(c++,0),c+=8;if(ct(c===nn.#kn,"FontInfo.write: BBox properties offset mismatch"),t.fontMatrix){h.setUint8(c++,6);for(const e of t.fontMatrix)h.setFloat64(c,e,!0),c+=8}else h.setUint8(c++,0),c+=48;if(ct(c===nn.#Mn,"FontInfo.write: FontMatrix properties offset mismatch"),t.defaultVMetrics){h.setUint8(c++,1);for(const e of t.defaultVMetrics)h.setInt16(c,e,!0),c+=2}else h.setUint8(c++,0),c+=6;ct(c===nn.#Dn,"FontInfo.write: DefaultVMetrics properties offset mismatch"),h.setUint32(nn.#Dn,0),c+=4;for(const t of nn.strings){const e=s[t],i=e.length;h.setUint32(c,i),l.set(e,c+4),c+=4+i}if(h.setUint32(nn.#Dn,c-nn.#Dn-4),e){const t=e.byteLength;h.setUint32(c,t),ct(c+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at systemFontInfo"),l.set(new Uint8Array(e),c+4),c+=4+t}else h.setUint32(c,0),c+=4;if(i){const t=i.byteLength;h.setUint32(c,t),ct(c+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at cssFontInfo"),l.set(new Uint8Array(i),c+4),c+=4+t}else h.setUint32(c,0),c+=4;return void 0===t.data?(h.setUint32(c,0),c+=4):(h.setUint32(c,t.data.length),l.set(t.data,c+4),c+=4+t.data.length),ct(c<=o.byteLength,"FontInfo.write: Buffer overflow"),o.transferToFixedLength(c)}}class sn{static#Rn=null;static#Ln="";static get workerPort(){return this.#Rn}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Rn=t}static get workerSrc(){return this.#Ln}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Ln=t}}class rn{#Bn;#Fn;constructor({parsedData:t,rawData:e}){this.#Bn=t,this.#Fn=e}getRaw(){return this.#Fn}get(t){return this.#Bn.get(t)??null}[Symbol.iterator](){return this.#Bn.entries()}}const an=Symbol("INTERNAL");class on{#On=!1;#Nn=!1;#Un=!1;#jn=!0;constructor(t,{name:e,intent:i,usage:n,rbGroups:s}){this.#On=!!(t&T),this.#Nn=!!(t&k),this.name=e,this.intent=i,this.usage=n,this.rbGroups=s}get visible(){if(this.#Un)return this.#jn;if(!this.#jn)return!1;const{print:t,view:e}=this.usage;return this.#On?"OFF"!==e?.viewState:!this.#Nn||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==an&&ht("Internal method `_setVisible` called."),this.#Un=i,this.#jn=e}}class ln{#zn=null;#Hn=new Map;#$n=null;#Wn=null;constructor(t,e=T){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Wn=t.order;for(const i of t.groups)this.#Hn.set(i.id,new on(e,i));if("OFF"===t.baseState)for(const t of this.#Hn.values())t._setVisible(an,!1);for(const e of t.on)this.#Hn.get(e)._setVisible(an,!0);for(const e of t.off)this.#Hn.get(e)._setVisible(an,!1);this.#$n=this.getHash()}}#Vn(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let n=1;n<e;n++){const e=t[n];let s;if(Array.isArray(e))s=this.#Vn(e);else{if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;s=this.#Hn.get(e).visible}switch(i){case"And":if(!s)return!1;break;case"Or":if(s)return!0;break;case"Not":return!s;default:return!0}}return"And"===i}isVisible(t){if(0===this.#Hn.size)return!0;if(!t)return ot("Optional content group not defined."),!0;if("OCG"===t.type)return this.#Hn.has(t.id)?this.#Hn.get(t.id).visible:(lt(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#Vn(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;if(this.#Hn.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;if(!this.#Hn.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;if(!this.#Hn.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;if(this.#Hn.get(e).visible)return!1}return!0}return lt(`Unknown optional content policy ${t.policy}.`),!0}return lt(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,i=!0){const n=this.#Hn.get(t);if(n){if(i&&e&&n.rbGroups.length)for(const e of n.rbGroups)for(const i of e)i!==t&&this.#Hn.get(i)?._setVisible(an,!1,!0);n._setVisible(an,!!e,!0),this.#zn=null}else lt(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(const n of t){switch(n){case"ON":case"OFF":case"Toggle":i=n;continue}const t=this.#Hn.get(n);if(t)switch(i){case"ON":this.setVisibility(n,!0,e);break;case"OFF":this.setVisibility(n,!1,e);break;case"Toggle":this.setVisibility(n,!t.visible,e)}}this.#zn=null}get hasInitialVisibility(){return null===this.#$n||this.getHash()===this.#$n}getOrder(){return this.#Hn.size?this.#Wn?this.#Wn.slice():[...this.#Hn.keys()]:null}getGroup(t){return this.#Hn.get(t)||null}getHash(){if(null!==this.#zn)return this.#zn;const t=new Ae;for(const[e,i]of this.#Hn)t.update(`${e}:${i.visible}`);return this.#zn=t.hexdigest()}[Symbol.iterator](){return this.#Hn.entries()}}class hn{constructor(t,{disableRange:e=!1,disableStream:i=!1}){ct(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:n,initialData:s,progressiveDone:r,contentDispositionFilename:a}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=a,s?.length>0){const t=s instanceof Uint8Array&&s.byteLength===s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!i,this._isRangeSupported=!e,this._contentLength=n,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((t,e)=>{this._onReceiveData({begin:t,chunk:e})}),t.addProgressListener((t,e)=>{this._onProgress({loaded:t,total:e})}),t.addProgressiveReadListener(t=>{this._onReceiveData({chunk:t})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{ct(this._rangeReaders.some(function(e){return e._begin===t&&(e._enqueue(i),!0)}),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){ct(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new cn(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new dn(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class cn{constructor(t,e,i=!1,n=null){this._stream=t,this._done=i||!1,this._filename=jt(n)?n:null,this._queuedChunks=e||[],this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class dn{constructor(t,e,i){this._stream=t,this._begin=e,this._end=i,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function un(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const n=e[t];void 0!==n&&i.append(t,n)}return i}function pn(t){return URL.parse(t)?.origin??null}function gn({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:n}){const s={allowRangeRequests:!1,suggestedLength:void 0},r=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(r))return s;if(s.suggestedLength=r,r<=2*i)return s;if(n||!e)return s;if("bytes"!==t.get("Accept-Ranges"))return s;return"identity"!==(t.get("Content-Encoding")||"identity")||(s.allowRangeRequests=!0),s}function mn(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=n("filename\\*","i").exec(t);if(i){i=i[1];let t=a(i);return t=unescape(t),t=o(t),t=l(t),r(t)}if(i=function(t){const e=[];let i;const s=n("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,n,s]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[n,s]}const r=[];for(let t=0;t<e.length&&t in e;++t){let[i,n]=e[t];n=a(n),i&&(n=unescape(n),0===t&&(n=o(n))),r.push(n)}return r.join("")}(t),i)return r(l(i));if(i=n("filename","i").exec(t),i){i=i[1];let t=a(i);return t=l(t),r(t)}function n(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function s(t,i){if(t){if(!/^[\x00-\xFF]+$/.test(i))return i;try{const n=new TextDecoder(t,{fatal:!0}),s=At(i);i=n.decode(s),e=!1}catch{}}return i}function r(t){return e&&/[\x80-\xff]/.test(t)&&(t=s("utf-8",t),e&&(t=s("iso-8859-1",t))),t}function a(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const i=e[t].indexOf('"');-1!==i&&(e[t]=e[t].slice(0,i),e.length=t+1),e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function o(t){const e=t.indexOf("'");return-1===e?t:s(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function l(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(t,e,i,n){if("q"===i||"Q"===i)return s(e,n=(n=n.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{n=atob(n)}catch{}return s(e,n)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(jt(t))return t}return null}function fn(t,e){return new vt(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t,404===t||0===t&&e.startsWith("file:"))}function bn(t){return 200===t||206===t}function vn(t,e,i){return{method:"GET",headers:t,signal:i.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function yn(t){return t instanceof Uint8Array?t.buffer:t instanceof ArrayBuffer?t:(lt(`getArrayBuffer - unexpected data format: ${t}`),new Uint8Array(t).buffer)}class wn{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=un(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return ct(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new xn(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new An(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class xn{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const i=new Headers(t.headers),n=e.url;fetch(n,vn(i,this._withCredentials,this._abortController)).then(e=>{if(t._responseOrigin=pn(e.url),!bn(e.status))throw fn(e.status,n);this._reader=e.body.getReader(),this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:s,suggestedLength:r}=gn({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=r||this._contentLength,this._filename=mn(i),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new wt("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:yn(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class An{constructor(t,e,i){this._stream=t,this._reader=null,this._loaded=0;const n=t.source;this._withCredentials=n.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!n.disableStream,this._abortController=new AbortController;const s=new Headers(t.headers);s.append("Range",`bytes=${e}-${i-1}`);const r=n.url;fetch(r,vn(s,this._withCredentials,this._abortController)).then(e=>{const i=pn(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!bn(e.status))throw fn(e.status,r);this._readCapability.resolve(),this._reader=e.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:yn(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class _n{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=un(this.isHttp,e),this.withCredentials=i||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,n=this.pendingRequests[i]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),n.expectedStatus=206):n.expectedStatus=200,e.responseType="arraybuffer",ct(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,i),e.onprogress=this.onProgress.bind(this,i),n.onHeadersReceived=t.onHeadersReceived,n.onDone=t.onDone,n.onError=t.onError,n.onProgress=t.onProgress,e.send(null),i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const n=i.xhr;if(n.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==n.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===n.status&&this.isHttp)return void i.onError(n.status);const s=n.status||200;if(!(200===s&&206===i.expectedStatus)&&s!==i.expectedStatus)return void i.onError(n.status);const r=function(t){const e=t.response;return"string"!=typeof e?e:At(e).buffer}(n);if(206===s){const t=n.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);e?i.onDone({begin:parseInt(e[1],10),chunk:r}):(lt('Missing or invalid "Content-Range" header.'),i.onError(0))}else r?i.onDone({begin:0,chunk:r}):i.onError(n.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Sn{constructor(t){this._source=t,this._manager=new _n(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return ct(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Cn(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const i=new En(this._manager,t,e);return i.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Cn{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=pn(e.responseURL);const i=e.getAllResponseHeaders(),n=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{allowRangeRequests:s,suggestedLength:r}=gn({responseHeaders:n,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});s&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=mn(n),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);if(this._done=!0,!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=fn(t,this._url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class En{constructor(t,e,i){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){const t=pn(this._manager.getRequestXhr(this._requestId)?.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError??=fn(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const Tn=/^[a-z][a-z0-9\-+.]+:/i;class kn{constructor(t){this.source=t,this.url=function(t){if(Tn.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url),ct("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return ct(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Mn(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new Dn(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Mn{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then(t=>{this._contentLength=t.size,this._setReadableStream(i.createReadStream(this._url)),this._headersCapability.resolve()},t=>{"ENOENT"===t.code&&(t=fn(0,this._url.href)),this._storedError=t,this._headersCapability.reject(t)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",t=>{this._error(t)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new wt("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Dn{constructor(t,e,i){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const n=t.source;this._isStreamingSupported=!n.disableStream;const s=process.getBuiltinModule("fs");this._setReadableStream(s.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",t=>{this._error(t)}),this._storedError&&this._readableStream.destroy(this._storedError)}}const Pn=Symbol("INITIAL_DATA");class In{#Gn=Object.create(null);#qn(t){return this.#Gn[t]||={...Promise.withResolvers(),data:Pn}}get(t,e=null){if(e){const i=this.#qn(t);return i.promise.then(()=>e(i.data)),null}const i=this.#Gn[t];if(!i||i.data===Pn)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Gn[t];return!!e&&e.data!==Pn}delete(t){const e=this.#Gn[t];return!(!e||e.data===Pn)&&(delete this.#Gn[t],!0)}resolve(t,e=null){const i=this.#qn(t);i.data=e,i.resolve()}clear(){for(const t in this.#Gn){const{data:e}=this.#Gn[t];e?.bitmap?.close()}this.#Gn=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Gn){const{data:e}=this.#Gn[t];e!==Pn&&(yield[t,e])}}}class Rn{#Xn=Promise.withResolvers();#xt=null;#Kn=!1;#Yn=!!globalThis.FontInspector?.enabled;#Jn=null;#Qn=null;#Zn=0;#ts=0;#es=null;#is=null;#ns=0;#ss=0;#rs=Object.create(null);#as=[];#os=null;#ls=[];#hs=new WeakMap;#cs=null;static#ds=new Map;static#us=new Map;static#ps=new WeakMap;static#gs=null;static#ms=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#os=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#os=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#xt=this.#is=e,this.#ss=i.scale*Yt.pixelRatio,this.#ns=i.rotation,this.#Qn={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:s,pageX:r,pageY:a}=i.rawDims;this.#cs=[1,0,0,-1,-r,a+s],this.#ts=n,this.#Zn=s,Rn.#fs(),Kt(e,i),this.#Xn.promise.finally(()=>{Rn.#ms.delete(this),this.#Qn=null,this.#rs=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=_t.platform;return pt(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const t=()=>{this.#es.read().then(({value:e,done:i})=>{i?this.#Xn.resolve():(this.#Jn??=e.lang,Object.assign(this.#rs,e.styles),this.#bs(e.items),t())},this.#Xn.reject)};return this.#es=this.#os.getReader(),Rn.#ms.add(this),t(),this.#Xn.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*Yt.pixelRatio,n=t.rotation;if(n!==this.#ns&&(e?.(),this.#ns=n,Kt(this.#is,{rotation:n})),i!==this.#ss){e?.(),this.#ss=i;const t={div:null,properties:null,ctx:Rn.#vs(this.#Jn)};for(const e of this.#ls)t.properties=this.#hs.get(e),t.div=e,this.#ys(t)}}cancel(){const t=new wt("TextLayer task cancelled.");this.#es?.cancel(t).catch(()=>{}),this.#es=null,this.#Xn.reject(t)}get textDivs(){return this.#ls}get textContentItemsStr(){return this.#as}#bs(t){if(this.#Kn)return;this.#Qn.ctx??=Rn.#vs(this.#Jn);const e=this.#ls,i=this.#as;for(const n of t){if(e.length>1e5)return lt("Ignoring additional textDivs for performance reasons."),void(this.#Kn=!0);if(void 0!==n.str)i.push(n.str),this.#ws(n);else if("beginMarkedContentProps"===n.type||"beginMarkedContent"===n.type){const t=this.#xt;this.#xt=document.createElement("span"),this.#xt.classList.add("markedContent"),n.id&&this.#xt.setAttribute("id",`${n.id}`),t.append(this.#xt)}else"endMarkedContent"===n.type&&(this.#xt=this.#xt.parentNode)}}#ws(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ls.push(e);const n=Ct.transform(this.#cs,t.transform);let s=Math.atan2(n[1],n[0]);const r=this.#rs[t.fontName];r.vertical&&(s+=Math.PI/2);let a=this.#Yn&&r.fontSubstitution||r.fontFamily;a=Rn.fontFamilyMap.get(a)||a;const o=Math.hypot(n[2],n[3]),l=o*Rn.#xs(a,r,this.#Jn);let h,c;0===s?(h=n[4],c=n[5]-l):(h=n[4]+l*Math.sin(s),c=n[5]-l*Math.cos(s));const d="calc(var(--total-scale-factor) *",u=e.style;this.#xt===this.#is?(u.left=`${(100*h/this.#ts).toFixed(2)}%`,u.top=`${(100*c/this.#Zn).toFixed(2)}%`):(u.left=`${d}${h.toFixed(2)}px)`,u.top=`${d}${c.toFixed(2)}px)`),u.fontSize=`${d}${(Rn.#gs*o).toFixed(2)}px)`,u.fontFamily=a,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#Yn&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),0!==s&&(i.angle=s*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}if(p&&(i.canvasWidth=r.vertical?t.height:t.width),this.#hs.set(e,i),this.#Qn.div=e,this.#Qn.properties=i,this.#ys(this.#Qn),i.hasText&&this.#xt.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#xt.append(t)}}#ys(t){const{div:e,properties:i,ctx:n}=t,{style:s}=e;let r="";if(Rn.#gs>1&&(r=`scale(${1/Rn.#gs})`),0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=s,{canvasWidth:a,fontSize:o}=i;Rn.#As(n,o*this.#ss,t);const{width:l}=n.measureText(e.textContent);l>0&&(r=`scaleX(${a*this.#ss/l}) ${r}`)}0!==i.angle&&(r=`rotate(${i.angle}deg) ${r}`),r.length>0&&(s.transform=r)}static cleanup(){if(!(this.#ms.size>0)){this.#ds.clear();for(const{canvas:t}of this.#us.values())t.remove();this.#us.clear()}}static#vs(t=null){let e=this.#us.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#us.set(t,e),this.#ps.set(e,{size:0,family:""})}return e}static#As(t,e,i){const n=this.#ps.get(t);e===n.size&&i===n.family||(t.font=`${e}px ${i}`,n.size=e,n.family=i)}static#fs(){if(null!==this.#gs)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#gs=t.getBoundingClientRect().height,t.remove()}static#xs(t,e,i){const n=this.#ds.get(t);if(n)return n;const s=this.#vs(i);s.canvas.width=s.canvas.height=30,this.#As(s,30,t);const r=s.measureText(""),a=r.fontBoundingBoxAscent,o=Math.abs(r.fontBoundingBoxDescent);s.canvas.width=s.canvas.height=0;let l=.8;return a?l=a/(a+o):(_t.platform.isFirefox&<("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)),this.#ds.set(t,l),l}}function Ln(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new Bn,{docId:i}=e,n=t.url?function(t){if(t instanceof URL)return t.href;if("string"==typeof t){if(_)return t;const e=URL.parse(t,window.location);if(e)return e.href}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,s=t.data?function(t){if(_&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return At(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,a=!0===t.withCredentials,o=t.password??null,l=t.range instanceof Fn?t.range:null,h=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let c=t.worker instanceof Un?t.worker:null;const d=t.verbosity,u="string"!=typeof t.docBaseUrl||Ut(t.docBaseUrl)?null:t.docBaseUrl,p=ke(t.cMapUrl),g=!1!==t.cMapPacked,m=t.CMapReaderFactory||(_?si:Xe),f=ke(t.iccUrl),b=ke(t.standardFontDataUrl),v=t.StandardFontDataFactory||(_?ri:Qe),y=ke(t.wasmUrl),w=t.WasmFactory||(_?ai:ti),x=!0!==t.stopAtErrors,A=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,S=!1!==t.isEvalSupported,C="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!_,E="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!_&&(_t.platform.isFirefox||!globalThis.chrome),T=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,k="boolean"==typeof t.disableFontFace?t.disableFontFace:_,M=!0===t.fontExtraProperties,D=!0===t.enableXfa,P=t.ownerDocument||globalThis.document,I=!0===t.disableRange,R=!0===t.disableStream,L=!0===t.disableAutoFetch,B=!0===t.pdfBug,F=t.CanvasFactory||(_?ni:Ge),O=t.FilterFactory||(_?ii:Ye),N=!0===t.enableHWA,U=!1!==t.useWasm,j=l?l.length:t.length??NaN,z="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!_&&!k,H="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:!!(m===Xe&&v===Qe&&w===ti&&p&&b&&y&&Ht(p,document.baseURI)&&Ht(b,document.baseURI)&&Ht(y,document.baseURI));rt(d);const $={canvasFactory:new F({ownerDocument:P,enableHWA:N}),filterFactory:new O({docId:i,ownerDocument:P}),cMapReaderFactory:H?null:new m({baseUrl:p,isCompressed:g}),standardFontDataFactory:H?null:new v({baseUrl:b}),wasmFactory:H?null:new w({baseUrl:y})};c||(c=Un.create({verbosity:d,port:sn.workerPort}),e._worker=c);const W={docId:i,apiVersion:"5.4.296",data:s,password:o,disableAutoFetch:L,rangeChunkSize:h,length:j,docBaseUrl:u,enableXfa:D,evaluatorOptions:{maxImageSize:A,disableFontFace:k,ignoreErrors:x,isEvalSupported:S,isOffscreenCanvasSupported:C,isImageDecoderSupported:E,canvasMaxAreaInBytes:T,fontExtraProperties:M,useSystemFonts:z,useWasm:U,useWorkerFetch:H,cMapUrl:p,iccUrl:f,standardFontDataUrl:b,wasmUrl:y}},V={ownerDocument:P,pdfBug:B,styleElement:null,loadingParams:{disableAutoFetch:L,enableXfa:D}};return c.promise.then(function(){if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",W,s?[s.buffer]:null);let o;if(l)o=new hn(l,{disableRange:I,disableStream:R});else if(!s){if(!n)throw new Error("getDocument - no `url` parameter provided.");const t=Ht(n)?wn:_?kn:Sn;o=new t({url:n,length:j,httpHeaders:r,withCredentials:a,rangeChunkSize:h,disableRange:I,disableStream:R})}return t.then(t=>{if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const n=new We(i,t,c.port),s=new jn(n,e,o,V,$,N);e._transport=s,n.send("Ready",null)})}).catch(e._capability.reject),e}class Bn{static#Bi=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+Bn.#Bi++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class Fn{#Xn=Promise.withResolvers();#_s=[];#Ss=[];#Cs=[];#Es=[];constructor(t,e,i=!1,n=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=n}addRangeListener(t){this.#Es.push(t)}addProgressListener(t){this.#Cs.push(t)}addProgressiveReadListener(t){this.#Ss.push(t)}addProgressiveDoneListener(t){this.#_s.push(t)}onDataRange(t,e){for(const i of this.#Es)i(t,e)}onDataProgress(t,e){this.#Xn.promise.then(()=>{for(const i of this.#Cs)i(t,e)})}onDataProgressiveRead(t){this.#Xn.promise.then(()=>{for(const e of this.#Ss)e(t)})}onDataProgressiveDone(){this.#Xn.promise.then(()=>{for(const t of this.#_s)t()})}transportReady(){this.#Xn.resolve()}requestDataRange(t,e){ht("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class On{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return pt(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class Nn{#Ts=!1;constructor(t,e,i,n=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=n?new zt:null,this._pdfBug=n,this.commonObjs=i.commonObjs,this.objs=new In,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:n=0,dontFlip:s=!1}={}){return new Ot({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return pt(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:i,intent:n="display",annotationMode:s=L.ENABLE,transform:r=null,background:a=null,optionalContentConfigPromise:o=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:c=null,isEditing:d=!1,recordOperations:u=!1,operationsFilter:p=null}){this._stats?.time("Overall");const g=this._transport.getRenderingIntent(n,s,c,d),{renderingIntent:m,cacheKey:f}=g;this.#Ts=!1,o||=this._transport.getOptionalContentConfig(m);let b=this._intentStates.get(f);b||(b=Object.create(null),this._intentStates.set(f,b)),b.streamReaderCancelTimeout&&(clearTimeout(b.streamReaderCancelTimeout),b.streamReaderCancelTimeout=null);const v=!!(m&k);b.displayReadyCapability||(b.displayReadyCapability=Promise.withResolvers(),b.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(g));const y=Boolean(this._pdfBug&&globalThis.StepperManager?.enabled),w=!this.recordedBBoxes&&(u||y),x=t=>{if(b.renderTasks.delete(A),w){const t=A.gfx?.dependencyTracker.take();t&&(A.stepper&&A.stepper.setOperatorBBoxes(t,A.gfx.dependencyTracker.takeDebugMetadata()),u&&(this.recordedBBoxes=t))}v&&(this.#Ts=!0),this.#ks(),t?(A.capability.reject(t),this._abortOperatorList({intentState:b,reason:t instanceof Error?t:new Error(t)})):A.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},A=new Hn({callback:x,params:{canvas:e,canvasContext:t,dependencyTracker:w?new gi(e,b.operatorList.length,y):null,viewport:i,transform:r,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:b.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!v,pdfBug:this._pdfBug,pageColors:h,enableHWA:this._transport.enableHWA,operationsFilter:p});(b.renderTasks||=new Set).add(A);const _=A.task;return Promise.all([b.displayReadyCapability.promise,o]).then(([t,e])=>{if(this.destroyed)x();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&m))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:t,optionalContentConfig:e}),A.operatorListChanged()}}).catch(x),_}getOperatorList({intent:t="display",annotationMode:e=L.ENABLE,printAnnotationStorage:i=null,isEditing:n=!1}={}){const s=this._transport.getRenderingIntent(t,e,i,n,!0);let r,a=this._intentStates.get(s.cacheKey);return a||(a=Object.create(null),this._intentStates.set(s.cacheKey,a)),a.opListReadCapability||(r=Object.create(null),r.operatorListChanged=function(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(r))},a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||=new Set).add(r),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(s)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>It.textContent(t));const e=this.streamTextContent(t);return new Promise(function(t,i){const n=e.getReader(),s={items:[],styles:Object.create(null),lang:null};!function e(){n.read().then(function({value:i,done:n}){n?t(s):(s.lang??=i.lang,Object.assign(s.styles,i.styles),s.items.push(...i.items),e())},i)}()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#Ts=!1,Promise.all(t)}cleanup(t=!1){this.#Ts=!0;const e=this.#ks();return t&&e&&(this._stats&&=new zt),e}#ks(){if(!this.#Ts||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#Ts=!1,!0}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,n=t.length;i<n;i++)e.operatorList.fnArray.push(t.fnArray[i]),e.operatorList.argsArray.push(t.argsArray[i]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#ks()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:n}){const{map:s,transfer:r}=i,a=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:s,modifiedIds:n},r).getReader(),o=this._intentStates.get(e);o.streamReader=a;const l=()=>{a.read().then(({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())},t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#ks()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof Nt){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i))}}if(t.streamReader.cancel(new wt(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class Un{#Xn=Promise.withResolvers();#Ms=null;#Rn=null;#Ds=null;static#Ps=0;static#Is=!1;static#Rs=new WeakMap;static{_&&(this.#Is=!0,sn.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const n=new URL(e,i);return i.origin===n.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))},this.fromPort=t=>{var e;if(e="`PDFWorker.fromPort` - please use `PDFWorker.create` instead.",console.log("Deprecated API usage: "+e),!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.create(t)}}constructor({name:t=null,port:e=null,verbosity:i=at()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,e){if(Un.#Rs.has(e))throw new Error("Cannot use more than one PDFWorker per port.");Un.#Rs.set(e,this),this.#Ls(e)}else this.#Bs()}get promise(){return this.#Xn.promise}#Fs(){this.#Xn.resolve(),this.#Ms.send("configure",{verbosity:this.verbosity})}get port(){return this.#Rn}get messageHandler(){return this.#Ms}#Ls(t){this.#Rn=t,this.#Ms=new We("main","worker",t),this.#Ms.on("ready",()=>{}),this.#Fs()}#Bs(){if(Un.#Is||Un.#Os)return void this.#Ns();let{workerSrc:t}=Un;try{Un._isSameOrigin(window.location,t)||(t=Un._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new We("main","worker",e),n=()=>{s.abort(),i.destroy(),e.terminate(),this.destroyed?this.#Xn.reject(new Error("Worker was destroyed")):this.#Ns()},s=new AbortController;e.addEventListener("error",()=>{this.#Ds||n()},{signal:s.signal}),i.on("test",t=>{s.abort(),!this.destroyed&&t?(this.#Ms=i,this.#Rn=e,this.#Ds=e,this.#Fs()):n()}),i.on("ready",t=>{if(s.abort(),this.destroyed)n();else try{r()}catch{this.#Ns()}});const r=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void r()}catch{ot("The worker has been disabled.")}this.#Ns()}#Ns(){Un.#Is||(lt("Setting up fake worker."),Un.#Is=!0),Un._setupFakeWorkerGlobal.then(t=>{if(this.destroyed)return void this.#Xn.reject(new Error("Worker was destroyed"));const e=new Pe;this.#Rn=e;const i="fake"+Un.#Ps++,n=new We(i+"_worker",i,e);t.setup(n,e),this.#Ms=new We(i,i+"_worker",e),this.#Fs()}).catch(t=>{this.#Xn.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this.#Ds?.terminate(),this.#Ds=null,Un.#Rs.delete(this.#Rn),this.#Rn=null,this.#Ms?.destroy(),this.#Ms=null}static create(t){const e=this.#Rs.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new Un(t)}static get workerSrc(){if(sn.workerSrc)return sn.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Os(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return pt(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Os)return this.#Os;return(await(import(this.workerSrc))).WorkerMessageHandler})())}}class jn{#Us=new Map;#js=new Map;#zs=new Map;#Hs=new Map;#$s=null;constructor(t,e,i,n,s,r){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new In,this.fontLoader=new Ee({ownerDocument:n.ownerDocument,styleElement:n.styleElement}),this.loadingParams=n.loadingParams,this._params=n,this.canvasFactory=s.canvasFactory,this.filterFactory=s.filterFactory,this.cMapReaderFactory=s.cMapReaderFactory,this.standardFontDataFactory=s.standardFontDataFactory,this.wasmFactory=s.wasmFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=i,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.enableHWA=r,this.setupMessageHandler()}#Ws(t,e=null){const i=this.#Us.get(t);if(i)return i;const n=this.messageHandler.sendWithPromise(t,e);return this.#Us.set(t,n),n}get annotationStorage(){return pt(this,"annotationStorage",new Se)}getRenderingIntent(t,e=L.ENABLE,i=null,n=!1,s=!1){let r=T,a=_e;switch(t){case"any":r=E;break;case"display":break;case"print":r=k;break;default:lt(`getRenderingIntent - invalid intent: ${t}`)}const o=r&k&&i instanceof Ce?i:this.annotationStorage;switch(e){case L.DISABLE:r+=P;break;case L.ENABLE:break;case L.ENABLE_FORMS:r+=M;break;case L.ENABLE_STORAGE:r+=D,a=o.serializable;break;default:lt(`getRenderingIntent - invalid annotationMode: ${e}`)}n&&(r+=I),s&&(r+=R);const{ids:l,hash:h}=o.modifiedIds;return{renderingIntent:r,cacheKey:[r,a.hash,h].join("_"),annotationStorageSerializable:a,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#$s?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#js.values())t.push(e._destroy());this.#js.clear(),this.#zs.clear(),this.#Hs.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#Us.clear(),this.filterFactory.destroy(),Rn.cleanup(),this._networkStream?.cancelAllRequests(new wt("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{ct(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}},e.onPull=()=>{this._fullReader.read().then(function({value:t,done:i}){i?e.close():(ct(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{this._fullReader.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("ReaderHeadersReady",async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:s}=this._fullReader;return i&&n||(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:s}}),t.on("GetRangeReader",(t,e)=>{ct(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then(function({value:t,done:i}){i?e.close():(ct(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{i.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}):e.close()}),t.on("GetDoc",({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new On(t,this))}),t.on("DocException",t=>{e._capability.reject($e(t))}),t.on("PasswordRequest",t=>{this.#$s=Promise.withResolvers();try{if(!e.onPassword)throw $e(t);const i=t=>{t instanceof Error?this.#$s.reject(t):this.#$s.resolve({password:t})};e.onPassword(i,t.code)}catch(t){this.#$s.reject(t)}return this.#$s.promise}),t.on("DataLoaded",t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)}),t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#js.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}),t.on("commonobj",([e,i,n])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in n){const t=n.error;lt(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const s=new nn(n),r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new Te(s,r,n.extra,n.charProcOperatorList);this.fontLoader.bind(a).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{!a.fontExtraProperties&&a.data&&a.clearData(),this.commonObjs.resolve(e,a)});break;case"CopyLocalImage":const{imageRef:o}=n;ct(o,"The imageRef must be defined.");for(const t of this.#js.values())for(const[,i]of t.objs)if(i?.ref===o)return i.dataLen?(this.commonObjs.resolve(e,structuredClone(i)),i.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([t,e,i,n])=>{if(this.destroyed)return;const s=this.#js.get(e);if(!s.objs.has(t))if(0!==s._intentStates.size)switch(i){case"Image":case"Pattern":s.objs.resolve(t,n);break;default:throw new Error(`Got unknown object type ${i}`)}else n?.bitmap?.close()}),t.on("DocProgress",t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}),t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");const e=this[t.type];if(!e)throw new Error(`${t.type} not initialized, see the \`useWorkerFetch\` parameter.`);return e.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&<("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#zs.get(e);if(i)return i;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#Hs.set(i.refStr,t);const n=new Nn(e,i,this,this._params.pdfBug);return this.#js.set(e,n),n});return this.#zs.set(e,n),n}getPageIndex(t){return Me(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Ws("GetFieldObjects")}hasJSActions(){return this.#Ws("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#Ws("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Ws("GetOptionalContentConfig").then(e=>new ln(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Us.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new rn(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#Us.set(t,i),i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#js.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear(),t||this.fontLoader.clear(),this.#Us.clear(),this.filterFactory.destroy(!0),Rn.cleanup()}}cachedPageNumber(t){if(!Me(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#Hs.get(e)??null}}class zn{#Vs=null;onContinue=null;onError=null;constructor(t){this.#Vs=t}get promise(){return this.#Vs.capability.promise}cancel(t=0){this.#Vs.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Vs.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Vs;return t.form||t.canvas&&e?.size>0}}class Hn{#Gs=null;static#qs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:n,annotationCanvasMap:s,operatorList:r,pageIndex:a,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:c=!1,pageColors:d=null,enableHWA:u=!1,operationsFilter:p=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=n,this.annotationCanvasMap=s,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=a,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=c,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new zn(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvas,this._canvasContext=e.canvas?null:e.canvasContext,this._enableHWA=u,this._dependencyTracker=e.dependencyTracker,this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Hn.#qs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");Hn.#qs.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{viewport:i,transform:n,background:s,dependencyTracker:r}=this.params,a=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new Zi(a,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,r),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:s}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#Gs&&(window.cancelAnimationFrame(this.#Gs),this.#Gs=null),Hn.#qs.delete(this._canvas),t||=new Nt(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}operatorListChanged(){this.graphicsReady?(this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Gs=window.requestAnimationFrame(()=>{this.#Gs=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),Hn.#qs.delete(this._canvas),this.callback())))}}class $n{#Xs=null;#Ks=null;#Ys;#Js=null;#Qs=!1;#Zs=!1;#r=null;#tr;#er=null;#b=null;static#ir=null;static get _keyboardManager(){return pt(this,"_keyboardManager",new de([[["Escape","mac+Escape"],$n.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],$n.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],$n.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],$n.prototype._moveToPrevious],[["Home","mac+Home"],$n.prototype._moveToBeginning],[["End","mac+End"],$n.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#Zs=!1,this.#r=t):this.#Zs=!0,this.#b=t?._uiManager||e,this.#tr=this.#b._eventBus,this.#Ys=t?.color?.toUpperCase()||this.#b?.highlightColors.values().next().value||"#FFFF98",$n.#ir||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Xs=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.ariaHasPopup="true",this.#r&&(t.ariaControls=`${this.#r.id}_colorpicker_dropdown`);const e=this.#b._signal;t.addEventListener("click",this.#nr.bind(this),{signal:e}),t.addEventListener("keydown",this.#sr.bind(this),{signal:e});const i=this.#Ks=document.createElement("span");return i.className="swatch",i.ariaHidden="true",i.style.backgroundColor=this.#Ys,t.append(i),t}renderMainDropdown(){const t=this.#Js=this.#rr();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#rr(){const t=document.createElement("div"),e=this.#b._signal;t.addEventListener("contextmenu",$t,{signal:e}),t.className="dropdown",t.role="listbox",t.ariaMultiSelectable="false",t.ariaOrientation="vertical",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#r&&(t.id=`${this.#r.id}_colorpicker_dropdown`);for(const[i,n]of this.#b.highlightColors){const s=document.createElement("button");s.tabIndex="0",s.role="option",s.setAttribute("data-color",n),s.title=i,s.setAttribute("data-l10n-id",$n.#ir[i]);const r=document.createElement("span");s.append(r),r.className="swatch",r.style.backgroundColor=n,s.ariaSelected=n===this.#Ys,s.addEventListener("click",this.#ar.bind(this,n),{signal:e}),t.append(s)}return t.addEventListener("keydown",this.#sr.bind(this),{signal:e}),t}#ar(t,e){e.stopPropagation(),this.#tr.dispatch("switchannotationeditorparams",{source:this,type:O.HIGHLIGHT_COLOR,value:t}),this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#Xs)return void this.#nr(t);const e=t.target.getAttribute("data-color");e&&this.#ar(e,t)}_moveToNext(t){this.#or?t.target!==this.#Xs?t.target.nextSibling?.focus():this.#Js.firstChild?.focus():this.#nr(t)}_moveToPrevious(t){t.target!==this.#Js?.firstChild&&t.target!==this.#Xs?(this.#or||this.#nr(t),t.target.previousSibling?.focus()):this.#or&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#or?this.#Js.firstChild?.focus():this.#nr(t)}_moveToEnd(t){this.#or?this.#Js.lastChild?.focus():this.#nr(t)}#sr(t){$n._keyboardManager.exec(this,t)}#nr(t){if(this.#or)return void this.hideDropdown();if(this.#Qs=0===t.detail,this.#er||(this.#er=new AbortController,window.addEventListener("pointerdown",this.#u.bind(this),{signal:this.#b.combinedSignal(this.#er)})),this.#Xs.ariaExpanded="true",this.#Js)return void this.#Js.classList.remove("hidden");const e=this.#Js=this.#rr();this.#Xs.append(e)}#u(t){this.#Js?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#Js?.classList.add("hidden"),this.#Xs.ariaExpanded="false",this.#er?.abort(),this.#er=null}get#or(){return this.#Js&&!this.#Js.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#Zs||(this.#or?(this.hideDropdown(),this.#Xs.focus({preventScroll:!0,focusVisible:this.#Qs})):this.#r?.unselect())}updateColor(t){if(this.#Ks&&(this.#Ks.style.backgroundColor=t),!this.#Js)return;const e=this.#b.highlightColors.values();for(const i of this.#Js.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#Xs?.remove(),this.#Xs=null,this.#Ks=null,this.#Js?.remove(),this.#Js=null}}class Wn{#lr=null;#r=null;#b=null;static#ir=null;constructor(t){this.#r=t,this.#b=t._uiManager,Wn.#ir||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#lr)return this.#lr;const{editorType:t,colorType:e,colorValue:i}=this.#r,n=this.#lr=document.createElement("input");return n.type="color",n.value=i||"#000000",n.className="basicColorPicker",n.tabIndex=0,n.setAttribute("data-l10n-id",Wn.#ir[t]),n.addEventListener("input",()=>{this.#b.updateParams(e,n.value)},{signal:this.#b._signal}),n}update(t){this.#lr&&(this.#lr.value=t)}destroy(){this.#lr?.remove(),this.#lr=null}hideDropdown(){}}function Vn(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function Gn(t){return Math.max(0,Math.min(255,255*t))}class qn{static CMYK_G([t,e,i,n]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+n)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=Gn(t),t,t]}static G_HTML([t]){const e=Vn(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(Gn)}static RGB_HTML(t){return`#${t.map(Vn).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,n]){return["RGB",1-Math.min(1,t+n),1-Math.min(1,i+n),1-Math.min(1,e+n)]}static CMYK_rgb([t,e,i,n]){return[Gn(1-Math.min(1,t+n)),Gn(1-Math.min(1,i+n)),Gn(1-Math.min(1,e+n))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const n=1-t,s=1-e,r=1-i;return["CMYK",n,s,r,Math.min(n,s,r)]}}class Xn{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const n=this._createSVG("svg:svg");return n.setAttribute("version","1.1"),i||(n.setAttribute("width",`${t}px`),n.setAttribute("height",`${e}px`)),n.setAttribute("preserveAspectRatio","none"),n.setAttribute("viewBox",`0 0 ${t} ${e}`),n}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){ht("Abstract method `_createSVG` called.")}}class Kn extends Xn{_createSVG(t){return document.createElementNS(Lt,t)}}const Yn=new WeakSet,Jn=60*(new Date).getTimezoneOffset()*1e3;class Qn{static create(t){switch(t.data.annotationType){case V.LINK:return new es(t);case V.TEXT:return new is(t);case V.WIDGET:switch(t.data.fieldType){case"Tx":return new ss(t);case"Btn":return t.data.radioButton?new os(t):t.data.checkBox?new as(t):new ls(t);case"Ch":return new hs(t);case"Sig":return new rs(t)}return new ns(t);case V.POPUP:return new cs(t);case V.FREETEXT:return new us(t);case V.LINE:return new ps(t);case V.SQUARE:return new gs(t);case V.CIRCLE:return new ms(t);case V.POLYLINE:return new fs(t);case V.CARET:return new vs(t);case V.INK:return new ys(t);case V.POLYGON:return new bs(t);case V.HIGHLIGHT:return new ws(t);case V.UNDERLINE:return new xs(t);case V.SQUIGGLY:return new As(t);case V.STRIKEOUT:return new _s(t);case V.STAMP:return new Ss(t);case V.FILEATTACHMENT:return new Cs(t);default:return new Zn(t)}}}class Zn{#hr=null;#cr=!1;#dr=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:n=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableComment=t.enableComment,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(i)),n&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Zn._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:i,rect:n}=this.data;let s=-1/0,r=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)e[t+1]>r?(r=e[t+1],s=e[t+2]):e[t+1]===r&&(s=Math.max(s,e[t+2]));return[s,r]}if(i?.length>=1){for(const t of i)for(let e=0,i=t.length;e<i;e+=2)t[e+1]>r?(r=t[e+1],s=t[e]):t[e+1]===r&&(s=Math.max(s,t[e]));if(s!==1/0)return[s,r]}return n?[n[2],n[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:r}}}=this.parent;return t[1]=e[3]-t[1]+e[1],t[0]=100*(t[0]-s)/i,t[1]=100*(t[1]-r)/n,t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${B}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,i={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:i})||this.annotationStorage.setValue(`${B}${e.id}`,{id:e.id,annotationType:e.annotationType,pageIndex:this.parent.page._pageIndex,popup:i,popupRef:e.popupRef,modificationDate:new Date}),t||this.removePopup()}removePopup(){(this.#dr?.popup||this.popup)?.remove(),this.#dr=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#hr||={rect:this.data.rect.slice(0)});const{rect:e,popup:i}=t;e&&this.#ur(e);let n=this.#dr?.popup||this.popup;!n&&i?.text&&(this._createPopup(i),n=this.#dr.popup),n&&(n.updateEdited(t),i?.deleted&&(n.remove(),this.#dr=null,this.popup=null))}resetEdited(){this.#hr&&(this.#ur(this.#hr.rect),this.#dr?.popup.resetEdited(),this.#hr=null)}#ur(t){const{container:{style:e},data:{rect:i,rotation:n},parent:{viewport:{rawDims:{pageWidth:s,pageHeight:r,pageX:a,pageY:o}}}}=this;i?.splice(0,4,...t),e.left=100*(t[0]-a)/s+"%",e.top=100*(r-t[3]+o)/r+"%",0===n?(e.width=100*(t[2]-t[0])/s+"%",e.height=100*(t[3]-t[1])/r+"%"):this.setRotation(n)}_createContainer(t){const{data:e,parent:{page:i,viewport:n}}=this,s=document.createElement("section");s.setAttribute("data-annotation-id",e.id),this instanceof ns||this instanceof es||(s.tabIndex=0);const{style:r}=s;if(r.zIndex=this.parent.zIndex,this.parent.zIndex+=2,e.alternativeText&&(s.title=e.alternativeText),e.noRotate&&s.classList.add("norotate"),!e.rect||this instanceof cs){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,s),s}const{width:a,height:o}=this;if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;r.borderRadius=e}else if(this instanceof os){const t=`calc(${a}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;r.borderRadius=t}switch(e.borderStyle.style){case G:r.borderStyle="solid";break;case q:r.borderStyle="dashed";break;case X:lt("Unimplemented border style: beveled");break;case K:lt("Unimplemented border style: inset");break;case Y:r.borderBottomStyle="solid"}const n=e.borderColor||null;n?(this.#cr=!0,r.borderColor=Ct.makeHexColor(0|n[0],0|n[1],0|n[2])):r.borderWidth=0}const l=Ct.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:c,pageX:d,pageY:u}=n.rawDims;r.left=100*(l[0]-d)/h+"%",r.top=100*(l[1]-u)/c+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(r.width=100*a/h+"%",r.height=100*o/c+"%"):this.setRotation(p,s),s}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:n}=this.parent.viewport.rawDims;let{width:s,height:r}=this;t%180!=0&&([s,r]=[r,s]),e.style.width=100*s/i+"%",e.style.height=100*r/n+"%",e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const n=i.detail[t],s=n[0],r=n.slice(1);i.target.style[e]=qn[`${s}_HTML`](r),this.annotationStorage.setValue(this.data.id,{[e]:qn[`${s}_rgb`](r)})};return pt(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const n of Object.keys(e.detail)){const s=t[n]||i[n];s?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[n,s]of Object.entries(e)){const r=i[n];if(r){r({detail:{[n]:s},target:t}),delete e[n]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,n,s]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[r,a,o,l]=t.subarray(2,6);if(n===r&&s===a&&e===o&&i===l)return}const{style:r}=this.container;let a;if(this.#cr){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0,a=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${t}" stroke-width="${e}">`],this.container.classList.add("hasBorder")}const o=n-e,l=s-i,{svgFactory:h}=this,c=h.createElement("svg");c.classList.add("quadrilateralsContainer"),c.setAttribute("width",0),c.setAttribute("height",0),c.role="none";const d=h.createElement("defs");c.append(d);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),d.append(u);for(let i=2,n=t.length;i<n;i+=8){const n=t[i],r=t[i+1],c=t[i+2],d=t[i+3],p=h.createElement("rect"),g=(c-e)/o,m=(s-r)/l,f=(n-c)/o,b=(r-d)/l;p.setAttribute("x",g),p.setAttribute("y",m),p.setAttribute("width",f),p.setAttribute("height",b),u.append(p),a?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}this.#cr&&(a.push("</g></svg>')"),r.backgroundImage=a.join("")),this.container.append(c),this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:e}=this;let i,n;t?(i={str:t.text},n=t.date):(i=e.contentsObj,n=e.modificationDate);const s=this.#dr=new cs({data:{color:e.color,titleObj:e.titleObj,modificationDate:n,contentsObj:i,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]});this.parent._commentManager||this.parent.div.append(s.render())}get hasPopupElement(){return!!(this.#dr||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#dr}render(){ht("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const n=this._fieldObjects[t];if(n)for(const{page:t,id:s,exportValues:r}of n){if(-1===t)continue;if(s===e)continue;const n="string"==typeof r?r:null,a=document.querySelector(`[data-element-id="${s}"]`);!a||Yn.has(a)?i.push({id:s,exportValue:n,domElement:a}):lt(`_getElementsByName - element not allowed: ${s}`)}return i}for(const n of document.getElementsByName(t)){const{exportValue:t}=n,s=n.getAttribute("data-element-id");s!==e&&(Yn.has(n)&&i.push({id:s,exportValue:t,domElement:n}))}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class ts extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.editor=t.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){const{editor:t}=this;t.hasComment&&(this._createPopup(t.comment),this.extraPopupElement.popup.renderCommentButton())}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(t){this.editor.comment=t,t||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.container.remove(),this.container=null,this.removePopup()}}class es extends Zn{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let n=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),n=!0):t.action?(this._bindNamedAction(i,t.action,t.overlaidText),n=!0):t.attachment?(this.#pr(i,t.attachment,t.overlaidText,t.attachmentDest),n=!0):t.setOCGState?(this.#gr(i,t.setOCGState,t.overlaidText),n=!0):t.dest?(this._bindLink(i,t.dest,t.overlaidText),n=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),n=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),n=!0):this.isTooltipOnly&&!n&&(this._bindLink(i,""),n=!0)),this.container.classList.add("linkAnnotation"),n&&this.container.append(i),this.container}#mr(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,i=""){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#mr(),i&&(t.title=i)}_bindNamedAction(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),i&&(t.title=i),this.#mr()}#pr(t,e,i="",n=null){t.href=this.linkService.getAnchorUrl(""),e.description?t.title=e.description:i&&(t.title=i),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,n),!1),this.#mr()}#gr(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),i&&(t.title=i),this.#mr()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(e.actions)){const s=i.get(n);s&&(t[s]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:n}}),!1))}e.overlaidText&&(t.title=e.overlaidText),t.onclick||(t.onclick=()=>!1),this.#mr()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#mr(),!this._fieldObjects)return lt('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:n,include:s}=e,r=[];if(0!==t.length||0!==n.length){const e=new Set(n);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===s&&r.push(i)}else for(const t of Object.values(this._fieldObjects))r.push(...t);const a=this.annotationStorage,o=[];for(const t of r){const{id:e}=t;switch(o.push(e),t.type){case"text":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;a.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Yn.has(i)?i.dispatchEvent(new Event("resetform")):lt(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class is extends Zn{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class ns extends Zn{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return _t.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,n,s){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(i,t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t)}})})}_setEventListeners(t,e,i,n){for(const[s,r]of i)("Action"===r||this.data.actions?.[r])&&("Focus"!==r&&"Blur"!==r||(e||={focused:!1}),this._setEventListener(t,e,s,r,n),"Focus"!==r||this.data.actions?.Blur?"Blur"!==r||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Ct.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,n=this.data.defaultAppearanceData.fontSize||9,s=t.style;let r;const a=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(C*n))||1);r=Math.min(n,a(e/C))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(n,a(t/C))}s.fontSize=`calc(${r}px * var(--total-scale-factor))`,s.color=Ct.makeHexColor(i[0],i[1],i[2]),null!==this.data.textAlignment&&(s.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class ss extends ns{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,n){const s=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=i),s.setValue(r.id,{[n]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const n=t.getValue(e,{value:this.data.fieldValue});let s=n.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&s.length>r&&(s=s.slice(0,r));let a=n.formattedValue||this.data.textContent?.join("\n")||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const o={userValue:s,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(i=document.createElement("textarea"),i.textContent=a??s,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type=this.data.password?"password":"text",i.setAttribute("value",a??s),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),Yn.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=0;const{datetimeFormat:l,datetimeType:h,timeStep:c}=this.data,d=!!h&&this.enableScripting;l&&(i.title=l),this._setRequired(i,this.data.required),r&&(i.maxLength=r),i.addEventListener("input",n=>{t.setValue(e,{value:n.target.value}),this.setPropertyOnSiblings(i,"value",n.target.value,"value"),o.formattedValue=null}),i.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null});let u=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",t=>{if(o.focused)return;const{target:e}=t;if(d&&(e.type=h,c&&(e.step=c)),o.userValue){const t=o.userValue;if(d)if("time"===h){const i=new Date(t),n=[i.getHours(),i.getMinutes(),i.getSeconds()];e.value=n.map(t=>t.toString().padStart(2,"0")).join(":")}else e.value=new Date(t-Jn).toISOString().split("date"===h?"T":".",1)[0];else e.value=t}o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)}),i.addEventListener("updatefromsandbox",i=>{this.showElementAndHideCanvas(i.target);const n={value(i){o.userValue=i.detail.value??"",d||t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:n}=i.detail;o.formattedValue=n,null!=n&&i.target!==document.activeElement&&(i.target.value=n);const s={formattedValue:n};d&&(s.value=n),t.setValue(e,s)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:n}=i.detail,{target:s}=i;if(0===n)return void s.removeAttribute("maxLength");s.setAttribute("maxLength",n);let r=o.userValue;!r||r.length<=n||(r=r.slice(0,n),s.value=o.userValue=r,t.setValue(e,{value:r}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,willCommit:!0,commitKey:1,selStart:s.selectionStart,selEnd:s.selectionEnd}}))}};this._dispatchEventFromSandbox(n,i)}),i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:n}=t.target;o.lastCommittedValue!==n&&(o.lastCommittedValue=n,o.userValue=n,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))});const n=u;u=null,i.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{target:i}=t;let{value:s}=i;if(d){if(s&&"time"===h){const t=s.split(":").map(t=>parseInt(t,10));s=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf(),i.step=""}else s.includes("T")||(s=`${s}T00:00`),s=new Date(s).valueOf();i.type="text"}o.userValue=s,o.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),n(t)}),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;const{data:i,target:n}=t,{value:s,selectionStart:r,selectionEnd:a}=n;let l=r,h=a;switch(t.inputType){case"deleteWordBackward":{const t=s.substring(0,r).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=s.substring(r).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":r===a&&(l-=1);break;case"deleteContentForward":r===a&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}if(u&&i.addEventListener("blur",u),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/r;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--total-scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class rs extends ns{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class as extends ns{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof n&&(n="Off"!==n,t.setValue(i,{value:n})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const s=document.createElement("input");return Yn.add(s),s.setAttribute("data-element-id",i),s.disabled=e.readOnly,this._setRequired(s,this.data.required),s.type="checkbox",s.name=e.fieldName,n&&s.setAttribute("checked",!0),s.setAttribute("exportValue",e.exportValue),s.tabIndex=0,s.addEventListener("change",n=>{const{name:s,checked:r}=n.target;for(const n of this._getElementsByName(s,i)){const i=r&&n.exportValue===e.exportValue;n.domElement&&(n.domElement.checked=i),t.setValue(n.id,{value:i})}t.setValue(i,{value:r})}),s.addEventListener("resetform",t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}),this.enableScripting&&this.hasJSActions&&(s.addEventListener("updatefromsandbox",e=>{const n={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(n,e)}),this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class os extends ns{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof n&&(n=n!==e.buttonValue,t.setValue(i,{value:n})),n)for(const n of this._getElementsByName(e.fieldName,i))t.setValue(n.id,{value:!1});const s=document.createElement("input");if(Yn.add(s),s.setAttribute("data-element-id",i),s.disabled=e.readOnly,this._setRequired(s,this.data.required),s.type="radio",s.name=e.fieldName,n&&s.setAttribute("checked",!0),s.tabIndex=0,s.addEventListener("change",e=>{const{name:n,checked:s}=e.target;for(const e of this._getElementsByName(n,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:s})}),s.addEventListener("resetform",t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}),this.enableScripting&&this.hasJSActions){const n=e.buttonValue;s.addEventListener("updatefromsandbox",e=>{const s={value:e=>{const s=n===e.detail.value;for(const n of this._getElementsByName(e.target.name)){const e=s&&n.id===i;n.domElement&&(n.domElement.checked=e),t.setValue(n.id,{value:e})}}};this._dispatchEventFromSandbox(s,e)}),this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}return this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class ls extends es{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})),t}}class hs extends ns{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),n=document.createElement("select");Yn.add(n),n.setAttribute("data-element-id",e),n.disabled=this.data.readOnly,this._setRequired(n,this.data.required),n.name=this.data.fieldName,n.tabIndex=0;let s=this.data.combo&&this.data.options.length>0;this.data.combo||(n.size=this.data.options.length,this.data.multiSelect&&(n.multiple=!0)),n.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue;for(const t of n.options)t.selected=t.value===e});for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),s=!1),n.append(e)}let r=null;if(s){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),n.prepend(t),r=()=>{t.remove(),n.removeEventListener("input",r),r=null},n.addEventListener("input",r)}const a=t=>{const e=t?"value":"textContent",{options:i,multiple:s}=n;return s?Array.prototype.filter.call(i,t=>t.selected).map(t=>t[e]):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let o=a(!1);const l=t=>{const e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.textContent,exportValue:t.value}))};return this.enableScripting&&this.hasJSActions?(n.addEventListener("updatefromsandbox",i=>{const s={value(i){r?.();const s=i.detail.value,l=new Set(Array.isArray(s)?s:[s]);for(const t of n.options)t.selected=l.has(t.value);t.setValue(e,{value:a(!0)}),o=a(!1)},multipleSelection(t){n.multiple=!0},remove(i){const s=n.options,r=i.detail.remove;if(s[r].selected=!1,n.remove(r),s.length>0){-1===Array.prototype.findIndex.call(s,t=>t.selected)&&(s[0].selected=!0)}t.setValue(e,{value:a(!0),items:l(i)}),o=a(!1)},clear(i){for(;0!==n.length;)n.remove(0);t.setValue(e,{value:null,items:[]}),o=a(!1)},insert(i){const{index:s,displayValue:r,exportValue:h}=i.detail.insert,c=n.children[s],d=document.createElement("option");d.textContent=r,d.value=h,c?c.before(d):n.append(d),t.setValue(e,{value:a(!0),items:l(i)}),o=a(!1)},items(i){const{items:s}=i.detail;for(;0!==n.length;)n.remove(0);for(const t of s){const{displayValue:e,exportValue:i}=t,s=document.createElement("option");s.textContent=e,s.value=i,n.append(s)}n.options.length>0&&(n.options[0].selected=!0),t.setValue(e,{value:a(!0),items:l(i)}),o=a(!1)},indices(i){const n=new Set(i.detail.indices);for(const t of i.target.options)t.selected=n.has(t.index);t.setValue(e,{value:a(!0)}),o=a(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(s,i)}),n.addEventListener("input",i=>{const n=a(!0),s=a(!1);t.setValue(e,{value:n}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:s,changeEx:n,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(n,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],t=>t.target.value)):n.addEventListener("input",function(i){t.setValue(e,{value:a(!0)})}),this.data.combo&&this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class cs extends Zn{constructor(t){const{data:e,elements:i,parent:n}=t,s=!!n._commentManager;if(super(t,{isRenderable:!s&&Zn._hasPopupData(e)}),this.elements=i,s&&Zn._hasPopupData(e)){const t=this.popup=this.#fr();for(const e of i)e.popup=t}else this.popup=null}#fr(){return new ds({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const e=this.popup=this.#fr(),i=[];for(const t of this.elements)t.popup=e,t.container.ariaHasPopup="dialog",i.push(t.data.id),t.addHighlightArea();return this.container.setAttribute("aria-controls",i.map(t=>`${Mt}${t}`).join(",")),this.container}}class ds{#U=null;#br=this.#sr.bind(this);#vr=this.#yr.bind(this);#wr=this.#xr.bind(this);#Ar=this.#_r.bind(this);#Sr=null;#xt=null;#Cr=null;#Er=null;#Tr=null;#kr=null;#Mr=null;#Dr=!1;#Pr=null;#Ir=null;#k=null;#Rr=null;#Lr=null;#pe=null;#Br=null;#he=null;#Fr=null;#hr=null;#Or=!1;#Nr=null;#Ur=null;constructor({container:t,color:e,elements:i,titleObj:n,modificationDate:s,contentsObj:r,richText:a,parent:o,rect:l,parentRect:h,open:c,commentManager:d=null}){this.#xt=t,this.#Fr=n,this.#Cr=r,this.#he=a,this.#kr=o,this.#Sr=e,this.#Br=l,this.#Mr=h,this.#Tr=i,this.#U=d,this.#Nr=i[0],this.#Er=Vt.toDateObject(s),this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup()),d?this.renderCommentButton():(this.#jr(),this.#xt.hidden=!0,c&&this.#_r())}#jr(){if(this.#Ir)return;this.#Ir=new AbortController;const{signal:t}=this.#Ir;for(const e of this.trigger)e.addEventListener("click",this.#Ar,{signal:t}),e.addEventListener("pointerenter",this.#wr,{signal:t}),e.addEventListener("pointerleave",this.#vr,{signal:t}),e.classList.add("popupTriggerArea");for(const e of this.#Tr)e.container?.addEventListener("keydown",this.#br,{signal:t})}#zr(){const t=this.#Tr.find(t=>t.hasCommentButton);t&&(this.#Lr=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#Rr)return;if(this.#Lr||this.#zr(),!this.#Lr)return;const{signal:t}=this.#Ir=new AbortController,e=!!this.#Nr.extraPopupElement,i=()=>{this.#U.toggleCommentPopup(this,!0,void 0,!e)},n=()=>{this.#U.toggleCommentPopup(this,!1,!0,!e)},s=()=>{this.#U.toggleCommentPopup(this,!1,!1)};if(e){this.#Rr=this.#Nr.container;for(const e of this.trigger)e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.addEventListener("keydown",this.#br,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",n,{signal:t}),e.addEventListener("pointerleave",s,{signal:t}),e.classList.add("popupTriggerArea")}else{const e=this.#Rr=document.createElement("button");e.className="annotationCommentButton";const r=this.#Nr.container;e.style.zIndex=r.style.zIndex+1,e.tabIndex=0,e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#Hr(),this.#$r(),e.addEventListener("keydown",this.#br,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",n,{signal:t}),e.addEventListener("pointerleave",s,{signal:t}),r.after(e)}}#$r(){if(this.#Nr.extraPopupElement&&!this.#Nr.editor)return;this.renderCommentButton();const[t,e]=this.#Lr,{style:i}=this.#Rr;i.left=`calc(${t}%)`,i.top=`calc(${e}% - var(--comment-button-dim))`}#Hr(){this.#Nr.extraPopupElement||(this.renderCommentButton(),this.#Rr.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){const{color:t,opacity:e}=this.#Nr.commentData;return t?this.#kr._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#Rr?.focus()},0)}getData(){const{richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}=this.#Nr.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}}get elementBeforePopup(){return this.#Rr}get comment(){return this.#Ur||=this.#Nr.commentText,this.#Ur}set comment(t){t!==this.comment&&(this.#Nr.commentText=this.#Ur=t)}get parentBoundingClientRect(){return this.#Nr.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){this.#Rr&&(this.#Rr.classList.toggle("selected",t),this.#Rr.ariaExpanded=e)}setSelectedCommentButton(t){this.#Rr.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#pe)return this.#pe;const{x:t,y:e,height:i}=this.#Rr.getBoundingClientRect(),{x:n,y:s,width:r,height:a}=this.#Nr.layer.getBoundingClientRect();return[(t-n)/r,(e+i-s)/a]}set commentPopupPosition(t){this.#pe=t}hasDefaultPopupPosition(){return null===this.#pe}get commentButtonPosition(){return this.#Lr}get commentButtonWidth(){return this.#Rr.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,i]=this.#pe||this.commentButtonPosition.map(t=>t/100),n=this.parentBoundingClientRect,{x:s,y:r,width:a,height:o}=n;this.#U.showDialog(null,this,s+e*a,r+i*o,{...t,parentDimensions:n})}render(){if(this.#Pr)return;const t=this.#Pr=document.createElement("div");if(t.className="popup",this.#Sr){const e=t.style.outlineColor=Ct.makeHexColor(...this.#Sr);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");if(e.className="header",this.#Fr?.str){const t=document.createElement("span");t.className="title",e.append(t),({dir:t.dir,str:t.textContent}=this.#Fr)}if(t.append(e),this.#Er){const t=document.createElement("time");t.className="popupDate",t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#Er.valueOf()})),t.dateTime=this.#Er.toISOString(),e.append(t)}se({html:this.#Wr||this.#Cr.str,dir:this.#Cr?.dir,className:"popupContent"},t),this.#xt.append(t)}get#Wr(){const t=this.#he,e=this.#Cr;return!t?.str||e?.str&&e.str!==t.str?null:this.#he.html||null}get#Vr(){return this.#Wr?.attributes?.style?.fontSize||0}get#Gr(){return this.#Wr?.attributes?.style?.color||null}#qr(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},n={style:{color:this.#Gr,fontSize:this.#Vr?`calc(${this.#Vr}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:n});return i}#sr(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#Dr)&&this.#_r()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#U)return i?(this.remove(),this.#Ur=null):e&&(e.deleted?this.remove():(this.#Hr(),this.#Ur=e.text)),void(t&&(this.#Lr=null,this.#zr(),this.#$r()));i||e?.deleted?this.remove():(this.#jr(),this.#hr||={contentsObj:this.#Cr,richText:this.#he},t&&(this.#k=null),e&&e.text&&(this.#he=this.#qr(e.text),this.#Er=Vt.toDateObject(e.date),this.#Cr=null),this.#Pr?.remove(),this.#Pr=null)}resetEdited(){this.#hr&&(({contentsObj:this.#Cr,richText:this.#he}=this.#hr),this.#hr=null,this.#Pr?.remove(),this.#Pr=null,this.#k=null)}remove(){if(this.#Ir?.abort(),this.#Ir=null,this.#Pr?.remove(),this.#Pr=null,this.#Or=!1,this.#Dr=!1,this.#Rr?.remove(),this.#Rr=null,this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#Xr(){if(null!==this.#k)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:n,pageY:s}}}=this.#kr;let r=!!this.#Mr,a=r?this.#Mr:this.#Br;for(const t of this.#Tr)if(!a||null!==Ct.intersect(t.data.rect,a)){a=t.data.rect,r=!0;break}const o=Ct.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),l=r?a[2]-a[0]+5:0,h=o[0]+l,c=o[1];this.#k=[100*(h-n)/e,100*(c-s)/i];const{style:d}=this.#xt;d.left=`${this.#k[0]}%`,d.top=`${this.#k[1]}%`}#_r(){this.#U?this.#U.toggleCommentPopup(this,!1):(this.#Dr=!this.#Dr,this.#Dr?(this.#xr(),this.#xt.addEventListener("click",this.#Ar),this.#xt.addEventListener("keydown",this.#br)):(this.#yr(),this.#xt.removeEventListener("click",this.#Ar),this.#xt.removeEventListener("keydown",this.#br)))}#xr(){this.#Pr||this.render(),this.isVisible?this.#Dr&&this.#xt.classList.add("focused"):(this.#Xr(),this.#xt.hidden=!1,this.#xt.style.zIndex=parseInt(this.#xt.style.zIndex)+1e3)}#yr(){this.#xt.classList.remove("focused"),!this.#Dr&&this.isVisible&&(this.#xt.hidden=!0,this.#xt.style.zIndex=parseInt(this.#xt.style.zIndex)-1e3)}forceHide(){this.#Or=this.isVisible,this.#Or&&(this.#xt.hidden=!0)}maybeShow(){this.#U||(this.#jr(),this.#Or&&(this.#Pr||this.#xr(),this.#Or=!1,this.#xt.hidden=!1))}get isVisible(){return!this.#U&&!1===this.#xt.hidden}}class us extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=F.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const i=document.createElement("span");i.textContent=e,t.append(i)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class ps extends Zn{#Kr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=this.#Kr=this.svgFactory.createElement("svg:line");return s.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),s.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),s.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),s.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),s.setAttribute("stroke-width",t.borderStyle.width||1),s.setAttribute("stroke","transparent"),s.setAttribute("fill","transparent"),n.append(s),this.container.append(n),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Kr}addHighlightArea(){this.container.classList.add("highlightArea")}}class gs extends Zn{#Yr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,r=this.#Yr=this.svgFactory.createElement("svg:rect");return r.setAttribute("x",s/2),r.setAttribute("y",s/2),r.setAttribute("width",e-s),r.setAttribute("height",i-s),r.setAttribute("stroke-width",s||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),n.append(r),this.container.append(n),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Yr}addHighlightArea(){this.container.classList.add("highlightArea")}}class ms extends Zn{#Jr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,r=this.#Jr=this.svgFactory.createElement("svg:ellipse");return r.setAttribute("cx",e/2),r.setAttribute("cy",i/2),r.setAttribute("rx",e/2-s/2),r.setAttribute("ry",i/2-s/2),r.setAttribute("stroke-width",s||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),n.append(r),this.container.append(n),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Jr}addHighlightArea(){this.container.classList.add("highlightArea")}}class fs extends Zn{#Qr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:i,popupRef:n},width:s,height:r}=this;if(!e)return this.container;const a=this.svgFactory.create(s,r,!0);let o=[];for(let i=0,n=e.length;i<n;i+=2){const n=e[i]-t[0],s=t[3]-e[i+1];o.push(`${n},${s}`)}o=o.join(" ");const l=this.#Qr=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",o),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),a.append(l),this.container.append(a),!n&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Qr}addHighlightArea(){this.container.classList.add("highlightArea")}}class bs extends fs{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class vs extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class ys extends Zn{#Zr=null;#ta=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?F.HIGHLIGHT:F.INK}#ea(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:i,borderStyle:n,popupRef:s}}=this,{transform:r,width:a,height:o}=this.#ea(e,t),l=this.svgFactory.create(a,o,!0),h=this.#Zr=this.svgFactory.createElement("svg:g");l.append(h),h.setAttribute("stroke-width",n.width||1),h.setAttribute("stroke-linecap","round"),h.setAttribute("stroke-linejoin","round"),h.setAttribute("stroke-miterlimit",10),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),h.setAttribute("transform",r);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#ta.push(e),e.setAttribute("points",i[t].join(",")),h.append(e)}return!s&&this.hasPopupData&&this._createPopup(),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:n}=t,s=this.#Zr;if(e>=0&&s.setAttribute("stroke-width",e||1),i)for(let t=0,e=this.#ta.length;t<e;t++)this.#ta[t].setAttribute("points",i[t].join(","));if(n){const{transform:t,width:e,height:i}=this.#ea(this.data.rotation,n);s.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`),s.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#ta}addHighlightArea(){this.container.classList.add("highlightArea")}}class ws extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=F.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){const e=document.createElement("mark");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class xs extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),t){const e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class As extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),t){const e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class _s extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),t){const e=document.createElement("s");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class Ss extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=F.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Cs extends Zn{#ia=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let i;e.hasAppearance||0===e.fillAlpha?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)),i.addEventListener("dblclick",this.#na.bind(this)),this.#ia=i;const{isMac:n}=_t.platform;return t.addEventListener("keydown",t=>{"Enter"===t.key&&(n?t.metaKey:t.ctrlKey)&&this.#na()}),!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#ia}addHighlightArea(){this.container.classList.add("highlightArea")}#na(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Es{#sa=null;#ra=null;#F=null;#aa=new Map;#oa=null;#la=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:n,page:s,viewport:r,structTreeLayer:a,commentManager:o,linkService:l,annotationStorage:h}){this.div=t,this.#sa=e,this.#ra=i,this.#oa=a||null,this.#la=l||null,this.#F=h||new Se,this.page=s,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=n,this._commentManager=o||null}hasEditableAnnotations(){return this.#aa.size>0}async#ha(t,e,i){const n=t.firstChild||t,s=n.id=`${Mt}${e}`,r=await(this.#oa?.getAriaAttributes(s));if(r)for(const[t,e]of r)n.setAttribute(t,e);i?i.at(-1).container.after(t):(this.div.append(t),this.#sa?.moveElementInDOM(this.div,t,n,!1))}async render(t){const{annotations:e}=t,i=this.div;Kt(i,this.viewport);const n=new Map,s={data:null,layer:i,linkService:this.#la,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new Kn,annotationStorage:this.#F,enableComment:!0===t.enableComment,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===V.POPUP;if(e){const e=n.get(t.id);if(!e)continue;s.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;s.data=t;const i=Qn.create(s);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=n.get(t.popupRef);e?e.push(i):n.set(t.popupRef,[i])}const r=i.render();t.hidden&&(r.style.visibility="hidden"),await this.#ha(r,t.id,s.elements),i.extraPopupElement?.popup?.renderCommentButton(),i._isEditable&&(this.#aa.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}this.#ca()}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#la,svgFactory:new Kn,parent:this};for(const i of t){i.borderStyle||=Es._defaultBorderStyle,e.data=i;const t=Qn.create(e);if(!t.isRenderable)continue;const n=t.render();await this.#ha(n,i.id,null)}}update({viewport:t}){const e=this.div;this.viewport=t,Kt(e,{rotation:t.rotation}),this.#ca(),e.hidden=!1}#ca(){if(!this.#ra)return;const t=this.div;for(const[e,i]of this.#ra){const n=t.querySelector(`[data-annotation-id="${e}"]`);if(!n)continue;i.className="annotationContent";const{firstChild:s}=n;s?"CANVAS"===s.nodeName?s.replaceWith(i):s.classList.contains("annotationContent")?s.after(i):s.before(i):n.append(i);const r=this.#aa.get(e);r&&(r._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(e,n.id,i),r._hasNoCanvas=!1):r.canvas=i)}this.#ra.clear()}getEditableAnnotations(){return Array.from(this.#aa.values())}getEditableAnnotation(t){return this.#aa.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:i,rotation:n}=t,s=new ts({data:{id:i,rect:t.getPDFRect(),rotation:n},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#la,annotationStorage:this.#F}),r=s.render();return e.append(r),this.#sa?.moveElementInDOM(e,r,r,!1),s.createOrUpdatePopup(),s}static get _defaultBorderStyle(){return pt(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:G,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const Ts=/\r\n?|\n/g;class ks extends be{#da="";#ua=`${this.id}-editor`;#pa=null;#Vr;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=ks.prototype,e=t=>t.isEmpty(),i=pe.TRANSLATE_SMALL,n=pe.TRANSLATE_BIG;return pt(this,"_keyboardManager",new de([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,n],checker:e}]]))}static _type="freetext";static _editorType=F.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.color=t.color||ks._defaultColor||be._defaultLineColor,this.#Vr=t.fontSize||ks._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert")}static initialize(t,e){be.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case O.FREETEXT_SIZE:ks._defaultFontSize=e;break;case O.FREETEXT_COLOR:ks._defaultColor=e}}updateParams(t,e){switch(t){case O.FREETEXT_SIZE:this.#ga(e);break;case O.FREETEXT_COLOR:this.#Hr(e)}}static get defaultPropertiesToUpdate(){return[[O.FREETEXT_SIZE,ks._defaultFontSize],[O.FREETEXT_COLOR,ks._defaultColor||be._defaultLineColor]]}get propertiesToUpdate(){return[[O.FREETEXT_SIZE,this.#Vr],[O.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new Wn(this),[["colorPicker",this._colorPicker]]}get colorType(){return O.FREETEXT_COLOR}#ga(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#Vr)*this.parentScale),this.#Vr=t,this.#ma()},i=this.#Vr;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:O.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#Hr(t){const e=t=>{this.color=t,this.onUpdatedColor()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:O.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-ks._internalPadding*t,-(ks._internalPadding+this.#Vr)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#pa=new AbortController;const t=this._uiManager.combinedSignal(this.#pa);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return!!super.disableEditMode()&&(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#ua),this._isDraggable=!0,this.#pa?.abort(),this.#pa=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0)}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#fa(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(ks.#ba(i)),e=i);return t.join("\n")}#ma(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,n=e.style.display,s=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=n,e.classList.toggle("hidden",s)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#da,e=this.#da=this.#fa().trimEnd();if(t===e)return;const i=t=>{this.#da=t,t?(this.#va(),this._uiManager.rebuild(this),this.#ma()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#ma()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){ks._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(this._isCopy||this.annotationElementId)&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#ua),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#Vr}px * var(--total-scale-factor))`,i.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:s}=this._initialData;let[r,a]=this.getInitialTranslation();[r,a]=this.pageTranslationToScreen(r,a);const[o,l]=this.pageDimensions,[h,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(s[0]-h)/o,u=e+this.height-(s[1]-c)/l;break;case 90:d=t+(s[0]-h)/o,u=e-(s[1]-c)/l,[r,a]=[a,-r];break;case 180:d=t-this.width+(s[0]-h)/o,u=e-(s[1]-c)/l,[r,a]=[-r,-a];break;case 270:d=t+(s[0]-h-this.height*l)/o,u=e+(s[1]-c-this.width*o)/l,[r,a]=[-a,r]}this.setAt(d*i,u*n,r,a)}else this._moveAfterPaste(t,e);this.#va(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#ba(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Ts,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const n=ks.#ya(e.getData("text")||"").replaceAll(Ts,"\n");if(!n)return;const s=window.getSelection();if(!s.rangeCount)return;this.editorDiv.normalize(),s.deleteFromDocument();const r=s.getRangeAt(0);if(!n.includes("\n"))return r.insertNode(document.createTextNode(n)),this.editorDiv.normalize(),void s.collapseToStart();const{startContainer:a,startOffset:o}=r,l=[],h=[];if(a.nodeType===Node.TEXT_NODE){const t=a.parentElement;if(h.push(a.nodeValue.slice(o).replaceAll(Ts,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(ks.#ba(i)):e=h}l.push(a.nodeValue.slice(0,o).replaceAll(Ts,""))}else if(a===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(ks.#ba(i))}this.#da=`${l.join("\n")}${n}${h.join("\n")}`,this.#va();const c=new Range;let d=Math.sumPrecise(l.map(t=>t.length));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(d<=e){c.setStart(t,d),c.setEnd(t,d);break}d-=e}s.removeAllRanges(),s.addRange(c)}#va(){if(this.editorDiv.replaceChildren(),this.#da)for(const t of this.#da.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#wa(){return this.#da.replaceAll(" "," ")}static#ya(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=ks._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,i){let n=null;if(t instanceof us){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:s,rotation:r,id:a,popupRef:o,richText:l,contentsObj:h,creationDate:c,modificationDate:d},textContent:u,textPosition:p,parent:{page:{pageNumber:g}}}=t;if(!u||0===u.length)return null;n=t={annotationType:F.FREETEXT,color:Array.from(i),fontSize:e,value:u.join("\n"),position:p,pageIndex:g-1,rect:s.slice(0),rotation:r,annotationElementId:a,id:a,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:c,modificationDate:d}}const s=await super.deserialize(t,e,i);return s.#Vr=t.fontSize,s.color=Ct.makeHexColor(...t.color),s.#da=ks.#ya(t.value),s._initialData=n,t.comment&&s.setCommentData(t),s}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=be._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:e,fontSize:this.#Vr,value:this.#wa()});return this.addComment(i),t?(i.isCopy=!0,i):this.annotationElementId&&!this.#xa(i)?null:(i.id=this.annotationElementId,i)}#xa(t){const{value:e,fontSize:i,color:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==n[e])||t.pageIndex!==s}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:i}=e;i.fontSize=`calc(${this.#Vr}px * var(--total-scale-factor))`,i.color=this.color,e.replaceChildren();for(const t of this.#da.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#da}}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class Ms{static PRECISION=1e-4;toSVGPath(){ht("Abstract method `toSVGPath` must be implemented.")}get box(){ht("Abstract getter `box` must be implemented.")}serialize(t,e){ht("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,n,s,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a]*n,r[a+1]=i+t[a+1]*s;return r}static _rescaleAndSwap(t,e,i,n,s,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a+1]*n,r[a+1]=i+t[a]*s;return r}static _translate(t,e,i,n){n||=new Float32Array(t.length);for(let s=0,r=t.length;s<r;s+=2)n[s]=e+t[s],n[s+1]=i+t[s+1];return n}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,n,s){switch(s){case 90:return[1-e/i,t/n];case 180:return[1-t/i,1-e/n];case 270:return[e/i,1-t/n];default:return[t/i,e/n]}}static _normalizePagePoint(t,e,i){switch(i){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,i,n,s,r){return[(t+5*i)/6,(e+5*n)/6,(5*i+s)/6,(5*n+r)/6,(i+s)/2,(n+r)/2]}}class Ds{#Aa;#_a=[];#Sa;#Ca;#Ea=[];#Ta=new Float32Array(18);#ka;#Ma;#Da;#Pa;#Ia;#Ra;#La=[];static#Ba=8;static#Fa=2;static#Oa=Ds.#Ba+Ds.#Fa;constructor({x:t,y:e},i,n,s,r,a=0){this.#Aa=i,this.#Ra=s*n,this.#Ca=r,this.#Ta.set([NaN,NaN,NaN,NaN,t,e],6),this.#Sa=a,this.#Pa=Ds.#Ba*n,this.#Da=Ds.#Oa*n,this.#Ia=n,this.#La.push(t,e)}isEmpty(){return isNaN(this.#Ta[8])}#Na(){const t=this.#Ta.subarray(4,6),e=this.#Ta.subarray(16,18),[i,n,s,r]=this.#Aa;return[(this.#ka+(t[0]-e[0])/2-i)/s,(this.#Ma+(t[1]-e[1])/2-n)/r,(this.#ka+(e[0]-t[0])/2-i)/s,(this.#Ma+(e[1]-t[1])/2-n)/r]}add({x:t,y:e}){this.#ka=t,this.#Ma=e;const[i,n,s,r]=this.#Aa;let[a,o,l,h]=this.#Ta.subarray(8,12);const c=t-l,d=e-h,u=Math.hypot(c,d);if(u<this.#Da)return!1;const p=u-this.#Pa,g=p/u,m=g*c,f=g*d;let b=a,v=o;a=l,o=h,l+=m,h+=f,this.#La?.push(t,e);const y=m/p,w=-f/p*this.#Ra,x=y*this.#Ra;if(this.#Ta.set(this.#Ta.subarray(2,8),0),this.#Ta.set([l+w,h+x],4),this.#Ta.set(this.#Ta.subarray(14,18),12),this.#Ta.set([l-w,h-x],16),isNaN(this.#Ta[6]))return 0===this.#Ea.length&&(this.#Ta.set([a+w,o+x],2),this.#Ea.push(NaN,NaN,NaN,NaN,(a+w-i)/s,(o+x-n)/r),this.#Ta.set([a-w,o-x],14),this.#_a.push(NaN,NaN,NaN,NaN,(a-w-i)/s,(o-x-n)/r)),this.#Ta.set([b,v,a,o,l,h],6),!this.isEmpty();this.#Ta.set([b,v,a,o,l,h],6);return Math.abs(Math.atan2(v-o,b-a)-Math.atan2(f,m))<Math.PI/2?([a,o,l,h]=this.#Ta.subarray(2,6),this.#Ea.push(NaN,NaN,NaN,NaN,((a+l)/2-i)/s,((o+h)/2-n)/r),[a,o,b,v]=this.#Ta.subarray(14,18),this.#_a.push(NaN,NaN,NaN,NaN,((b+a)/2-i)/s,((v+o)/2-n)/r),!0):([b,v,a,o,l,h]=this.#Ta.subarray(0,6),this.#Ea.push(((b+5*a)/6-i)/s,((v+5*o)/6-n)/r,((5*a+l)/6-i)/s,((5*o+h)/6-n)/r,((a+l)/2-i)/s,((o+h)/2-n)/r),[l,h,a,o,b,v]=this.#Ta.subarray(12,18),this.#_a.push(((b+5*a)/6-i)/s,((v+5*o)/6-n)/r,((5*a+l)/6-i)/s,((5*o+h)/6-n)/r,((a+l)/2-i)/s,((o+h)/2-n)/r),!0)}toSVGPath(){if(this.isEmpty())return"";const t=this.#Ea,e=this.#_a;if(isNaN(this.#Ta[6])&&!this.isEmpty())return this.#Ua();const i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#ja(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return this.#za(i),i.join(" ")}#Ua(){const[t,e,i,n]=this.#Aa,[s,r,a,o]=this.#Na();return`M${(this.#Ta[2]-t)/i} ${(this.#Ta[3]-e)/n} L${(this.#Ta[4]-t)/i} ${(this.#Ta[5]-e)/n} L${s} ${r} L${a} ${o} L${(this.#Ta[16]-t)/i} ${(this.#Ta[17]-e)/n} L${(this.#Ta[14]-t)/i} ${(this.#Ta[15]-e)/n} Z`}#za(t){const e=this.#_a;t.push(`L${e[4]} ${e[5]} Z`)}#ja(t){const[e,i,n,s]=this.#Aa,r=this.#Ta.subarray(4,6),a=this.#Ta.subarray(16,18),[o,l,h,c]=this.#Na();t.push(`L${(r[0]-e)/n} ${(r[1]-i)/s} L${o} ${l} L${h} ${c} L${(a[0]-e)/n} ${(a[1]-i)/s}`)}newFreeDrawOutline(t,e,i,n,s,r){return new Ps(t,e,i,n,s,r)}getOutlines(){const t=this.#Ea,e=this.#_a,i=this.#Ta,[n,s,r,a]=this.#Aa,o=new Float32Array((this.#La?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2)o[t]=(this.#La[t]-n)/r,o[t+1]=(this.#La[t+1]-s)/a;if(o[o.length-2]=(this.#ka-n)/r,o[o.length-1]=(this.#Ma-s)/a,isNaN(i[6])&&!this.isEmpty())return this.#Ha(o);const l=new Float32Array(this.#Ea.length+24+this.#_a.length);let h=t.length;for(let e=0;e<h;e+=2)isNaN(t[e])?l[e]=l[e+1]=NaN:(l[e]=t[e],l[e+1]=t[e+1]);h=this.#$a(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(l[h]=l[h+1]=NaN,h+=2):(l[h]=e[t+i],l[h+1]=e[t+i+1],h+=2);return this.#Wa(l,h),this.newFreeDrawOutline(l,o,this.#Aa,this.#Ia,this.#Sa,this.#Ca)}#Ha(t){const e=this.#Ta,[i,n,s,r]=this.#Aa,[a,o,l,h]=this.#Na(),c=new Float32Array(36);return c.set([NaN,NaN,NaN,NaN,(e[2]-i)/s,(e[3]-n)/r,NaN,NaN,NaN,NaN,(e[4]-i)/s,(e[5]-n)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/s,(e[17]-n)/r,NaN,NaN,NaN,NaN,(e[14]-i)/s,(e[15]-n)/r],0),this.newFreeDrawOutline(c,t,this.#Aa,this.#Ia,this.#Sa,this.#Ca)}#Wa(t,e){const i=this.#_a;return t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e),e+6}#$a(t,e){const i=this.#Ta.subarray(4,6),n=this.#Ta.subarray(16,18),[s,r,a,o]=this.#Aa,[l,h,c,d]=this.#Na();return t.set([NaN,NaN,NaN,NaN,(i[0]-s)/a,(i[1]-r)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(n[0]-s)/a,(n[1]-r)/o],e),e+24}}class Ps extends Ms{#Aa;#Va=new Float32Array(4);#Sa;#Ca;#La;#Ia;#Ga;constructor(t,e,i,n,s,r){super(),this.#Ga=t,this.#La=e,this.#Aa=i,this.#Ia=n,this.#Sa=s,this.#Ca=r,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#qa(r);const[a,o,l,h]=this.#Va;for(let e=0,i=t.length;e<i;e+=2)t[e]=(t[e]-a)/l,t[e+1]=(t[e+1]-o)/h;for(let t=0,i=e.length;t<i;t+=2)e[t]=(e[t]-a)/l,e[t+1]=(e[t+1]-o)/h}toSVGPath(){const t=[`M${this.#Ga[4]} ${this.#Ga[5]}`];for(let e=6,i=this.#Ga.length;e<i;e+=6)isNaN(this.#Ga[e])?t.push(`L${this.#Ga[e+4]} ${this.#Ga[e+5]}`):t.push(`C${this.#Ga[e]} ${this.#Ga[e+1]} ${this.#Ga[e+2]} ${this.#Ga[e+3]} ${this.#Ga[e+4]} ${this.#Ga[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,i,n],s){const r=i-t,a=n-e;let o,l;switch(s){case 0:o=Ms._rescale(this.#Ga,t,n,r,-a),l=Ms._rescale(this.#La,t,n,r,-a);break;case 90:o=Ms._rescaleAndSwap(this.#Ga,t,e,r,a),l=Ms._rescaleAndSwap(this.#La,t,e,r,a);break;case 180:o=Ms._rescale(this.#Ga,i,e,-r,a),l=Ms._rescale(this.#La,i,e,-r,a);break;case 270:o=Ms._rescaleAndSwap(this.#Ga,i,n,-r,-a),l=Ms._rescaleAndSwap(this.#La,i,n,-r,-a)}return{outline:Array.from(o),points:[Array.from(l)]}}#qa(t){const e=this.#Ga;let i=e[4],n=e[5];const s=[i,n,i,n];let r=i,a=n,o=i,l=n;const h=t?Math.max:Math.min,c=new Float32Array(4);for(let t=6,d=e.length;t<d;t+=6){const d=e[t+4],u=e[t+5];isNaN(e[t])?(Ct.pointBoundingBox(d,u,s),a>u?(r=d,a=u):a===u&&(r=h(r,d)),l<u?(o=d,l=u):l===u&&(o=h(o,d))):(c[0]=c[1]=1/0,c[2]=c[3]=-1/0,Ct.bezierBoundingBox(i,n,...e.slice(t,t+6),c),Ct.rectBoundingBox(c[0],c[1],c[2],c[3],s),a>c[1]?(r=c[0],a=c[1]):a===c[1]&&(r=h(r,c[0])),l<c[3]?(o=c[2],l=c[3]):l===c[3]&&(o=h(o,c[2]))),i=d,n=u}const d=this.#Va;d[0]=s[0]-this.#Sa,d[1]=s[1]-this.#Sa,d[2]=s[2]-s[0]+2*this.#Sa,d[3]=s[3]-s[1]+2*this.#Sa,this.firstPoint=[r,a],this.lastPoint=[o,l]}get box(){return this.#Va}newOutliner(t,e,i,n,s,r=0){return new Ds(t,e,i,n,s,r)}getNewOutline(t,e){const[i,n,s,r]=this.#Va,[a,o,l,h]=this.#Aa,c=s*l,d=r*h,u=i*l+a,p=n*h+o,g=this.newOutliner({x:this.#La[0]*c+u,y:this.#La[1]*d+p},this.#Aa,this.#Ia,t,this.#Ca,e??this.#Sa);for(let t=2;t<this.#La.length;t+=2)g.add({x:this.#La[t]*c+u,y:this.#La[t+1]*d+p});return g.getOutlines()}}class Is{#Aa;#Xa;#Ka;#Ya=[];#Ja=[];constructor(t,e=0,i=0,n=!0){const s=[1/0,1/0,-1/0,-1/0],r=10**-4;for(const{x:i,y:n,width:a,height:o}of t){const t=Math.floor((i-e)/r)*r,l=Math.ceil((i+a+e)/r)*r,h=Math.floor((n-e)/r)*r,c=Math.ceil((n+o+e)/r)*r,d=[t,h,c,!0],u=[l,h,c,!1];this.#Ya.push(d,u),Ct.rectBoundingBox(t,h,l,c,s)}const a=s[2]-s[0]+2*i,o=s[3]-s[1]+2*i,l=s[0]-i,h=s[1]-i;let c=n?-1/0:1/0,d=1/0;const u=this.#Ya.at(n?-1:-2),p=[u[0],u[2]];for(const t of this.#Ya){const[e,i,s,r]=t;!r&&n?i<d?(d=i,c=e):i===d&&(c=Math.max(c,e)):r&&!n&&(i<d?(d=i,c=e):i===d&&(c=Math.min(c,e))),t[0]=(e-l)/a,t[1]=(i-h)/o,t[2]=(s-h)/o}this.#Aa=new Float32Array([l,h,a,o]),this.#Xa=[c,d],this.#Ka=p}getOutlines(){this.#Ya.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#Ya)e[3]?(t.push(...this.#Qa(e)),this.#Za(e)):(this.#to(e),t.push(...this.#Qa(e)));return this.#eo(t)}#eo(t){const e=[],i=new Set;for(const i of t){const[t,n,s]=i;e.push([t,n,i],[t,s,i])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,n=e.length;t<n;t+=2){const n=e[t][2],s=e[t+1][2];n.push(s),s.push(n),i.add(n),i.add(s)}const n=[];let s;for(;i.size>0;){const t=i.values().next().value;let[e,r,a,o,l]=t;i.delete(t);let h=e,c=r;for(s=[e,a],n.push(s);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,r,a,o,l]=t,h!==e&&(s.push(h,c,e,c===r?r:a),h=e),c=c===r?a:r}s.push(h,c)}return new Rs(n,this.#Aa,this.#Xa,this.#Ka)}#io(t){const e=this.#Ja;let i=0,n=e.length-1;for(;i<=n;){const s=i+n>>1,r=e[s][0];if(r===t)return s;r<t?i=s+1:n=s-1}return n+1}#Za([,t,e]){const i=this.#io(t);this.#Ja.splice(i,0,[t,e])}#to([,t,e]){const i=this.#io(t);for(let n=i;n<this.#Ja.length;n++){const[i,s]=this.#Ja[n];if(i!==t)break;if(i===t&&s===e)return void this.#Ja.splice(n,1)}for(let n=i-1;n>=0;n--){const[i,s]=this.#Ja[n];if(i!==t)break;if(i===t&&s===e)return void this.#Ja.splice(n,1)}}#Qa(t){const[e,i,n]=t,s=[[e,i,n]],r=this.#io(n);for(let t=0;t<r;t++){const[i,n]=this.#Ja[t];for(let t=0,r=s.length;t<r;t++){const[,a,o]=s[t];if(!(n<=a||o<=i))if(a>=i)if(o>n)s[t][1]=n;else{if(1===r)return[];s.splice(t,1),t--,r--}else s[t][2]=i,o>n&&s.push([e,n,o])}}return s}}class Rs extends Ms{#Aa;#no;constructor(t,e,i,n){super(),this.#no=t,this.#Aa=e,this.firstPoint=i,this.lastPoint=n}toSVGPath(){const t=[];for(const e of this.#no){let[i,n]=e;t.push(`M${i} ${n}`);for(let s=2;s<e.length;s+=2){const r=e[s],a=e[s+1];r===i?(t.push(`V${a}`),n=a):a===n&&(t.push(`H${r}`),i=r)}t.push("Z")}return t.join(" ")}serialize([t,e,i,n],s){const r=[],a=i-t,o=n-e;for(const e of this.#no){const i=new Array(e.length);for(let s=0;s<e.length;s+=2)i[s]=t+e[s]*a,i[s+1]=n-e[s+1]*o;r.push(i)}return r}get box(){return this.#Aa}get classNamesForOutlining(){return["highlightOutline"]}}class Ls extends Ds{newFreeDrawOutline(t,e,i,n,s,r){return new Bs(t,e,i,n,s,r)}}class Bs extends Ps{newOutliner(t,e,i,n,s,r=0){return new Ls(t,e,i,n,s,r)}}class Fs extends be{#so=null;#ro=0;#ao;#oo=null;#s=null;#lo=null;#ho=null;#co=0;#do=null;#uo=null;#x=null;#po=!1;#Xa=null;#Ka=null;#go=null;#ce="";#Ra;#mo="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=F.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=Fs.prototype;return pt(this,"_keyboardManager",new de([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||Fs._defaultColor,this.#Ra=t.thickness||Fs._defaultThickness,this.opacity=t.opacity||Fs._defaultOpacity,this.#ao=t.boxes||null,this.#mo=t.methodOfCreation||"",this.#ce=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#po=!0,this.#fo(t),this.#bo()):this.#ao&&(this.#so=t.anchorNode,this.#ro=t.anchorOffset,this.#ho=t.focusNode,this.#co=t.focusOffset,this.#vo(),this.#bo(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}get telemetryInitialData(){return{action:"added",type:this.#po?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#Ra,methodOfCreation:this.#mo}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#vo(){const t=new Is(this.#ao,.001);this.#uo=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#uo.box;const e=new Is(this.#ao,.0025,.001,"ltr"===this._uiManager.direction);this.#lo=e.getOutlines();const{firstPoint:i}=this.#uo;this.#Xa=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];const{lastPoint:n}=this.#lo;this.#Ka=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height]}#fo({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#uo=t;if(this.#lo=t.getNewOutline(this.#Ra/2+1.5,.0025),e>=0)this.#x=e,this.#oo=i,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#go=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#lo.box,path:{d:this.#lo.toSVGPath()}},!0);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#x,{bbox:Fs.#yo(this.#uo.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#go,{bbox:Fs.#yo(this.#lo.box,e),path:{d:this.#lo.toSVGPath()}})}const[n,s,r,a]=t.box;switch(this.rotation){case 0:this.x=n,this.y=s,this.width=r,this.height=a;break;case 90:{const[t,e]=this.parentDimensions;this.x=s,this.y=1-n,this.width=r*e/t,this.height=a*t/e;break}case 180:this.x=1-n,this.y=1-s,this.width=r,this.height=a;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-s,this.y=n,this.width=r*e/t,this.height=a*t/e;break}}const{firstPoint:o}=t;this.#Xa=[(o[0]-n)/r,(o[1]-s)/a];const{lastPoint:l}=this.#lo;this.#Ka=[(l[0]-n)/r,(l[1]-s)/a]}static initialize(t,e){be.initialize(t,e),Fs._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case O.HIGHLIGHT_COLOR:Fs._defaultColor=e;break;case O.HIGHLIGHT_THICKNESS:Fs._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Ka}get commentButtonPosition(){return this.#Xa}updateParams(t,e){switch(t){case O.HIGHLIGHT_COLOR:this.#Hr(e);break;case O.HIGHLIGHT_THICKNESS:this.#wo(e)}}static get defaultPropertiesToUpdate(){return[[O.HIGHLIGHT_COLOR,Fs._defaultColor],[O.HIGHLIGHT_THICKNESS,Fs._defaultThickness]]}get propertiesToUpdate(){return[[O.HIGHLIGHT_COLOR,this.color||Fs._defaultColor],[O.HIGHLIGHT_THICKNESS,this.#Ra||Fs._defaultThickness],[O.HIGHLIGHT_FREE,this.#po]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#x,{root:{fill:this.color,"fill-opacity":this.opacity}}),this.#s?.updateColor(this.color),super.onUpdatedColor()}#Hr(t){const e=(t,e)=>{this.color=t,this.opacity=e,this.onUpdatedColor()},i=this.color,n=this.opacity;this.addCommands({cmd:e.bind(this,t,Fs._defaultOpacity),undo:e.bind(this,i,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:O.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#wo(t){const e=this.#Ra,i=t=>{this.#Ra=t,this.#xo(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:O.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){if(this._uiManager.highlightColors){return[["colorPicker",this.#s=new $n({editor:this})]]}return super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#Ao())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Ao())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#_o(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#bo(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#_o():t&&(this.#bo(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#xo(t){this.#po&&(this.#fo({highlightOutlines:this.#uo.getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims(this.width,this.height))}#_o(){null!==this.#x&&this.parent&&(this.parent.drawLayer.remove(this.#x),this.#x=null,this.parent.drawLayer.remove(this.#go),this.#go=null)}#bo(t=this.parent){null===this.#x&&(({id:this.#x,clipPathId:this.#oo}=t.drawLayer.draw({bbox:this.#uo.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#po},path:{d:this.#uo.toSVGPath()}},!1,!0)),this.#go=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#po},bbox:this.#lo.box,path:{d:this.#lo.toSVGPath()}},this.#po),this.#do&&(this.#do.style.clipPath=this.#oo))}static#yo([t,e,i,n],s){switch(s){case 90:return[1-e-n,t,n,i];case 180:return[1-t-i,1-e-n,i,n];case 270:return[e,1-t-i,n,i]}return[t,e,i,n]}rotate(t){const{drawLayer:e}=this.parent;let i;this.#po?(t=(t-this.rotation+360)%360,i=Fs.#yo(this.#uo.box,t)):i=Fs.#yo([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#x,{bbox:i,root:{"data-main-rotation":t}}),e.updateProperties(this.#go,{bbox:Fs.#yo(this.#lo.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#ce&&(t.setAttribute("aria-label",this.#ce),t.setAttribute("role","mark")),this.#po?t.classList.add("free"):this.div.addEventListener("keydown",this.#So.bind(this),{signal:this._uiManager._signal});const e=this.#do=document.createElement("div");return t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#oo,this.setDims(this.width,this.height),oe(this,this.#do,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{hovered:!1}})}#So(t){Fs._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#Co(!0);break;case 1:case 3:this.#Co(!1)}}#Co(t){if(!this.#so)return;const e=window.getSelection();t?e.setPosition(this.#so,this.#ro):e.setPosition(this.#ho,this.#co)}select(){super.select(),this.#go&&this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#go&&(this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{selected:!1}}),this.#po||this.#Co(!1))}get _mustFixPosition(){return!this.#po}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#x,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#go,{rootClass:{hidden:!t}}))}#Ao(){return this.#po?this.rotation:0}#Eo(){if(this.#po)return null;const[t,e]=this.pageDimensions,[i,n]=this.pageTranslation,s=this.#ao,r=new Float32Array(8*s.length);let a=0;for(const{x:o,y:l,width:h,height:c}of s){const s=o*t+i,d=(1-l)*e+n;r[a]=r[a+4]=s,r[a+1]=r[a+3]=d,r[a+2]=r[a+6]=s+h*t,r[a+5]=r[a+7]=d-c*e,a+=8}return r}#To(t){return this.#uo.serialize(t,this.#Ao())}static startHighlighting(t,e,{target:i,x:n,y:s}){const{x:r,y:a,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,c=t.combinedSignal(h),d=e=>{h.abort(),this.#ko(t,e)};window.addEventListener("blur",d,{signal:c}),window.addEventListener("pointerup",d,{signal:c}),window.addEventListener("pointerdown",Wt,{capture:!0,passive:!1,signal:c}),window.addEventListener("contextmenu",$t,{signal:c}),i.addEventListener("pointermove",this.#Mo.bind(this,t),{signal:c}),this._freeHighlight=new Ls({x:n,y:s},[r,a,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#Mo(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#ko(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let n=null;if(t instanceof ws){const{data:{quadPoints:e,rect:i,rotation:s,id:r,color:a,opacity:o,popupRef:l,richText:h,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;n=t={annotationType:F.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:c?.str||null,creationDate:d,modificationDate:u}}else if(t instanceof ys){const{data:{inkLists:e,rect:i,rotation:s,id:r,color:a,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;n=t={annotationType:F.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:c?.str||null,creationDate:d,modificationDate:u}}const{color:s,quadPoints:r,inkLists:a,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Ct.makeHexColor(...s),l.opacity=o||1,a&&(l.#Ra=t.thickness),l._initialData=n,t.comment&&l.setCommentData(t);const[h,c]=l.pageDimensions,[d,u]=l.pageTranslation;if(r){const t=l.#ao=[];for(let e=0;e<r.length;e+=8)t.push({x:(r[e]-d)/h,y:1-(r[e+1]-u)/c,width:(r[e+2]-r[e])/h,height:(r[e+1]-r[e+5])/c});l.#vo(),l.#bo(),l.rotate(l.rotation)}else if(a){l.#po=!0;const t=a[0],i={x:t[0]-d,y:c-(t[1]-u)},n=new Ls(i,[0,0,h,c],1,l.#Ra/2,!0,.001);for(let e=0,s=t.length;e<s;e+=2)i.x=t[e]-d,i.y=c-(t[e+1]-u),n.add(i);const{id:s,clipPathId:r}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:n.toSVGPath()}},!0,!0);l.#fo({highlightOutlines:n.getOutlines(),highlightId:s,clipPathId:r}),l.#bo(),l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=be._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);return Object.assign(i,{color:e,opacity:this.opacity,thickness:this.#Ra,quadPoints:this.#Eo(),outlines:this.#To(i.rect)}),this.addComment(i),this.annotationElementId&&!this.#xa(i)?null:(i.id=this.annotationElementId,i)}#xa(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,i)=>t!==e[i])}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}}class Os{#Do=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#Do[t]=e}toSVGProperties(){const t=this.#Do;return this.#Do=Object.create(null),{root:t}}reset(){this.#Do=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){ht("Not implemented")}}class Ns extends be{#Po=null;#Io;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#Ro=null;static#Lo=null;static#Bo=null;static#Fo=NaN;static#Oo=null;static#No=null;static#Uo=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#Io=t.mustBeCommitted||!1,this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}_addOutlines(t){t.drawOutlines&&(this.#jo(t),this.#bo())}#jo({drawOutlines:t,drawId:e,drawingOptions:i}){this.#Po=t,this._drawingOptions||=i,this.annotationElementId||this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`),e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#zo(t,this.parent),this.#Ho(t.box)}#zo(t,e){const{id:i}=e.drawLayer.draw(Ns._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[n,s]of Object.entries(e))i.has(n)?Object.assign(t[n],s):t[n]=s;return t}static getDefaultDrawingOptions(t){ht("Not implemented")}static get typesMap(){ht("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e),this._currentParent&&(Ns.#Ro.updateProperty(i,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,n]of this.typesMap)t.push([i,e[n]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,n]of this.constructor.typesMap)t.push([i,e[n]]);return t}_updateProperty(t,e,i){const n=this._drawingOptions,s=n[e],r=i=>{n.updateProperty(e,i);const s=this.#Po.updateProperty(e,i);s&&this.#Ho(s),this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties()),t===this.colorType&&this.onUpdatedColor()};this.addCommands({cmd:r.bind(this,i),undo:r.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,Ns._mergeSVGProperties(this.#Po.getPathResizingSVGProperties(this.#$o()),{bbox:this.#Wo()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,Ns._mergeSVGProperties(this.#Po.getPathResizedSVGProperties(this.#$o()),{bbox:this.#Wo()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Wo()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,Ns._mergeSVGProperties(this.#Po.getPathTranslatedSVGProperties(this.#$o(),this.parentDimensions),{bbox:this.#Wo()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#Io&&(this.#Io=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#_o(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#bo(),this.#Ho(this.#Po.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#_o()):t&&(this._uiManager.addShouldRescale(this),this.#bo(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#_o(){null!==this._drawId&&this.parent&&(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#bo(t=this.parent){null!==this._drawId&&this.parent===t||(null===this._drawId?(this._drawingOptions.updateAll(),this._drawId=this.#zo(this.#Po,t)):this.parent.drawLayer.updateParent(this._drawId,t.drawLayer))}#Vo([t,e,i,n]){const{parentDimensions:[s,r],rotation:a}=this;switch(a){case 90:return[e,1-t,i*(r/s),n*(s/r)];case 180:return[1-t,1-e,i,n];case 270:return[1-e,t,i*(r/s),n*(s/r)];default:return[t,e,i,n]}}#$o(){const{x:t,y:e,width:i,height:n,parentDimensions:[s,r],rotation:a}=this;switch(a){case 90:return[1-e,t,i*(s/r),n*(r/s)];case 180:return[1-t,1-e,i,n];case 270:return[e,1-t,i*(s/r),n*(r/s)];default:return[t,e,i,n]}}#Ho(t){[this.x,this.y,this.width,this.height]=this.#Vo(t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#Wo(){const{x:t,y:e,width:i,height:n,rotation:s,parentRotation:r,parentDimensions:[a,o]}=this;switch((4*s+r)/90){case 1:return[1-e-n,t,n,i];case 2:return[1-t-i,1-e-n,i,n];case 3:return[e,1-t-i,n,i];case 4:return[t,e-i*(a/o),n*(o/a),i*(a/o)];case 5:return[1-e,t,i*(a/o),n*(o/a)];case 6:return[1-t-n*(o/a),1-e,n*(o/a),i*(a/o)];case 7:return[e-i*(a/o),1-t-n*(o/a),i*(a/o),n*(o/a)];case 8:return[t-i,e-n,i,n];case 9:return[1-e,t-i,n,i];case 10:return[1-t,1-e,i,n];case 11:return[e-n,1-t,n,i];case 12:return[t-n*(o/a),e,n*(o/a),i*(a/o)];case 13:return[1-e-i*(a/o),t-n*(o/a),i*(a/o),n*(o/a)];case 14:return[1-t,1-e-i*(a/o),n*(o/a),i*(a/o)];case 15:return[e,1-t,i*(a/o),n*(o/a)];default:return[t,e,i,n]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,Ns._mergeSVGProperties({bbox:this.#Wo()},this.#Po.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Ho(this.#Po.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const i=super.render();i.classList.add("draw");const n=document.createElement("div");return i.append(n),n.setAttribute("aria-hidden","true"),n.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),i}static createDrawerInstance(t,e,i,n,s){ht("Not implemented")}static startDrawing(t,e,i,n){const{target:s,offsetX:r,offsetY:a,pointerId:o,pointerType:l}=n;if(Ns.#Oo&&Ns.#Oo!==l)return;const{viewport:{rotation:h}}=t,{width:c,height:d}=s.getBoundingClientRect(),u=Ns.#Lo=new AbortController,p=t.combinedSignal(u);Ns.#Fo||=o,Ns.#Oo??=l,window.addEventListener("pointerup",t=>{Ns.#Fo===t.pointerId?this._endDraw(t):Ns.#No?.delete(t.pointerId)},{signal:p}),window.addEventListener("pointercancel",t=>{Ns.#Fo===t.pointerId?this._currentParent.endDrawingSession():Ns.#No?.delete(t.pointerId)},{signal:p}),window.addEventListener("pointerdown",t=>{Ns.#Oo===t.pointerType&&((Ns.#No||=new Set).add(t.pointerId),Ns.#Ro.isCancellable()&&(Ns.#Ro.removeLastElement(),Ns.#Ro.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",$t,{signal:p}),s.addEventListener("pointermove",this._drawMove.bind(this),{signal:p}),s.addEventListener("touchmove",t=>{t.timeStamp===Ns.#Uo&&Wt(t)},{signal:p}),t.toggleDrawing(),e._editorUndoBar?.hide(),Ns.#Ro?t.drawLayer.updateProperties(this._currentDrawId,Ns.#Ro.startNew(r,a,c,d,h)):(e.updateUIForDefaultProperties(this),Ns.#Ro=this.createDrawerInstance(r,a,c,d,h),Ns.#Bo=this.getDefaultDrawingOptions(),this._currentParent=t,({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(Ns.#Bo.toSVGProperties(),Ns.#Ro.defaultSVGProperties),!0,!1)))}static _drawMove(t){if(Ns.#Uo=-1,!Ns.#Ro)return;const{offsetX:e,offsetY:i,pointerId:n}=t;Ns.#Fo===n&&(Ns.#No?.size>=1?this._endDraw(t):(this._currentParent.drawLayer.updateProperties(this._currentDrawId,Ns.#Ro.add(e,i)),Ns.#Uo=t.timeStamp,Wt(t)))}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,Ns.#Ro=null,Ns.#Bo=null,Ns.#Oo=null,Ns.#Uo=NaN),Ns.#Lo&&(Ns.#Lo.abort(),Ns.#Lo=null,Ns.#Fo=NaN,Ns.#No=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,Ns.#Ro.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const t=Ns.#Ro,i=this._currentDrawId,n=t.getLastElement();return void e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:O.DRAW_STEP})}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(O.DRAW_STEP),!Ns.#Ro.isEmpty()){const{pageDimensions:[i,n],scale:s}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:Ns.#Ro.getOutlines(i*s,n*s,s,this._INNER_MARGIN),drawingOptions:Ns.#Bo,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,i,n,s,r){ht("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:n,pageHeight:s,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,n,s,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);return l.createDrawingOptions(t),l.#jo({drawOutlines:o}),l.#bo(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,i]=this.pageTranslation,[n,s]=this.pageDimensions;return this.#Po.serialize([e,i,n,s],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class Us{#Ta=new Float64Array(6);#Kr;#Go;#ns;#Ra;#La;#qo="";#Xo=0;#no=new js;#Ko;#Yo;constructor(t,e,i,n,s,r){this.#Ko=i,this.#Yo=n,this.#ns=s,this.#Ra=r,[t,e]=this.#Jo(t,e);const a=this.#Kr=[NaN,NaN,NaN,NaN,t,e];this.#La=[t,e],this.#Go=[{line:a,points:this.#La}],this.#Ta.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#Ra=e)}#Jo(t,e){return Ms._normalizePoint(t,e,this.#Ko,this.#Yo,this.#ns)}isEmpty(){return!this.#Go||0===this.#Go.length}isCancellable(){return this.#La.length<=10}add(t,e){[t,e]=this.#Jo(t,e);const[i,n,s,r]=this.#Ta.subarray(2,6),a=t-s,o=e-r;return Math.hypot(this.#Ko*a,this.#Yo*o)<=2?null:(this.#La.push(t,e),isNaN(i)?(this.#Ta.set([s,r,t,e],2),this.#Kr.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#Ta[0])&&this.#Kr.splice(6,6),this.#Ta.set([i,n,s,r,t,e],0),this.#Kr.push(...Ms.createBezierPoints(i,n,s,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const i=this.add(t,e);return i||(2===this.#La.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,n,s){this.#Ko=i,this.#Yo=n,this.#ns=s,[t,e]=this.#Jo(t,e);const r=this.#Kr=[NaN,NaN,NaN,NaN,t,e];this.#La=[t,e];const a=this.#Go.at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),this.#Go.push({line:r,points:this.#La}),this.#Ta.set(r,0),this.#Xo=0,this.toSVGPath(),null}getLastElement(){return this.#Go.at(-1)}setLastElement(t){return this.#Go?(this.#Go.push(t),this.#Kr=t.line,this.#La=t.points,this.#Xo=0,{path:{d:this.toSVGPath()}}):this.#no.setLastElement(t)}removeLastElement(){if(!this.#Go)return this.#no.removeLastElement();this.#Go.pop(),this.#qo="";for(let t=0,e=this.#Go.length;t<e;t++){const{line:e,points:i}=this.#Go[t];this.#Kr=e,this.#La=i,this.#Xo=0,this.toSVGPath()}return{path:{d:this.#qo}}}toSVGPath(){const t=Ms.svgRound(this.#Kr[4]),e=Ms.svgRound(this.#Kr[5]);if(2===this.#La.length)return this.#qo=`${this.#qo} M ${t} ${e} Z`,this.#qo;if(this.#La.length<=6){const i=this.#qo.lastIndexOf("M");this.#qo=`${this.#qo.slice(0,i)} M ${t} ${e}`,this.#Xo=6}if(4===this.#La.length){const t=Ms.svgRound(this.#Kr[10]),e=Ms.svgRound(this.#Kr[11]);return this.#qo=`${this.#qo} L ${t} ${e}`,this.#Xo=12,this.#qo}const i=[];0===this.#Xo&&(i.push(`M ${t} ${e}`),this.#Xo=6);for(let t=this.#Xo,e=this.#Kr.length;t<e;t+=6){const[e,n,s,r,a,o]=this.#Kr.slice(t,t+6).map(Ms.svgRound);i.push(`C${e} ${n} ${s} ${r} ${a} ${o}`)}return this.#qo+=i.join(" "),this.#Xo=this.#Kr.length,this.#qo}getOutlines(t,e,i,n){const s=this.#Go.at(-1);return s.line=new Float32Array(s.line),s.points=new Float32Array(s.points),this.#no.build(this.#Go,t,e,i,this.#ns,this.#Ra,n),this.#Ta=null,this.#Kr=null,this.#Go=null,this.#qo=null,this.#no}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class js extends Ms{#Va;#Qo=0;#Sa;#Go;#Ko;#Yo;#Zo;#ns;#Ra;build(t,e,i,n,s,r,a){this.#Ko=e,this.#Yo=i,this.#Zo=n,this.#ns=s,this.#Ra=r,this.#Sa=a??0,this.#Go=t,this.#tl()}get thickness(){return this.#Ra}setLastElement(t){return this.#Go.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#Go.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#Go)if(t.push(`M${Ms.svgRound(e[4])} ${Ms.svgRound(e[5])}`),6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Ms.svgRound(e[10])} ${Ms.svgRound(e[11])}`);else for(let i=6,n=e.length;i<n;i+=6){const[n,s,r,a,o,l]=e.subarray(i,i+6).map(Ms.svgRound);t.push(`C${n} ${s} ${r} ${a} ${o} ${l}`)}else t.push("Z");return t.join("")}serialize([t,e,i,n],s){const r=[],a=[],[o,l,h,c]=this.#el();let d,u,p,g,m,f,b,v,y;switch(this.#ns){case 0:y=Ms._rescale,d=t,u=e+n,p=i,g=-n,m=t+o*i,f=e+(1-l-c)*n,b=t+(o+h)*i,v=e+(1-l)*n;break;case 90:y=Ms._rescaleAndSwap,d=t,u=e,p=i,g=n,m=t+l*i,f=e+o*n,b=t+(l+c)*i,v=e+(o+h)*n;break;case 180:y=Ms._rescale,d=t+i,u=e,p=-i,g=n,m=t+(1-o-h)*i,f=e+l*n,b=t+(1-o)*i,v=e+(l+c)*n;break;case 270:y=Ms._rescaleAndSwap,d=t+i,u=e+n,p=-i,g=-n,m=t+(1-l-c)*i,f=e+(1-o-h)*n,b=t+(1-l)*i,v=e+(1-o)*n}for(const{line:t,points:e}of this.#Go)r.push(y(t,d,u,p,g,s?new Array(t.length):null)),a.push(y(e,d,u,p,g,s?new Array(e.length):null));return{lines:r,points:a,rect:[m,f,b,v]}}static deserialize(t,e,i,n,s,{paths:{lines:r,points:a},rotation:o,thickness:l}){const h=[];let c,d,u,p,g;switch(o){case 0:g=Ms._rescale,c=-t/i,d=e/n+1,u=1/i,p=-1/n;break;case 90:g=Ms._rescaleAndSwap,c=-e/n,d=-t/i,u=1/n,p=1/i;break;case 180:g=Ms._rescale,c=t/i+1,d=-e/n,u=-1/i,p=1/n;break;case 270:g=Ms._rescaleAndSwap,c=e/n+1,d=t/i+1,u=-1/n,p=-1/i}if(!r){r=[];for(const t of a){const e=t.length;if(2===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const i=new Float32Array(3*(e-2));r.push(i);let[n,s,a,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,n,s],0);for(let r=4;r<e;r+=2){const e=t[r],l=t[r+1];i.set(Ms.createBezierPoints(n,s,a,o,e,l),3*(r-2)),[n,s,a,o]=[a,o,e,l]}}}for(let t=0,e=r.length;t<e;t++)h.push({line:g(r[t].map(t=>t??NaN),c,d,u,p),points:g(a[t].map(t=>t??NaN),c,d,u,p)});const m=new this.prototype.constructor;return m.build(h,i,n,1,o,l,s),m}#il(t=this.#Ra){const e=this.#Sa+t/2*this.#Zo;return this.#ns%180==0?[e/this.#Ko,e/this.#Yo]:[e/this.#Yo,e/this.#Ko]}#el(){const[t,e,i,n]=this.#Va,[s,r]=this.#il(0);return[t+s,e+r,i-2*s,n-2*r]}#tl(){const t=this.#Va=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Go){if(e.length<=12){for(let i=4,n=e.length;i<n;i+=6)Ct.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],n=e[5];for(let s=6,r=e.length;s<r;s+=6){const[r,a,o,l,h,c]=e.subarray(s,s+6);Ct.bezierBoundingBox(i,n,r,a,o,l,h,c,t),i=h,n=c}}const[e,i]=this.#il();t[0]=Dt(t[0]-e,0,1),t[1]=Dt(t[1]-i,0,1),t[2]=Dt(t[2]+e,0,1),t[3]=Dt(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#Va}updateProperty(t,e){return"stroke-width"===t?this.#wo(e):null}#wo(t){const[e,i]=this.#il();this.#Ra=t;const[n,s]=this.#il(),[r,a]=[n-e,s-i],o=this.#Va;return o[0]-=r,o[1]-=a,o[2]+=2*r,o[3]+=2*a,o}updateParentDimensions([t,e],i){const[n,s]=this.#il();this.#Ko=t,this.#Yo=e,this.#Zo=i;const[r,a]=this.#il(),o=r-n,l=a-s,h=this.#Va;return h[0]-=o,h[1]-=l,h[2]+=2*o,h[3]+=2*l,h}updateRotation(t){return this.#Qo=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#Va.map(Ms.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#Va;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Ms.svgRound(t)} ${Ms.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#Va;let i=0,n=0,s=0,r=0,a=0,o=0;switch(this.#Qo){case 90:n=e/t,s=-t/e,a=t;break;case 180:i=-1,r=-1,a=t,o=e;break;case 270:n=-e/t,s=t/e,o=e;break;default:return""}return`matrix(${i} ${n} ${s} ${r} ${Ms.svgRound(a)} ${Ms.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,n]){const[s,r]=this.#il(),[a,o,l,h]=this.#Va;if(Math.abs(l-s)<=Ms.PRECISION||Math.abs(h-r)<=Ms.PRECISION){const s=t+i/2-(a+l/2),r=e+n/2-(o+h/2);return{path:{"transform-origin":`${Ms.svgRound(t)} ${Ms.svgRound(e)}`,transform:`${this.rotationTransform} translate(${s} ${r})`}}}const c=(i-2*s)/(l-2*s),d=(n-2*r)/(h-2*r),u=l/i,p=h/n;return{path:{"transform-origin":`${Ms.svgRound(a)} ${Ms.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Ms.svgRound(s)} ${Ms.svgRound(r)}) scale(${c} ${d}) translate(${Ms.svgRound(-s)} ${Ms.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,i,n]){const[s,r]=this.#il(),a=this.#Va,[o,l,h,c]=a;if(a[0]=t,a[1]=e,a[2]=i,a[3]=n,Math.abs(h-s)<=Ms.PRECISION||Math.abs(c-r)<=Ms.PRECISION){const s=t+i/2-(o+h/2),r=e+n/2-(l+c/2);for(const{line:t,points:e}of this.#Go)Ms._translate(t,s,r,t),Ms._translate(e,s,r,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Ms.svgRound(t)} ${Ms.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(i-2*s)/(h-2*s),u=(n-2*r)/(c-2*r),p=-d*(o+s)+t+s,g=-u*(l+r)+e+r;if(1!==d||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#Go)Ms._rescale(t,p,g,d,u,t),Ms._rescale(e,p,g,d,u,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Ms.svgRound(t)} ${Ms.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[n,s]=i,r=this.#Va,a=t-r[0],o=e-r[1];if(this.#Ko===n&&this.#Yo===s)for(const{line:t,points:e}of this.#Go)Ms._translate(t,a,o,t),Ms._translate(e,a,o,e);else{const t=this.#Ko/n,e=this.#Yo/s;this.#Ko=n,this.#Yo=s;for(const{line:i,points:n}of this.#Go)Ms._rescale(i,a,o,t,e,i),Ms._rescale(n,a,o,t,e,n);r[2]*=t,r[3]*=e}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Ms.svgRound(t)} ${Ms.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#Va;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Ms.svgRound(t[0])} ${Ms.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class zs extends Os{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:be._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){"stroke-width"===t&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new zs(this._viewParameters);return t.updateAll(this),t}}class Hs extends Ns{static _type="ink";static _editorType=F.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){be.initialize(t,e),this._defaultDrawingOptions=new zs(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return pt(this,"typesMap",new Map([[O.INK_THICKNESS,"stroke-width"],[O.INK_COLOR,"stroke"],[O.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,n,s){return new Us(t,e,i,n,s,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,n,s,r){return js.deserialize(t,e,i,n,s,r)}static async deserialize(t,e,i){let n=null;if(t instanceof ys){const{data:{inkLists:e,rect:i,rotation:s,id:r,color:a,opacity:o,borderStyle:{rawWidth:l},popupRef:h,richText:c,contentsObj:d,creationDate:u,modificationDate:p},parent:{page:{pageNumber:g}}}=t;n=t={annotationType:F.INK,color:Array.from(a),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:h,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const s=await super.deserialize(t,e,i);return s._initialData=n,t.comment&&s.setCommentData(t),s}get toolbarButtons(){return this._colorPicker||=new Wn(this),[["colorPicker",this._colorPicker]]}get colorType(){return O.INK_COLOR}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:i}){this._drawingOptions=Hs.getDefaultDrawingOptions({stroke:Ct.makeHexColor(...t),"stroke-width":e,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":s,"stroke-width":r}}=this,a=Object.assign(super.serialize(t),{color:be._colorManager.convert(n),opacity:s,thickness:r,paths:{lines:e,points:i}});return this.addComment(a),t?(a.isCopy=!0,a):this.annotationElementId&&!this.#xa(a)?null:(a.id=this.annotationElementId,a)}#xa(t){const{color:e,thickness:i,opacity:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((t,i)=>t!==e[i])||t.thickness!==i||t.opacity!==n||t.pageIndex!==s}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:e,rect:i}=this.serializeDraw(!1);return t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment}),null}}class $s extends js{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}class Ws{static#nl={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#sl(t,e,i,n){return n-=e,0===(i-=t)?n>0?0:4:1===i?n+6:2-n}static#rl=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#al(t,e,i,n,s,r,a){const o=this.#sl(i,n,s,r);for(let s=0;s<8;s++){const r=(-s+o-a+16)%8;if(0!==t[(i+this.#rl[2*r])*e+(n+this.#rl[2*r+1])])return r}return-1}static#ol(t,e,i,n,s,r,a){const o=this.#sl(i,n,s,r);for(let s=0;s<8;s++){const r=(s+o+a+16)%8;if(0!==t[(i+this.#rl[2*r])*e+(n+this.#rl[2*r+1])])return r}return-1}static#ll(t,e,i,n){const s=t.length,r=new Int32Array(s);for(let e=0;e<s;e++)r[e]=t[e]<=n?1:0;for(let t=1;t<i-1;t++)r[t*e]=r[t*e+e-1]=0;for(let t=0;t<e;t++)r[t]=r[e*i-1-t]=0;let a,o=1;const l=[];for(let t=1;t<i-1;t++){a=1;for(let i=1;i<e-1;i++){const n=t*e+i,s=r[n];if(0===s)continue;let h=t,c=i;if(1===s&&0===r[n-1])o+=1,c-=1;else{if(!(s>=1&&0===r[n+1])){1!==s&&(a=Math.abs(s));continue}o+=1,c+=1,s>1&&(a=s)}const d=[i,t],u=c===i+1,p={isHole:u,points:d,id:o,parent:0};let g;l.push(p);for(const t of l)if(t.id===a){g=t;break}g?g.isHole?p.parent=u?g.parent:a:p.parent=u?a:g.parent:p.parent=u?a:0;const m=this.#al(r,e,t,i,h,c,0);if(-1===m){r[n]=-o,1!==r[n]&&(a=Math.abs(r[n]));continue}let f=this.#rl[2*m],b=this.#rl[2*m+1];const v=t+f,y=i+b;h=v,c=y;let w=t,x=i;for(;;){const s=this.#ol(r,e,w,x,h,c,1);f=this.#rl[2*s],b=this.#rl[2*s+1];const l=w+f,u=x+b;d.push(u,l);const p=w*e+x;if(0===r[p+1]?r[p]=-o:1===r[p]&&(r[p]=o),l===t&&u===i&&w===v&&x===y){1!==r[n]&&(a=Math.abs(r[n]));break}h=w,c=x,w=l,x=u}}}return l}static#hl(t,e,i,n){if(i-e<=4){for(let s=e;s<i-2;s+=2)n.push(t[s],t[s+1]);return}const s=t[e],r=t[e+1],a=t[i-4]-s,o=t[i-3]-r,l=Math.hypot(a,o),h=a/l,c=o/l,d=h*r-c*s,u=o/a,p=1/l,g=Math.atan(u),m=Math.cos(g),f=Math.sin(g),b=p*(Math.abs(m)+Math.abs(f)),v=p*(1-b+b**2),y=Math.max(Math.atan(Math.abs(f+m)*v),Math.atan(Math.abs(f-m)*v));let w=0,x=e;for(let n=e+2;n<i-2;n+=2){const e=Math.abs(d-h*t[n+1]+c*t[n]);e>w&&(x=n,w=e)}w>(l*y)**2?(this.#hl(t,e,x+2,n),this.#hl(t,x,i,n)):n.push(s,r)}static#cl(t){const e=[],i=t.length;return this.#hl(t,0,i,e),e.push(t[i-2],t[i-1]),e.length<=4?null:e}static#dl(t,e,i,n,s,r){const a=new Float32Array(r**2),o=-2*n**2,l=r>>1;for(let t=0;t<r;t++){const e=(t-l)**2;for(let i=0;i<r;i++)a[t*r+i]=Math.exp((e+(i-l)**2)/o)}const h=new Float32Array(256),c=-2*s**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/c);const d=t.length,u=new Uint8Array(d),p=new Uint32Array(256);for(let n=0;n<i;n++)for(let s=0;s<e;s++){const o=n*e+s,c=t[o];let d=0,g=0;for(let o=0;o<r;o++){const u=n+o-l;if(!(u<0||u>=i))for(let i=0;i<r;i++){const n=s+i-l;if(n<0||n>=e)continue;const p=t[u*e+n],m=a[o*r+i]*h[Math.abs(p-c)];d+=p*m,g+=m}}p[u[o]=Math.round(d/g)]++}return[u,p]}static#ul(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#pl(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let n=-1/0,s=1/0;for(let e=0,r=i.length;e<r;e++){const r=i[e]=t[e<<2];n=Math.max(n,r),s=Math.min(s,r)}const r=255/(n-s);for(let t=0,e=i.length;t<e;t++)i[t]=(i[t]-s)*r;return i}static#gl(t){let e,i=-1/0,n=-1/0;const s=t.findIndex(t=>0!==t);let r=s,a=s;for(e=s;e<256;e++){const s=t[e];s>i&&(e-r>n&&(n=e-r,a=e-1),i=s,r=e)}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#ml(t){const e=t,{width:i,height:n}=t,{maxDim:s}=this.#nl;let r=i,a=n;if(i>s||n>s){let o=i,l=n,h=Math.log2(Math.max(i,n)/s);const c=Math.floor(h);h=h===c?c-1:c;for(let i=0;i<h;i++){r=Math.ceil(o/2),a=Math.ceil(l/2);const i=new OffscreenCanvas(r,a);i.getContext("2d").drawImage(t,0,0,o,l,0,0,r,a),o=r,l=a,t!==e&&t.close(),t=i.transferToImageBitmap()}const d=Math.min(s/r,s/a);r=Math.round(r*d),a=Math.round(a*d)}const o=new OffscreenCanvas(r,a).getContext("2d",{willReadFrequently:!0});o.fillStyle="white",o.fillRect(0,0,r,a),o.filter="grayscale(1)",o.drawImage(t,0,0,t.width,t.height,0,0,r,a);const l=o.getImageData(0,0,r,a).data;return[this.#pl(l),r,a]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:n},s,r,a,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1});const c=h.font=`${i} ${n} 200px ${e}`,{actualBoundingBoxLeft:d,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=h.measureText(t),v=1.5,y=Math.ceil(Math.max(Math.abs(d)+Math.abs(u)||0,b)*v),w=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*v);l=new OffscreenCanvas(y,w),h=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),h.font=c,h.filter="grayscale(1)",h.fillStyle="white",h.fillRect(0,0,y,w),h.fillStyle="black",h.fillText(t,.5*y/2,1.5*w/2);const x=this.#pl(h.getImageData(0,0,y,w).data),A=this.#ul(x),_=this.#gl(A),S=this.#ll(x,y,w,_);return this.processDrawnLines({lines:{curves:S,width:y,height:w},pageWidth:s,pageHeight:r,rotation:a,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,n,s){const[r,a,o]=this.#ml(t),[l,h]=this.#dl(r,a,o,Math.hypot(a,o)*this.#nl.sigmaSFactor,this.#nl.sigmaR,this.#nl.kernelSize),c=this.#gl(h),d=this.#ll(l,a,o,c);return this.processDrawnLines({lines:{curves:d,width:a,height:o},pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:r,areContours:a}){n%180!=0&&([e,i]=[i,e]);const{curves:o,width:l,height:h}=t,c=t.thickness??0,d=[],u=Math.min(e/l,i/h),p=u/e,g=u/i,m=[];for(const{points:t}of o){const e=r?this.#cl(t):t;if(!e)continue;m.push(e);const i=e.length,n=new Float32Array(i),s=new Float32Array(3*(2===i?2:i-2));if(d.push({line:s,points:n}),2===i){n[0]=e[0]*p,n[1]=e[1]*g,s.set([NaN,NaN,NaN,NaN,n[0],n[1]],0);continue}let[a,o,l,h]=e;a*=p,o*=g,l*=p,h*=g,n.set([a,o,l,h],0),s.set([NaN,NaN,NaN,NaN,a,o],0);for(let t=4;t<i;t+=2){const i=n[t]=e[t]*p,r=n[t+1]=e[t+1]*g;s.set(Ms.createBezierPoints(a,o,l,h,i,r),3*(t-2)),[a,o,l,h]=[l,h,i,r]}}if(0===d.length)return null;const f=a?new $s:new js;return f.build(d,e,i,1,n,a?0:c,s),{outline:f,newCurves:m,areContours:a,thickness:c,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:n,height:s}){let r,a=1/0,o=-1/0,l=0;for(const e of t){l+=e.length;for(let t=2,i=e.length;t<i;t++){const i=e[t]-e[t-2];a=Math.min(a,i),o=Math.max(o,i)}}r=a>=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,c=8+3*h,d=new Uint32Array(c);let u=0;d[u++]=c*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*r.BYTES_PER_ELEMENT,d[u++]=0,d[u++]=n,d[u++]=s,d[u++]=e?0:1,d[u++]=Math.max(0,Math.floor(i??0)),d[u++]=h,d[u++]=r.BYTES_PER_ELEMENT;for(const e of t)d[u++]=e.length-2,d[u++]=e[0],d[u++]=e[1];const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(d);const m=r.prototype.constructor;for(const e of t){const t=new m(e.length-2);for(let i=2,n=e.length;i<n;i++)t[i-2]=e[i]-e[i-2];g.write(t)}g.close();const f=await new Response(p.readable).arrayBuffer();return Pt(new Uint8Array(f))}static async decompressSignature(t){try{const i=(e=t,Uint8Array.fromBase64?Uint8Array.fromBase64(e):At(atob(e))),{readable:n,writable:s}=new DecompressionStream("deflate-raw"),r=s.getWriter();await r.ready,r.write(i).then(async()=>{await r.ready,await r.close()}).catch(()=>{});let a=null,o=0;for await(const t of n)a||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),a.set(t,o),o+=t.length;const l=new Uint32Array(a.buffer,0,a.length>>2),h=l[1];if(0!==h)throw new Error(`Invalid version: ${h}`);const c=l[2],d=l[3],u=0===l[4],p=l[5],g=l[6],m=l[7],f=[],b=(8+3*g)*Uint32Array.BYTES_PER_ELEMENT;let v;switch(m){case Int8Array.BYTES_PER_ELEMENT:v=new Int8Array(a.buffer,b);break;case Int16Array.BYTES_PER_ELEMENT:v=new Int16Array(a.buffer,b);break;case Int32Array.BYTES_PER_ELEMENT:v=new Int32Array(a.buffer,b)}o=0;for(let t=0;t<g;t++){const e=l[3*t+8],i=new Float32Array(e+2);f.push(i);for(let e=0;e<2;e++)i[e]=l[3*t+8+e+1];for(let t=0;t<e;t++)i[t+2]=i[t]+v[o++]}return{areContours:u,thickness:p,outlines:f,width:c,height:d}}catch(t){return lt(`decompressSignature: ${t}`),null}var e}}class Vs extends Os{constructor(){super(),super.updateProperties({fill:be._defaultLineColor,"stroke-width":0})}clone(){const t=new Vs;return t.updateAll(this),t}}class Gs extends zs{constructor(t){super(t),super.updateProperties({stroke:be._defaultLineColor,"stroke-width":1})}clone(){const t=new Gs(this._viewParameters);return t.updateAll(this),t}}class qs extends Ns{#fl=!1;#bl=null;#vl=null;#yl=null;static _type="signature";static _editorType=F.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#vl=t.signatureData||null,this.#bl=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){be.initialize(t,e),this._defaultDrawingOptions=new Vs,this._defaultDrawnSignatureOptions=new Gs(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return pt(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#bl}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:i}=this;if(i&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),null===this._drawId)if(this.#vl){const{lines:t,mustSmooth:e,areContours:i,description:n,uuid:s,heightInPage:r}=this.#vl,{rawDims:{pageWidth:a,pageHeight:o},rotation:l}=this.parent.viewport,h=Ws.processDrawnLines({lines:t,pageWidth:a,pageHeight:o,rotation:l,innerMargin:qs._INNER_MARGIN,mustSmooth:e,areContours:i});this.addSignature(h,r,n,s)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#bl||""}));return i&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#yl=t,this.addEditToolbar()}getUuid(){return this.#yl}get description(){return this.#bl}set description(t){this.#bl=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:i,width:n,height:s}=this.#vl,r=Math.max(n,s);return{areContours:e,outline:Ws.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:n,height:s},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,i,n){const{x:s,y:r}=this,{outline:a}=this.#vl=t;let o;this.#fl=a instanceof $s,this.description=i,this.#fl?o=qs.getDefaultDrawingOptions():(o=qs._defaultDrawnSignatureOptions.clone(),o.updateProperties({"stroke-width":a.thickness})),this._addOutlines({drawOutlines:a,drawingOptions:o});const[,l]=this.pageDimensions;let h=e/l;h=h>=1?.5:h,this.width*=h/this.height,this.width>=1&&(h*=.9/this.width,this.width=.9),this.height=h,this.setDims(),this.x=s,this.y=r,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(n),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!n,hasDescription:!!i}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return Ws.process(t,e,i,n,qs._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:n},rotation:s}=this.parent.viewport;return Ws.extractContoursFromText(t,e,i,n,s,qs._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return Ws.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:qs._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=qs.getDefaultDrawingOptions():(this._drawingOptions=qs._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":n}}=this,s=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#fl,color:[0,0,0],thickness:this.#fl?0:n});return this.addComment(s),t?(s.paths={lines:e,points:i},s.uuid=this.#yl,s.isCopy=!0):s.lines=e,this.#bl&&(s.accessibilityData={type:"Figure",alt:this.#bl}),s}static deserializeDraw(t,e,i,n,s,r){return r.areContours?$s.deserialize(t,e,i,n,s,r):js.deserialize(t,e,i,n,s,r)}static async deserialize(t,e,i){const n=await super.deserialize(t,e,i);return n.#fl=t.areContours,n.description=t.accessibilityData?.alt||"",n.#yl=t.uuid,n}}class Xs extends be{#wl=null;#xl=null;#Al=null;#_l=null;#Sl=null;#Cl="";#El=null;#Tl=!1;#kl=null;#Ml=!1;#Dl=!1;static _type="stamp";static _editorType=F.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#_l=t.bitmapUrl,this.#Sl=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){be.initialize(t,e)}static isHandlingMimeForPasting(t){return Jt.includes(t)}static paste(t,e){e.pasteEditor({mode:F.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#Pl(t,e=!1){t?(this.#wl=t.bitmap,e||(this.#xl=t.id,this.#Ml=t.isSvg),t.file&&(this.#Cl=t.file.name),this.#Il()):this.remove()}#Rl(){if(this.#Al=null,this._uiManager.enableWaiting(!1),this.#El)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#wl)this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#wl){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:n,width:s,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await i.guess({name:"altText",request:{data:n,width:s,height:r,channels:n.length/(s*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const o=a.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#Ll(){if(this.#xl)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#xl).then(t=>this.#Pl(t,!0)).finally(()=>this.#Rl());if(this.#_l){const t=this.#_l;return this.#_l=null,this._uiManager.enableWaiting(!0),void(this.#Al=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#Pl(t)).finally(()=>this.#Rl()))}if(this.#Sl){const t=this.#Sl;return this.#Sl=null,this._uiManager.enableWaiting(!0),void(this.#Al=this._uiManager.imageManager.getFromFile(t).then(t=>this.#Pl(t)).finally(()=>this.#Rl()))}const t=document.createElement("input");t.type="file",t.accept=Jt.join(",");const e=this._uiManager._signal;this.#Al=new Promise(i=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#Pl(e)}else this.remove();i()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:e})}).finally(()=>this.#Rl()),t.click()}remove(){this.#xl&&(this.#wl=null,this._uiManager.imageManager.deleteId(this.#xl),this.#El?.remove(),this.#El=null,this.#kl&&(clearTimeout(this.#kl),this.#kl=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#xl&&null===this.#El&&this.#Ll(),this.isAttachedToDOM||this.parent.add(this))):this.#xl&&this.#Ll()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#Al||this.#wl||this.#_l||this.#Sl||this.#xl||this.#Tl)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#Tl||(this.#wl?this.#Il():this.#Ll()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:i,bitmap:n}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(this.#xl=i,n&&(this.#wl=n),this.#Tl=!1,this.#Il())}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#kl&&clearTimeout(this.#kl);this.#kl=setTimeout(()=>{this.#kl=null,this.#Bl()},200)}#Il(){const{div:t}=this;let{width:e,height:i}=this.#wl;const[n,s]=this.pageDimensions,r=.75;if(this.width)e=this.width*n,i=this.height*s;else if(e>r*n||i>r*s){const t=Math.min(r*n/e,r*s/i);e*=t,i*=t}this._uiManager.enableWaiting(!1);const a=this.#El=document.createElement("canvas");a.setAttribute("role","img"),this.addContainer(a),this.width=e/n,this.height=i/s,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Bl(),this.#Dl||(this.parent.addUndoableEditor(this),this.#Dl=!0),this._reportTelemetry({action:"inserted_image"}),this.#Cl&&this.div.setAttribute("aria-description",this.#Cl),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")}copyCanvas(t,e,i=!1){t||(t=224);const{width:n,height:s}=this.#wl,r=new Yt;let a=this.#wl,o=n,l=s,h=null;if(e){if(n>e||s>e){const t=Math.min(e/n,e/s);o=Math.floor(n*t),l=Math.floor(s*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*r.sx),i=h.height=Math.ceil(l*r.sy);this.#Ml||(a=this.#Fl(t,i));const c=h.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":Qt.isDarkMode&&(d="#8f8f9d",u="#42414d");const p=15,g=p*r.sx,m=p*r.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=d,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),c.fillStyle=c.createPattern(f,"repeat"),c.fillRect(0,0,t,i),c.drawImage(a,0,0,a.width,a.height,0,0,t,i)}let c=null;if(i){let e,i;if(r.symmetric&&a.width<t&&a.height<t)e=a.width,i=a.height;else if(a=this.#wl,n>t||s>t){const r=Math.min(t/n,t/s);e=Math.floor(n*r),i=Math.floor(s*r),this.#Ml||(a=this.#Fl(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(a,0,0,a.width,a.height,0,0,e,i),c={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:c}}#Fl(t,e){const{width:i,height:n}=this.#wl;let s=i,r=n,a=this.#wl;for(;s>2*t||r>2*e;){const i=s,n=r;s>2*t&&(s=s>=16384?Math.floor(s/2)-1:Math.ceil(s/2)),r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const o=new OffscreenCanvas(s,r);o.getContext("2d").drawImage(a,0,0,i,n,0,0,s,r),a=o.transferToImageBitmap()}return a}#Bl(){const[t,e]=this.parentDimensions,{width:i,height:n}=this,s=new Yt,r=Math.ceil(i*t*s.sx),a=Math.ceil(n*e*s.sy),o=this.#El;if(!o||o.width===r&&o.height===a)return;o.width=r,o.height=a;const l=this.#Ml?this.#wl:this.#Fl(r,a),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter,h.drawImage(l,0,0,l.width,l.height,0,0,r,a)}#Ol(t){if(t){if(this.#Ml){const t=this._uiManager.imageManager.getSvgUrl(this.#xl);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#wl);return t.getContext("2d").drawImage(this.#wl,0,0),t.toDataURL()}if(this.#Ml){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*Bt.PDF_TO_CSS_UNITS),n=Math.round(this.height*e*Bt.PDF_TO_CSS_UNITS),s=new OffscreenCanvas(i,n);return s.getContext("2d").drawImage(this.#wl,0,0,this.#wl.width,this.#wl.height,0,0,i,n),s.transferToImageBitmap()}return structuredClone(this.#wl)}static async deserialize(t,e,i){let n=null,s=!1;if(t instanceof Ss){const{data:{rect:r,rotation:a,id:o,structParent:l,popupRef:h,richText:c,contentsObj:d,creationDate:u,modificationDate:p},container:g,parent:{page:{pageNumber:m}},canvas:f}=t;let b,v;f?(delete t.canvas,({id:b,bitmap:v}=i.imageManager.getFromCanvas(g.id,f)),f.remove()):(s=!0,t._hasNoCanvas=!0);const y=(await e._structTree.getAriaAttributes(`${Mt}${o}`))?.get("aria-label")||"";n=t={annotationType:F.STAMP,bitmapId:b,bitmap:v,pageIndex:m-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:y},isSvg:!1,structParent:l,popupRef:h,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const r=await super.deserialize(t,e,i),{rect:a,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:c,accessibilityData:d}=t;s?(i.addMissingCanvas(t.id,r),r.#Tl=!0):h&&i.imageManager.isValidId(h)?(r.#xl=h,o&&(r.#wl=o)):r.#_l=l,r.#Ml=c;const[u,p]=r.pageDimensions;return r.width=(a[2]-a[0])/u,r.height=(a[3]-a[1])/p,d&&(r.altTextData=d),r._initialData=n,t.comment&&r.setCommentData(t),r.#Dl=!!n,r}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:this.#xl,isSvg:this.#Ml});if(this.addComment(i),t)return i.bitmapUrl=this.#Ol(!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;const{decorative:n,altText:s}=this.serializeAltText(!1);if(!n&&s&&(i.accessibilityData={type:"Figure",alt:s}),this.annotationElementId){const t=this.#xa(i);return t.isSame?null:(t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1,i.id=this.annotationElementId,delete i.bitmapId,i)}if(null===e)return i;e.stamps||=new Map;const r=this.#Ml?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#xl)){if(this.#Ml){const t=e.stamps.get(this.#xl);r>t.area&&(t.area=r,t.serialized.bitmap.close(),t.serialized.bitmap=this.#Ol(!1))}}else e.stamps.set(this.#xl,{area:r,serialized:i}),i.bitmap=this.#Ol(!1);return i}#xa(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,n=t.pageIndex===e,s=(t.accessibilityData?.alt||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&n&&s,isSameAltText:s}}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}class Ks{#sa;#Nl=!1;#Ul=null;#jl=null;#zl=null;#Hl=new Map;#$l=!1;#Wl=!1;#Vl=!1;#Gl=null;#ql=null;#Xl=null;#Kl=null;#Yl=null;#Jl=-1;#b;static _initialized=!1;static#V=new Map([ks,Hs,Xs,Fs,qs].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:n,accessibilityManager:s,annotationLayer:r,drawLayer:a,textLayer:o,viewport:l,l10n:h}){const c=[...Ks.#V.values()];if(!Ks._initialized){Ks._initialized=!0;for(const e of c)e.initialize(h,t)}t.registerEditorTypes(c),this.#b=t,this.pageIndex=e,this.div=i,this.#sa=s,this.#Ul=r,this.viewport=l,this.#Xl=o,this.drawLayer=a,this._structTree=n,this.#b.addLayer(this)}get isEmpty(){return 0===this.#Hl.size}get isInvisible(){return this.isEmpty&&this.#b.getMode()===F.NONE}updateToolbar(t){this.#b.updateToolbar(t)}updateMode(t=this.#b.getMode()){switch(this.#Ql(),t){case F.NONE:return this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case F.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case F.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;if(e.toggle("nonEditing",!1),t===F.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const i of Ks.#V.values())e.toggle(`${i._type}Editing`,t===i._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#Xl?.div}setEditingState(t){this.#b.setEditingState(t)}addCommands(t){this.#b.addCommands(t)}cleanUndoStack(t){this.#b.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Ul?.div.classList.toggle("disabled",!t)}get#Zl(){return 0!==this.#Hl.size?this.#Hl.values():this.#b.getEditors(this.pageIndex)}async enable(){this.#Vl=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),this.#Yl?.abort(),this.#Yl=null;const t=new Set;for(const e of this.#Zl)e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#b.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));const e=this.#Ul;if(e)for(const i of e.getEditableAnnotations()){if(i.hide(),this.#b.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}this.#Vl=!1,this.#b._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#Wl=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),this.#Xl&&!this.#Yl){this.#Yl=new AbortController;const t=this.#b.combinedSignal(this.#Yl);this.#Xl.div.addEventListener("pointerdown",t=>{const{clientX:e,clientY:i,timeStamp:n}=t;if(n-this.#Jl>500)return void(this.#Jl=n);this.#Jl=-1;const{classList:s}=this.div;s.toggle("getElements",!0);const r=document.elementsFromPoint(e,i);if(s.toggle("getElements",!1),!this.div.contains(r[0]))return;let a;const o=new RegExp(`^${B}[0-9]+$`);for(const t of r)if(o.test(t.id)){a=t.id;break}if(!a)return;const l=this.#Hl.get(a);null===l?.annotationElementId&&(t.stopPropagation(),t.preventDefault(),l.dblclick(t))},{signal:t,capture:!0})}const t=this.#Ul;if(t){const e=new Map,i=new Map;for(const n of this.#Zl)n.disableEditing(),n.annotationElementId?null===n.serialize()?(i.set(n.annotationElementId,n),this.getEditableAnnotation(n.annotationElementId)?.show(),n.remove()):e.set(n.annotationElementId,n):n.updateFakeAnnotationElement(t);const n=t.getEditableAnnotations();for(const t of n){const{id:n}=t.data;if(this.#b.isDeletedAnnotationElement(n)){t.updateEdited({deleted:!0});continue}let s=i.get(n);s?(s.resetAnnotationElement(t),s.show(!1),t.show()):(s=e.get(n),s&&(this.#b.addChangedExistingAnnotation(s),s.renderAnnotationElement(t)&&s.show(!1)),t.show())}}this.#Ql(),this.isEmpty&&(this.div.hidden=!0);const{classList:e}=this.div;for(const t of Ks.#V.values())e.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#Wl=!1}getEditableAnnotation(t){return this.#Ul?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#b.getActive()!==t&&this.#b.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#Xl?.div&&!this.#Kl){this.#Kl=new AbortController;const t=this.#b.combinedSignal(this.#Kl);this.#Xl.div.addEventListener("pointerdown",this.#th.bind(this),{signal:t}),this.#Xl.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#Xl?.div&&this.#Kl&&(this.#Kl.abort(),this.#Kl=null,this.#Xl.div.classList.remove("highlighting"))}#th(t){this.#b.unselectAll();const{target:e}=t;if(e===this.#Xl.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Xl.div.contains(e)){const{isMac:e}=_t.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#b.showAllEditors("highlight",!0,!0),this.#Xl.div.classList.add("free"),this.toggleDrawing(),Fs.startHighlighting(this,"ltr"===this.#b.direction,{target:this.#Xl.div,x:t.x,y:t.y}),this.#Xl.div.addEventListener("pointerup",()=>{this.#Xl.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#b._signal}),t.preventDefault()}}enableClick(){if(this.#jl)return;this.#jl=new AbortController;const t=this.#b.combinedSignal(this.#jl);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#jl?.abort(),this.#jl=null}attach(t){this.#Hl.set(t.id,t);const{annotationElementId:e}=t;e&&this.#b.isDeletedAnnotationElement(e)&&this.#b.removeDeletedAnnotationElement(t)}detach(t){this.#Hl.delete(t.id),this.#sa?.removePointerInTextLayer(t.contentDiv),!this.#Wl&&t.annotationElementId&&this.#b.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#b.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#b.addDeletedAnnotationElement(t.annotationElementId),be.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(t.parent!==this||!t.isAttachedToDOM){if(this.changeParent(t),this.#b.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#Vl),this.#b.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#zl&&(t._focusEventsAllowed=!1,this.#zl=setTimeout(()=>{this.#zl=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#b._signal}),e.focus())},0)),t._structTreeParentId=this.#sa?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getEditorByUID(t){for(const e of this.#Hl.values())if(e.uid===t)return e;return null}getNextId(){return this.#b.getId()}get#eh(){return Ks.#V.get(this.#b.getMode())}combinedSignal(t){return this.#b.combinedSignal(t)}#ih(t){const e=this.#eh;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#eh?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t),await this.#b.updateMode(t.mode);const{offsetX:i,offsetY:n}=this.#nh(),s=this.getNextId(),r=this.#ih({parent:this,id:s,x:i,y:n,uiManager:this.#b,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await(Ks.#V.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#b))||null}createAndAddNewEditor(t,e,i={}){const n=this.getNextId(),s=this.#ih({parent:this,id:n,x:t.offsetX,y:t.offsetY,uiManager:this.#b,isCentered:e,...i});return s&&this.add(s),s}get boundingClientRect(){return this.div.getBoundingClientRect()}#nh(){const{x:t,y:e,width:i,height:n}=this.boundingClientRect,s=Math.max(0,t),r=Math.max(0,e),a=(s+Math.min(window.innerWidth,t+i))/2-t,o=(r+Math.min(window.innerHeight,e+n))/2-e,[l,h]=this.viewport.rotation%180==0?[a,o]:[o,a];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#nh(),!0,t)}setSelected(t){this.#b.setSelected(t)}toggleSelected(t){this.#b.toggleSelected(t)}unselect(t){this.#b.unselect(t)}pointerup(t){const{isMac:e}=_t.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#$l)return;if(this.#$l=!1,this.#eh?.isDrawer&&this.#eh.supportMultipleDrawings)return;if(!this.#Nl)return void(this.#Nl=!0);const i=this.#b.getMode();i!==F.STAMP&&i!==F.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#b.unselectAll()}pointerdown(t){if(this.#b.getMode()===F.HIGHLIGHT&&this.enableTextSelection(),this.#$l)return void(this.#$l=!1);const{isMac:e}=_t.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(this.#$l=!0,this.#eh?.isDrawer)return void this.startDrawingSession(t);const i=this.#b.getActive();this.#Nl=!i||i.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#Gl)return void this.#eh.startDrawing(this,this.#b,!1,t);this.#b.setCurrentDrawingSession(this),this.#Gl=new AbortController;const e=this.#b.combinedSignal(this.#Gl);this.div.addEventListener("blur",({relatedTarget:t})=>{t&&!this.div.contains(t)&&(this.#ql=null,this.commitOrRemove())},{signal:e}),this.#eh.startDrawing(this,this.#b,!1,t)}pause(t){if(t){const{activeElement:t}=document;return void(this.div.contains(t)&&(this.#ql=t))}this.#ql&&setTimeout(()=>{this.#ql?.focus(),this.#ql=null},0)}endDrawingSession(t=!1){return this.#Gl?(this.#b.setCurrentDrawingSession(null),this.#Gl.abort(),this.#Gl=null,this.#ql=null,this.#eh.endDrawing(t)):null}findNewParent(t,e,i){const n=this.#b.findParent(e,i);return null!==n&&n!==this&&(n.changeParent(t),!0)}commitOrRemove(){return!!this.#Gl&&(this.endDrawingSession(),!0)}onScaleChanging(){this.#Gl&&this.#eh.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#b.getActive()?.parent===this&&(this.#b.commitOrRemove(),this.#b.setActiveEditor(null)),this.#zl&&(clearTimeout(this.#zl),this.#zl=null);for(const t of this.#Hl.values())this.#sa?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Hl.clear(),this.#b.removeLayer(this)}#Ql(){for(const t of this.#Hl.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,Kt(this.div,t);for(const t of this.#b.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#b.commitOrRemove(),this.#Ql();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,Kt(this.div,{rotation:i}),e!==i)for(const t of this.#Hl.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#b.viewParameters.realScale}}class Ys{#kr=null;#sh=new Map;#rh=new Map;static#x=0;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#kr){if(this.#kr!==t){if(this.#sh.size>0)for(const e of this.#sh.values())e.remove(),t.append(e);this.#kr=t}}else this.#kr=t}static get _svgFactory(){return pt(this,"_svgFactory",new Kn)}static#ah(t,[e,i,n,s]){const{style:r}=t;r.top=100*i+"%",r.left=100*e+"%",r.width=100*n+"%",r.height=100*s+"%"}#oh(){const t=Ys._svgFactory.create(1,1,!0);return this.#kr.append(t),t.setAttribute("aria-hidden",!0),t}#lh(t,e){const i=Ys._svgFactory.createElement("clipPath");t.append(i);const n=`clip_${e}`;i.setAttribute("id",n),i.setAttribute("clipPathUnits","objectBoundingBox");const s=Ys._svgFactory.createElement("use");return i.append(s),s.setAttribute("href",`#${e}`),s.classList.add("clip"),n}#hh(t,e){for(const[i,n]of Object.entries(e))null===n?t.removeAttribute(i):t.setAttribute(i,n)}draw(t,e=!1,i=!1){const n=Ys.#x++,s=this.#oh(),r=Ys._svgFactory.createElement("defs");s.append(r);const a=Ys._svgFactory.createElement("path");r.append(a);const o=`path_p${this.pageIndex}_${n}`;a.setAttribute("id",o),a.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#rh.set(n,a);const l=i?this.#lh(r,o):null,h=Ys._svgFactory.createElement("use");return s.append(h),h.setAttribute("href",`#${o}`),this.updateProperties(s,t),this.#sh.set(n,s),{id:n,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=Ys.#x++,n=this.#oh(),s=Ys._svgFactory.createElement("defs");n.append(s);const r=Ys._svgFactory.createElement("path");s.append(r);const a=`path_p${this.pageIndex}_${i}`;let o;if(r.setAttribute("id",a),r.setAttribute("vector-effect","non-scaling-stroke"),e){const t=Ys._svgFactory.createElement("mask");s.append(t),o=`mask_p${this.pageIndex}_${i}`,t.setAttribute("id",o),t.setAttribute("maskUnits","objectBoundingBox");const e=Ys._svgFactory.createElement("rect");t.append(e),e.setAttribute("width","1"),e.setAttribute("height","1"),e.setAttribute("fill","white");const n=Ys._svgFactory.createElement("use");t.append(n),n.setAttribute("href",`#${a}`),n.setAttribute("stroke","none"),n.setAttribute("fill","black"),n.setAttribute("fill-rule","nonzero"),n.classList.add("mask")}const l=Ys._svgFactory.createElement("use");n.append(l),l.setAttribute("href",`#${a}`),o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();return n.append(h),l.classList.add("mainOutline"),h.classList.add("secondaryOutline"),this.updateProperties(n,t),this.#sh.set(i,n),i}finalizeDraw(t,e){this.#rh.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:n,rootClass:s,path:r}=e,a="number"==typeof t?this.#sh.get(t):t;if(a){if(i&&this.#hh(a,i),n&&Ys.#ah(a,n),s){const{classList:t}=a;for(const[e,i]of Object.entries(s))t.toggle(e,i)}if(r){const t=a.firstChild.firstChild;this.#hh(t,r)}}}updateParent(t,e){if(e===this)return;const i=this.#sh.get(t);i&&(e.#kr.append(i),this.#sh.delete(t),e.#sh.set(t,i))}remove(t){this.#rh.delete(t),null!==this.#kr&&(this.#sh.get(t).remove(),this.#sh.delete(t))}destroy(){this.#kr=null;for(const t of this.#sh.values())t.remove();this.#sh.clear(),this.#rh.clear()}}globalThis._pdfjsTestingUtils={HighlightOutliner:Is},globalThis.pdfjsLib={AbortException:wt,AnnotationEditorLayer:Ks,AnnotationEditorParamsType:O,AnnotationEditorType:F,AnnotationEditorUIManager:pe,AnnotationLayer:Es,AnnotationMode:L,AnnotationType:V,applyOpacity:function(t,e,i,n){const s=255*(1-(n=Math.min(Math.max(n??1,0),1)));return[t=Math.round(t*n+s),e=Math.round(e*n+s),i=Math.round(i*n+s)]},build:"f56dc8601",ColorPicker:$n,createValidAbsoluteUrl:dt,CSSConstants:class{static get commentForegroundColor(){const t=document.createElement("span");t.classList.add("comment","sidebar");const{style:e}=t;e.width=e.height="0",e.display="none",e.color="var(--comment-fg-color)",document.body.append(t);const{color:i}=window.getComputedStyle(t);return t.remove(),pt(this,"commentForegroundColor",Gt(i))}},DOMSVGFactory:Kn,DrawLayer:Ys,FeatureTest:_t,fetchData:Ft,findContrastColor:function(t,e){const i=t[0]+256*t[1]+65536*t[2]+16777216*e[0]+4294967296*e[1]+1099511627776*e[2];let n=ne.get(i);if(n)return n;const s=new Float32Array(9),r=s.subarray(0,3),a=s.subarray(3,6);Zt(t,a);const o=s.subarray(6,9);Zt(e,o);const l=o[2]<.5,h=l?12:4.5;if(a[2]=l?Math.sqrt(a[2]):1-Math.sqrt(1-a[2]),ie(a,o,r)<h){let t,e;l?(t=a[2],e=1):(t=0,e=a[2]);const i=.005;for(;e-t>i;){const i=a[2]=(t+e)/2;l===ie(a,o,r)<h?t=i:e=i}a[2]=l?e:t}return te(a,r),n=Ct.makeHexColor(Math.round(255*r[0]),Math.round(255*r[1]),Math.round(255*r[2])),ne.set(i,n),n},getDocument:Ln,getFilenameFromUrl:function(t){return[t]=t.split(/[#?]/,1),t.substring(t.lastIndexOf("/")+1)},getPdfFilenameFromUrl:function(t,e="document.pdf"){if("string"!=typeof t)return e;if(Ut(t))return lt('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;const i=(t=>{try{return new URL(t)}catch{try{return new URL(decodeURIComponent(t))}catch{try{return new URL(t,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(t),"https://foo.bar")}catch{return null}}}}})(t);if(!i)return e;const n=t=>{try{let e=decodeURIComponent(t);return e.includes("/")?(e=e.split("/").at(-1),e.test(/^\.pdf$/i)?e:t):e}catch{return t}},s=/\.pdf$/i,r=i.pathname.split("/").at(-1);if(s.test(r))return n(r);if(i.searchParams.size>0){const t=Array.from(i.searchParams.values()).reverse();for(const e of t)if(s.test(e))return n(e);const e=Array.from(i.searchParams.keys()).reverse();for(const t of e)if(s.test(t))return n(t)}if(i.hash){const t=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(i.hash);if(t)return n(t[0])}return e},getRGB:Gt,getUuid:kt,getXfaPageViewport:function(t,{scale:e=1,rotation:i=0}){const{width:n,height:s}=t.attributes.style,r=[0,0,parseInt(n),parseInt(s)];return new Ot({viewBox:r,userUnit:1,scale:e,rotation:i})},GlobalWorkerOptions:sn,ImageKind:W,InvalidPDFException:bt,isDataScheme:Ut,isPdfFile:jt,isValidExplicitDest:De,MathClamp:Dt,noContextMenu:$t,normalizeUnicode:function(t){return Et||(Et=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,Tt=new Map([["ſt","ſt"]])),t.replaceAll(Et,(t,e,i)=>e?e.normalize("NFKC"):Tt.get(i))},OPS:Q,OutputScale:Yt,PasswordResponses:nt,PDFDataRangeTransport:Fn,PDFDateString:Vt,PDFWorker:Un,PermissionFlag:{PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},PixelsPerInch:Bt,RenderingCancelledException:Nt,renderRichText:se,ResponseException:vt,setLayerDimensions:Kt,shadow:pt,SignatureExtractor:Ws,stopEvent:Wt,SupportedImageMimeTypes:Jt,TextLayer:Rn,TouchManager:fe,updateUrlHash:ut,Util:Ct,VerbosityLevel:J,version:"5.4.296",XfaLayer:Rt};var Js="Invariant failed";function Qs(t,e){if(!t)throw new Error(Js)}d();const Zs=(0,g.createContext)(null);class tr{constructor(){this.externalLinkEnabled=!0,this.externalLinkRel=void 0,this.externalLinkTarget=void 0,this.isInPresentationMode=!1,this.pdfDocument=void 0,this.pdfViewer=void 0}setDocument(t){this.pdfDocument=t}setViewer(t){this.pdfViewer=t}setExternalLinkRel(t){this.externalLinkRel=t}setExternalLinkTarget(t){this.externalLinkTarget=t}setHash(){}setHistory(){}get pagesCount(){return this.pdfDocument?this.pdfDocument.numPages:0}get page(){return Qs(this.pdfViewer),this.pdfViewer.currentPageNumber||0}set page(t){Qs(this.pdfViewer),this.pdfViewer.currentPageNumber=t}get rotation(){return 0}set rotation(t){}addLinkAttributes(t,e,i){t.href=e,t.rel=this.externalLinkRel||"noopener noreferrer nofollow",t.target=i?"_blank":this.externalLinkTarget||""}goToDestination(t){return new Promise(e=>{Qs(this.pdfDocument),Qs(t),"string"==typeof t?this.pdfDocument.getDestination(t).then(e):Array.isArray(t)?e(t):t.then(e)}).then(t=>{Qs(Array.isArray(t));const e=t[0];new Promise(t=>{Qs(this.pdfDocument),e instanceof Object?this.pdfDocument.getPageIndex(e).then(e=>{t(e)}).catch(()=>{Qs(!1)}):"number"==typeof e?t(e):Qs(!1)}).then(e=>{const i=e+1;Qs(this.pdfViewer),Qs(i>=1&&i<=this.pagesCount),this.pdfViewer.scrollPageIntoView({dest:t,pageIndex:e,pageNumber:i})})})}goToPage(t){const e=t-1;Qs(this.pdfViewer),Qs(t>=1&&t<=this.pagesCount),this.pdfViewer.scrollPageIntoView({pageIndex:e,pageNumber:t})}goToXY(){}cachePageRef(){}getDestinationHash(){return"#"}getAnchorUrl(){return"#"}executeNamedAction(){}executeSetOCGState(){}isPageVisible(){return!0}isPageCached(){return!0}navigateTo(t){this.goToDestination(t)}}function er({children:t,type:e}){return(0,p.jsx)("div",{className:`react-pdf__message react-pdf__message--${e}`,children:t})}const ir={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};function nr(t,e){switch(e.type){case"RESOLVE":return{value:e.value,error:void 0};case"REJECT":return{value:!1,error:e.error};case"RESET":return{value:void 0,error:void 0};default:return t}}function sr(){return(0,g.useReducer)(nr,{value:void 0,error:void 0})}const rr="undefined"!=typeof window,ar=rr&&"file:"===window.location.protocol;function or(t){return void 0!==t}function lr(t){return or(t)&&null!==t}function hr(t){return function(t){return"string"==typeof t}(t)&&/^data:/.test(t)}function cr(t){Qs(hr(t));const[e="",i=""]=t.split(",");return-1!==e.split(";").indexOf("base64")?atob(i):unescape(i)}function dr(){return rr&&window.devicePixelRatio||1}const ur="On Chromium based browsers, you can use --allow-file-access-from-files flag for debugging purposes.";function pr(){d()(!ar,`Loading PDF as base64 strings/URLs may not work on protocols other than HTTP/HTTPS. ${ur}`)}function gr(t){(null==t?void 0:t.cancel)&&t.cancel()}function mr(t,e){return Object.defineProperty(t,"width",{get(){return this.getViewport({scale:e}).width},configurable:!0}),Object.defineProperty(t,"height",{get(){return this.getViewport({scale:e}).height},configurable:!0}),Object.defineProperty(t,"originalWidth",{get(){return this.getViewport({scale:1}).width},configurable:!0}),Object.defineProperty(t,"originalHeight",{get(){return this.getViewport({scale:1}).height},configurable:!0}),t}function fr(t){return"AbortException"===t.name||"RenderingCancelledException"===t.name}const{Tm:br}=u,vr=(t,e)=>{switch(e){case ir.NEED_PASSWORD:t(prompt("Enter the password to open this PDF file."));break;case ir.INCORRECT_PASSWORD:t(prompt("Invalid password. Please try again."));break}};function yr(t){return"object"==typeof t&&null!==t&&("data"in t||"range"in t||"url"in t)}const wr=(0,g.forwardRef)(function({children:t,className:e,error:i="Failed to load PDF file.",externalLinkRel:n,externalLinkTarget:s,file:r,inputRef:a,imageResourcesPath:o,loading:l="Loading PDF…",noData:h="No PDF file specified.",onItemClick:c,onLoadError:u,onLoadProgress:m,onLoadSuccess:b,onPassword:v=vr,onSourceError:x,onSourceSuccess:_,options:S,renderMode:C,rotate:E,scale:T,...k},M){const[D,P]=sr(),{value:I,error:R}=D,[L,B]=sr(),{value:F,error:O}=L,N=(0,g.useRef)(new tr),U=(0,g.useRef)([]),j=(0,g.useRef)(void 0),z=(0,g.useRef)(void 0);r&&r!==j.current&&yr(r)&&(d()(!y(r,j.current),'File prop passed to <Document /> changed, but it\'s equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "file" prop.'),j.current=r),S&&S!==z.current&&(d()(!y(S,z.current),'Options prop passed to <Document /> changed, but it\'s equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "options" prop.'),z.current=S);const H=(0,g.useRef)({scrollPageIntoView:t=>{const{dest:e,pageNumber:i,pageIndex:n=i-1}=t;if(c)return void c({dest:e,pageIndex:n,pageNumber:i});const s=U.current[n];s?s.scrollIntoView():d()(!1,`An internal link leading to page ${i} was clicked, but neither <Document> was provided with onItemClick nor it was able to find the page within itself. Either provide onItemClick to <Document> and handle navigating by yourself or ensure that all pages are rendered within <Document>.`)}});(0,g.useImperativeHandle)(M,()=>({linkService:N,pages:U,viewer:H}),[]),(0,g.useEffect)(function(){P({type:"RESET"})},[r,P]);const $=(0,g.useCallback)(async()=>{if(!r)return null;if("string"==typeof r){if(hr(r)){return{data:cr(r)}}return pr(),{url:r}}if(r instanceof br)return{range:r};if(r instanceof ArrayBuffer)return{data:r};if(rr&&function(t){return Qs(rr),t instanceof Blob}(r)){const t=await function(t){return new Promise((e,i)=>{const n=new FileReader;n.onload=()=>{if(!n.result)return i(new Error("Error while reading a file."));e(n.result)},n.onerror=t=>{if(!t.target)return i(new Error("Error while reading a file."));const{error:e}=t.target;if(!e)return i(new Error("Error while reading a file."));switch(e.code){case e.NOT_FOUND_ERR:return i(new Error("Error while reading a file: File not found."));case e.SECURITY_ERR:return i(new Error("Error while reading a file: Security error."));case e.ABORT_ERR:return i(new Error("Error while reading a file: Aborted."));default:return i(new Error("Error while reading a file."))}},n.readAsArrayBuffer(t)})}(r);return{data:t}}if(Qs("object"==typeof r),Qs(yr(r)),"url"in r&&"string"==typeof r.url){if(hr(r.url)){const{url:t,...e}=r;return{data:cr(t),...e}}pr()}return r},[r]);(0,g.useEffect)(()=>{const t=w($());return t.promise.then(t=>{P({type:"RESOLVE",value:t})}).catch(t=>{P({type:"REJECT",error:t})}),()=>{gr(t)}},[$,P]),(0,g.useEffect)(()=>{void 0!==I&&(!1!==I?_&&_():R&&(d()(!1,R.toString()),x&&x(R)))},[I]),(0,g.useEffect)(function(){B({type:"RESET"})},[B,I]),(0,g.useEffect)(function(){if(!I)return;const t=Ln(S?{...I,...S}:I);m&&(t.onProgress=m),v&&(t.onPassword=v);const e=t;return e.promise.then(t=>{e.destroyed||B({type:"RESOLVE",value:t})}).catch(t=>{e.destroyed||B({type:"REJECT",error:t})}),()=>{e.destroy(),B({type:"RESET"})}},[S,B,I]),(0,g.useEffect)(()=>{void 0!==F&&(!1!==F?F&&(b&&b(F),U.current=new Array(F.numPages),N.current.setDocument(F)):O&&(d()(!1,O.toString()),u&&u(O)))},[F]),(0,g.useEffect)(function(){N.current.setViewer(H.current),N.current.setExternalLinkRel(n),N.current.setExternalLinkTarget(s)},[n,s]);const W=(0,g.useCallback)((t,e)=>{U.current[t]=e},[]),V=(0,g.useCallback)(t=>{delete U.current[t]},[]),G=(0,g.useMemo)(()=>({imageResourcesPath:o,linkService:N.current,onItemClick:c,pdf:F,registerPage:W,renderMode:C,rotate:E,scale:T,unregisterPage:V}),[o,c,F,W,C,E,T,V]),q=(0,g.useMemo)(()=>A(k,()=>F),[k,F]);return(0,p.jsx)("div",{className:f("react-pdf__Document",e),ref:a,...q,children:r?null==F?(0,p.jsx)(er,{type:"loading",children:"function"==typeof l?l():l}):!1===F?(0,p.jsx)(er,{type:"error",children:"function"==typeof i?i():i}):function(){if(e=G,!Boolean(null==e?void 0:e.pdf))throw new Error("pdf is undefined");var e;const i="function"==typeof t?t(G):t;return(0,p.jsx)(Zs.Provider,{value:G,children:i})}():(0,p.jsx)(er,{type:"no-data",children:"function"==typeof h?h():h})})}),xr=n.p+"pdfjs/build/pdf.worker.min.mjs",Ar=t=>{var e;const i=window.dash_component_api;return i?i.useDashContext().useLoading():null!==(e=null==t?void 0:t.is_loading)&&void 0!==e&&e};function _r(){return _r.c||(_r.c=n.n(r()))}function Sr(){return Sr.c||(Sr.c=n.n(h()))}function Cr(){return Cr.c||(Cr.c=n.n(a()))}function Er(){return Er.c||(Er.c=n.n(l()))}function Tr(){return Tr.c||(Tr.c=n.n(o()))}function kr(){return kr.c||(kr.c=n.n(c()))}r(),h(),a(),l(),o(),c();var Mr=n(808),Dr={};Dr.styleTagTransform=kr()(),Dr.setAttributes=Er()(),Dr.insert=Cr()().bind(null,"head"),Dr.domAPI=Sr()(),Dr.insertStyleElement=Tr()();_r()()(Mr.A,Dr);Mr.A&&Mr.A.locals&&Mr.A.locals;var Pr=n(810),Ir={};Ir.styleTagTransform=kr()(),Ir.setAttributes=Er()(),Ir.insert=Cr()().bind(null,"head"),Ir.domAPI=Sr()(),Ir.insertStyleElement=Tr()();_r()()(Pr.A,Ir);Pr.A&&Pr.A.locals&&Pr.A.locals;var Rr=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const Lr=new URL("../",xr).toString(),Br=t=>t.endsWith("/")?t:`${t}/`,Fr=(t,e)=>{if(Object.is(t,e))return!0;if(!t||!e||"object"!=typeof t||"object"!=typeof e)return!1;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((t,i)=>Fr(t,e[i]));const i=t,n=e,s=Object.keys(i);return s.length===Object.keys(n).length&&s.every(t=>Object.prototype.hasOwnProperty.call(n,t)&&Fr(i[t],n[t]))},Or=t=>{const e=(0,g.useRef)(t);return Fr(e.current,t)||(e.current=t),e.current},Nr=t=>`${Br((null==t?void 0:t.trim())||Lr)}web/images/`,Ur=(t,e)=>{const i=e instanceof Error?e:new Error(String(e));return{stage:t,name:i.name,message:i.message}};let jr=0;const zr=(t,e)=>(jr=Math.max(Date.now(),jr+1),{pageIndex:t,pageNumber:e,timestamp:jr}),Hr=t=>({pageNumber:t.pageNumber,width:t.width,height:t.height,originalWidth:t.originalWidth,originalHeight:t.originalHeight}),$r=t=>{var{children:e,id:i,className:n,style:s,loading_state:r,setProps:a}=t,o=Rr(t,["children","id","className","style","loading_state","setProps"]);const l=Ar(r);return(0,p.jsx)("div",Object.assign({},o,{id:i,className:n,style:s,"data-dash-is-loading":l||void 0,children:e}))},Wr=(0,g.createContext)(null);var Vr=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const Gr=t=>{var{children:e,file:i=null,options:n={},assetBaseUrl:s,workerSrc:r,imageResourcesPath:a,externalLinkRel:o,externalLinkTarget:l,renderMode:h="canvas",rotate:c,scale:d=1,password:u,numPages:m,loadData:f,loadProgress:b,sourceLoaded:v,errorData:y,passwordData:w,itemClickData:x,loading:A,error:_,noData:S,setProps:C}=t,E=Vr(t,["children","file","options","assetBaseUrl","workerSrc","imageResourcesPath","externalLinkRel","externalLinkTarget","renderMode","rotate","scale","password","numPages","loadData","loadProgress","sourceLoaded","errorData","passwordData","itemClickData","loading","error","noData","setProps"]);const T=Or(i),k=Or(n),M=(0,g.useMemo)(()=>((t={},e,i)=>{const n=Br((null==e?void 0:e.trim())||Lr);return sn.workerSrc=(null==i?void 0:i.trim())||(e?`${n}build/pdf.worker.min.mjs`:xr),Object.assign({cMapUrl:`${n}cmaps/`,cMapPacked:!0,standardFontDataUrl:`${n}standard_fonts/`,wasmUrl:`${n}wasm/`,iccUrl:`${n}iccs/`,isEvalSupported:!1},t)})(k,s,r),[k,s,r]),D=(0,g.useRef)(null),P=(0,g.useRef)(new Map),I=(0,g.useCallback)((t,e)=>(P.current.set(t,e),()=>{P.current.delete(t)}),[]),R=(0,g.useMemo)(()=>({registerPage:I}),[I]);(0,g.useEffect)(()=>{u&&D.current&&(D.current(u),D.current=null)},[u]),(0,g.useEffect)(()=>{null==C||C({numPages:null,loadData:null,loadProgress:null,sourceLoaded:!1,errorData:null,passwordData:null})},[T,k,s,r]);return(0,p.jsx)(Wr.Provider,{value:R,children:(0,p.jsx)($r,Object.assign({},E,{setProps:C,children:(0,p.jsx)(wr,{file:T,options:M,imageResourcesPath:a||Nr(s),externalLinkRel:o,externalLinkTarget:l,renderMode:h,rotate:c,scale:d,loading:A,error:_,noData:S,onItemClick:({pageIndex:t,pageNumber:e})=>{const i=[...P.current.values()],n=i.find(t=>t.pageNumber===e);n?n.scrollIntoView():1===i.length&&i[0].setPageNumber(e),null==C||C({itemClickData:zr(t,e)})},onLoadProgress:t=>null==C?void 0:C({loadProgress:t}),onLoadSuccess:t=>{null==C||C({numPages:t.numPages,loadData:{numPages:t.numPages,fingerprints:[...t.fingerprints]},errorData:null,passwordData:null})},onLoadError:t=>null==C?void 0:C({numPages:null,errorData:Ur("document",t)}),onSourceSuccess:()=>null==C?void 0:C({sourceLoaded:!0}),onSourceError:t=>null==C?void 0:C({sourceLoaded:!1,errorData:Ur("source",t)}),onPassword:(t,e)=>{D.current=t,u?(t(u),D.current=null):null==C||C({passwordData:{reason:e===nt.INCORRECT_PASSWORD?"incorrect-password":"need-password"}})},children:e})}))})},qr=t=>(0,p.jsx)(Gr,Object.assign({},t)),Xr=(0,g.createContext)(null);class Kr{constructor({num:t,gen:e}){this.num=t,this.gen=e}toString(){let t=`${this.num}R`;return 0!==this.gen&&(t+=this.gen),t}}function Yr(t){const e=(0,g.useRef)(void 0),i=e.current;return or(i)?()=>i:()=>{const i=t();return e.current=i,i}}function Jr(){return(0,g.useContext)(Zs)}function Qr(t){const e=Jr(),i=(0,g.useContext)(Xr);Qs(i);const n={...e,...i,...t},{item:s,linkService:r,onItemClick:a,pdf:o,...l}=n;Qs(o);const h=Yr(()=>"string"==typeof s.dest?o.getDestination(s.dest):s.dest),c=Yr(async()=>{const t=await h();if(!t)throw new Error("Destination not found.");const[e]=t;return o.getPageIndex(new Kr(e))}),d=Yr(async()=>await c()+1);return(0,p.jsxs)("li",{children:[(0,p.jsx)("a",{href:"#",onClick:function(t){t.preventDefault(),Qs(a||r),a?Promise.all([h(),c(),d()]).then(([t,e,i])=>{a({dest:t,pageIndex:e,pageNumber:i})}):r&&r.goToDestination(s.dest)},children:s.title}),function(){var t;if(!(null===(t=s.items)||void 0===t?void 0:t.length))return null;const{items:e}=s;return(0,p.jsx)("ul",{children:e.map((t,e)=>(0,p.jsx)(Qr,{item:t,pdf:o,...l},"string"==typeof t.dest?t.dest:e))})}()]})}function Zr(t){const e={...Jr(),...t},{className:i,inputRef:n,onItemClick:s,onLoadError:r,onLoadSuccess:a,pdf:o,...l}=e;Qs(o);const[h,c]=sr(),{value:u,error:m}=h;(0,g.useEffect)(function(){c({type:"RESET"})},[c,o]),(0,g.useEffect)(function(){const t=w(o.getOutline()),e=t;return t.promise.then(t=>{c({type:"RESOLVE",value:t})}).catch(t=>{c({type:"REJECT",error:t})}),()=>gr(e)},[c,o]),(0,g.useEffect)(()=>{void 0!==u&&(!1!==u?void 0!==u&&!1!==u&&a&&a(u):m&&(d()(!1,m.toString()),r&&r(m)))},[u]);const b=(0,g.useMemo)(()=>({onItemClick:s}),[s]),v=(0,g.useMemo)(()=>A(l,()=>u),[l,u]);if(!u)return null;return(0,p.jsx)("div",{className:f("react-pdf__Outline",i),ref:n,...v,children:(0,p.jsx)(Xr.Provider,{value:b,children:u?(0,p.jsx)("ul",{children:u.map((t,e)=>(0,p.jsx)(Qr,{item:t,pdf:o},"string"==typeof t.dest?t.dest:e))}):null})})}var ta=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const ea=t=>Array.isArray(t)?t.map(t=>{const e=t;return{title:"string"==typeof e.title?e.title:"",bold:!0===e.bold,italic:!0===e.italic,url:"string"==typeof e.url?e.url:null,items:ea(e.items)||[]}}):null,ia=t=>{var{outlineData:e,itemClickData:i,errorData:n,setProps:s}=t,r=ta(t,["outlineData","itemClickData","errorData","setProps"]);return(0,p.jsx)($r,Object.assign({},r,{setProps:s,children:(0,p.jsx)(Zr,{onItemClick:({pageIndex:t,pageNumber:e})=>null==s?void 0:s({itemClickData:zr(t,e)}),onLoadSuccess:t=>null==s?void 0:s({outlineData:ea(t),errorData:null}),onLoadError:t=>null==s?void 0:s({errorData:Ur("outline-load",t)})})}))},na=t=>(0,p.jsx)(ia,Object.assign({},t));function sa(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=t.filter(Boolean);return i.length<=1?i[0]||null:function(t){for(var e=0,n=i;e<n.length;e++){var s=n[e];"function"==typeof s?s(t):s&&(s.current=t)}}}const ra=(0,g.createContext)(null);function aa(){return(0,g.useContext)(ra)}function oa(){const t=Jr(),e=aa();Qs(e);const i={...t,...e},{filterAnnotations:n,imageResourcesPath:s,linkService:r,onGetAnnotationsError:a,onGetAnnotationsSuccess:o,onRenderAnnotationLayerError:l,onRenderAnnotationLayerSuccess:h,page:c,pdf:u,renderForms:m,rotate:b,scale:v=1}=i;Qs(u),Qs(c),Qs(r);const[y,x]=sr(),{value:A,error:_}=y,S=(0,g.useRef)(null);d()(1===Number.parseInt(window.getComputedStyle(document.body).getPropertyValue("--react-pdf-annotation-layer"),10),"AnnotationLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-annotations"),(0,g.useEffect)(function(){x({type:"RESET"})},[x,c]),(0,g.useEffect)(function(){if(!c)return;const t=w(c.getAnnotations()),e=t;return t.promise.then(t=>{x({type:"RESOLVE",value:t})}).catch(t=>{x({type:"REJECT",error:t})}),()=>{gr(e)}},[x,c]),(0,g.useEffect)(()=>{void 0!==A&&(!1!==A?A&&o&&o(A):_&&(d()(!1,_.toString()),a&&a(_)))},[A]);const C=(0,g.useMemo)(()=>c.getViewport({scale:v,rotation:b}),[c,b,v]);return(0,g.useEffect)(function(){if(!(u&&c&&r&&A))return;const{current:t}=S;if(!t)return;const e=C.clone({dontFlip:!0}),i={accessibilityManager:null,annotationCanvasMap:null,annotationEditorUIManager:null,annotationStorage:u.annotationStorage,commentManager:null,div:t,l10n:null,linkService:r,page:c,structTreeLayer:null,viewport:e},a={annotations:n?n({annotations:A}):A,annotationStorage:u.annotationStorage,div:t,imageResourcesPath:s,linkService:r,page:c,renderForms:m,viewport:e};t.innerHTML="";try{new Es(i).render(a),h&&h()}catch(t){!function(t){d()(!1,`${t}`),l&&l(t)}(t)}return()=>{}},[A,n,s,r,c,u,m,C]),(0,p.jsx)("div",{className:f("react-pdf__Page__annotations","annotationLayer"),ref:S})}const la={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},ha=/^H(\d+)$/;function ca(t){return"children"in t}function da(t){return!!ca(t)&&(1===t.children.length&&0 in t.children&&"id"in t.children[0])}function ua(t){const e={};if(ca(t)){const{role:i}=t,n=i.match(ha);if(n)e.role="heading",e["aria-level"]=Number(n[1]);else if(function(t){return t in la}(i)){const t=la[i];t&&(e.role=t)}}return e}function pa(t){const e={};if(ca(t)){if(void 0!==t.alt&&(e["aria-label"]=t.alt),void 0!==t.lang&&(e.lang=t.lang),da(t)){const[i]=t.children;if(i){const t=pa(i);return{...e,...t}}}}else"id"in t&&(e["aria-owns"]=t.id);return e}function ga({className:t,node:e}){const i=(0,g.useMemo)(()=>function(t){return t?{...ua(t),...pa(t)}:null}(e),[e]),n=(0,g.useMemo)(()=>ca(e)?da(e)?null:e.children.map((t,e)=>(0,p.jsx)(ga,{node:t},e)):null,[e]);return(0,p.jsx)("span",{className:t,...i,children:n})}function ma(){const t=aa();Qs(t);const{onGetStructTreeError:e,onGetStructTreeSuccess:i}=t,[n,s]=sr(),{value:r,error:a}=n,{customTextRenderer:o,page:l}=t;return(0,g.useEffect)(function(){s({type:"RESET"})},[s,l]),(0,g.useEffect)(function(){if(o)return;if(!l)return;const t=w(l.getStructTree()),e=t;return t.promise.then(t=>{s({type:"RESOLVE",value:t})}).catch(t=>{s({type:"REJECT",error:t})}),()=>gr(e)},[o,l,s]),(0,g.useEffect)(()=>{void 0!==r&&(!1!==r?r&&i&&i(r):a&&(d()(!1,a.toString()),e&&e(a)))},[r]),r?(0,p.jsx)(ga,{className:"react-pdf__Page__structTree structTree",node:r}):null}const fa=L;function ba(t){const e=aa();Qs(e);const i={...e,...t},{_className:n,canvasBackground:s,devicePixelRatio:r=dr(),onRenderError:a,onRenderSuccess:o,page:l,renderForms:h,renderTextLayer:c,pageColors:u,rotate:m,scale:f}=i,{canvasRef:b}=t;Qs(l);const v=(0,g.useRef)(null);function y(t){fr(t)||(d()(!1,t.toString()),a&&a(t))}const w=(0,g.useMemo)(()=>l.getViewport({scale:f*r,rotation:m}),[r,l,m,f]),x=(0,g.useMemo)(()=>l.getViewport({scale:f,rotation:m}),[l,m,f]);(0,g.useEffect)(function(){if(!l)return;l.cleanup();const{current:t}=v;if(!t)return;t.width=w.width,t.height=w.height,t.style.width=`${Math.floor(x.width)}px`,t.style.height=`${Math.floor(x.height)}px`,t.style.visibility="hidden";const e={annotationMode:h?fa.ENABLE_FORMS:fa.ENABLE,canvas:t,canvasContext:t.getContext("2d",{alpha:!1}),pageColors:u,viewport:w};s&&(e.background=s);const i=l.render(e),n=i;return i.promise.then(()=>{t.style.visibility="",l&&o&&o(mr(l,f))}).catch(y),()=>gr(n)},[s,l,u,h,w,x]);const A=(0,g.useCallback)(()=>{const{current:t}=v;t&&(t.width=0,t.height=0)},[]);return(0,g.useEffect)(()=>A,[A]),(0,p.jsx)("canvas",{className:`${n}__canvas`,dir:"ltr",ref:sa(b,v),style:{display:"block",userSelect:"none"},children:c?(0,p.jsx)(ma,{}):null})}const va=new Set(["base","embed","iframe","link","meta","object","script","style","template"]),ya=new Set(["action","formaction","href","poster","src","xlink:href"]);function wa(t){return function(t){return t.nodeType===Node.ELEMENT_NODE}(t)&&t instanceof HTMLElement}function xa(t){var e;return wa(t)&&!function(t){return wa(t)&&va.has(t.tagName.toLowerCase())}(t)?function(t){const e=document.createElement(t.tagName.toLowerCase());return Array.from(t.attributes).forEach(t=>{const i=t.name.toLowerCase();i.startsWith("on")||"srcdoc"===i||ya.has(i)&&function(t){let e="";for(const i of t){const t=i.charCodeAt(0);t<=32||127===t||(e+=i.toLowerCase())}return e.startsWith("data:")||e.startsWith("javascript:")||e.startsWith("vbscript:")}(t.value)||e.setAttribute(t.name,t.value)}),Array.from(t.childNodes).forEach(t=>{e.append(xa(t))}),e}(t):document.createTextNode(null!==(e=t.textContent)&&void 0!==e?e:"")}function Aa(){const t=aa();Qs(t);const{customTextRenderer:e,onGetTextError:i,onGetTextSuccess:n,onRenderTextLayerError:s,onRenderTextLayerSuccess:r,page:a,pageIndex:o,pageNumber:l,rotate:h,scale:c}=t;Qs(a);const[u,m]=sr(),{value:b,error:v}=u,y=(0,g.useRef)(null);d()(1===Number.parseInt(window.getComputedStyle(document.body).getPropertyValue("--react-pdf-text-layer"),10),"TextLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-text-layer"),(0,g.useEffect)(function(){m({type:"RESET"})},[a,m]),(0,g.useEffect)(function(){if(!a)return;const t=w(a.getTextContent()),e=t;return t.promise.then(t=>{m({type:"RESOLVE",value:t})}).catch(t=>{m({type:"REJECT",error:t})}),()=>gr(e)},[a,m]),(0,g.useEffect)(()=>{void 0!==b&&(!1!==b?b&&n&&n(b):v&&(d()(!1,v.toString()),i&&i(v)))},[b]);const x=(0,g.useCallback)(()=>{r&&r()},[r]),A=(0,g.useCallback)(t=>{fr(t)||(d()(!1,t.toString()),s&&s(t))},[s]);const _=(0,g.useMemo)(()=>a.getViewport({scale:c,rotation:h}),[a,h,c]);return(0,g.useLayoutEffect)(function(){if(!a||!b)return;const{current:t}=y;if(!t)return;t.innerHTML="";const i=a.streamTextContent({includeMarkedContent:!0}),n=new Rn({container:t,textContentSource:i,viewport:_}),s=n;return n.render().then(()=>{const i=document.createElement("div");i.className="endOfContent",t.append(i);const n=t.querySelectorAll('[role="presentation"]');if(e){let t=0;b.items.forEach((i,s)=>{if(!function(t){return"str"in t}(i))return;const r=n[t];if(!r)return;!function(t,e){const i=document.createElement("template");i.innerHTML=e;const n=document.createDocumentFragment();Array.from(i.content.childNodes).forEach(t=>{n.append(xa(t))}),t.replaceChildren(n)}(r,e({pageIndex:o,pageNumber:l,itemIndex:s,...i})),t+=i.str&&i.hasEOL?2:1})}x()}).catch(A),()=>gr(s)},[e,A,x,a,o,l,b,_]),(0,p.jsx)("div",{className:f("react-pdf__Page__textContent","textLayer"),onMouseUp:function(){const t=y.current;t&&t.classList.remove("selecting")},onMouseDown:function(){const t=y.current;t&&t.classList.add("selecting")},ref:y})}const _a=1;function Sa(t){const e={...Jr(),...t},{_className:i="react-pdf__Page",_enableRegisterUnregisterPage:n=!0,canvasBackground:s,canvasRef:r,children:a,className:o,customRenderer:l,customTextRenderer:h,devicePixelRatio:c,error:u="Failed to load the page.",filterAnnotations:m,height:b,inputRef:v,loading:y="Loading page…",noData:x="No page specified.",onGetAnnotationsError:_,onGetAnnotationsSuccess:S,onGetStructTreeError:C,onGetStructTreeSuccess:E,onGetTextError:T,onGetTextSuccess:k,onLoadError:M,onLoadSuccess:D,onRenderAnnotationLayerError:P,onRenderAnnotationLayerSuccess:I,onRenderError:R,onRenderSuccess:L,onRenderTextLayerError:B,onRenderTextLayerSuccess:F,pageColors:O,pageIndex:N,pageNumber:U,pdf:j,registerPage:z,renderAnnotationLayer:H=!0,renderForms:$=!1,renderMode:W="canvas",renderTextLayer:V=!0,rotate:G,scale:q=_a,unregisterPage:X,width:K,...Y}=e,[J,Q]=sr(),{value:Z,error:tt}=J,et=(0,g.useRef)(null);Qs(j);const it=lr(U)?U-1:null!=N?N:null,nt=null!=U?U:lr(N)?N+1:null,st=null!=G?G:Z?Z.rotate:null,rt=(0,g.useMemo)(()=>{if(!Z)return null;let t=1;const e=null!=q?q:_a;if(K||b){const e=Z.getViewport({scale:1,rotation:st});K?t=K/e.width:b&&(t=b/e.height)}return e*t},[b,Z,st,q,K]);(0,g.useEffect)(function(){return()=>{lr(it)&&n&&X&&X(it)}},[n,j,it,X]),(0,g.useEffect)(function(){Q({type:"RESET"})},[Q,j,it]),(0,g.useEffect)(function(){if(!j||!nt)return;const t=w(j.getPage(nt)),e=t;return t.promise.then(t=>{Q({type:"RESOLVE",value:t})}).catch(t=>{Q({type:"REJECT",error:t})}),()=>gr(e)},[Q,j,nt]),(0,g.useEffect)(()=>{void 0!==Z&&(!1!==Z?function(){if(D){if(!Z||!rt)return;D(mr(Z,rt))}if(n&&z){if(!lr(it)||!et.current)return;z(it,et.current)}}():tt&&(d()(!1,tt.toString()),M&&M(tt)))},[Z,rt]);const at=(0,g.useMemo)(()=>lr(it)&&nt&&lr(st)&&lr(rt)?{_className:i,canvasBackground:s,customTextRenderer:h,devicePixelRatio:c,filterAnnotations:m,onGetAnnotationsError:_,onGetAnnotationsSuccess:S,onGetStructTreeError:C,onGetStructTreeSuccess:E,onGetTextError:T,onGetTextSuccess:k,onRenderAnnotationLayerError:P,onRenderAnnotationLayerSuccess:I,onRenderError:R,onRenderSuccess:L,onRenderTextLayerError:B,onRenderTextLayerSuccess:F,page:Z,pageColors:O,pageIndex:it,pageNumber:nt,renderForms:$,renderTextLayer:V,rotate:st,scale:rt}:null,[i,s,h,c,m,_,S,C,E,T,k,P,I,R,L,B,F,Z,O,it,nt,$,V,st,rt]),ot=(0,g.useMemo)(()=>A(Y,()=>Z?rt?mr(Z,rt):void 0:Z),[Y,Z,rt]),lt=`${it}@${rt}/${st}`;function ht(){switch(W){case"custom":return Qs(l),(0,p.jsx)(l,{},`${lt}_custom`);case"none":return null;default:return(0,p.jsx)(ba,{canvasRef:r},`${lt}_canvas`)}}return(0,p.jsx)("div",{className:f(i,o),"data-page-number":nt,ref:sa(v,et),style:{"--scale-round-x":"1px","--scale-round-y":"1px","--scale-factor":"1","--user-unit":`${rt}`,"--total-scale-factor":"calc(var(--scale-factor) * var(--user-unit))",backgroundColor:s||"white",position:"relative",minWidth:"min-content",minHeight:"min-content"},...ot,children:nt?null===j||null==Z?(0,p.jsx)(er,{type:"loading",children:"function"==typeof y?y():y}):!1===j||!1===Z?(0,p.jsx)(er,{type:"error",children:"function"==typeof u?u():u}):function(){if(t=at,!Boolean(null==t?void 0:t.page))throw new Error("page is undefined");var t;const e="function"==typeof a?a(at):a;return(0,p.jsxs)(ra.Provider,{value:at,children:[ht(),V?(0,p.jsx)(Aa,{},`${lt}_text`):null,H?(0,p.jsx)(oa,{},`${lt}_annotations`):null,e]})}():(0,p.jsx)(er,{type:"no-data",children:"function"==typeof x?x():x})})}var Ca=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const Ea=t=>{var{children:e,canvasBackground:i,devicePixelRatio:n,height:s,imageResourcesPath:r,loading:a,error:o,noData:l,pageColors:h,pageIndex:c,pageNumber:d,renderAnnotationLayer:u=!0,renderForms:m=!1,renderMode:f="canvas",renderTextLayer:b=!0,rotate:v,scale:y=1,width:w,loadData:x,renderData:A,errorData:_,annotationsData:S,textData:C,setProps:E}=t,T=Ca(t,["children","canvasBackground","devicePixelRatio","height","imageResourcesPath","loading","error","noData","pageColors","pageIndex","pageNumber","renderAnnotationLayer","renderForms","renderMode","renderTextLayer","rotate","scale","width","loadData","renderData","errorData","annotationsData","textData","setProps"]);const k=(0,g.useContext)(Wr),M=(0,g.useRef)(null),D=(0,g.useRef)(Symbol("pdf-page")),P=null!=d?d:(null!=c?c:0)+1;return(0,g.useEffect)(()=>{if(k)return k.registerPage(D.current,{pageNumber:P,setPageNumber:t=>null==E?void 0:E({pageNumber:t}),scrollIntoView:()=>{var t;return null===(t=M.current)||void 0===t?void 0:t.scrollIntoView()}})},[P,k,E]),(0,p.jsx)($r,Object.assign({},T,{setProps:E,children:(0,p.jsx)(Sa,{inputRef:M,canvasBackground:i,devicePixelRatio:n,height:s,imageResourcesPath:r,loading:a,error:o,noData:l,pageColors:h,pageIndex:c,pageNumber:d,renderAnnotationLayer:u,renderForms:m,renderMode:f,renderTextLayer:b,rotate:v,scale:y,width:w,onLoadSuccess:t=>null==E?void 0:E({loadData:Hr(t),errorData:null}),onLoadError:t=>null==E?void 0:E({errorData:Ur("page-load",t)}),onRenderSuccess:t=>null==E?void 0:E({renderData:Hr(t),errorData:null}),onRenderError:t=>null==E?void 0:E({errorData:Ur("page-render",t)}),onGetAnnotationsSuccess:t=>null==E?void 0:E({annotationsData:{layer:"annotations",count:t.length}}),onGetAnnotationsError:t=>null==E?void 0:E({errorData:Ur("annotations-load",t)}),onRenderAnnotationLayerError:t=>null==E?void 0:E({errorData:Ur("annotations-render",t)}),onGetTextSuccess:t=>null==E?void 0:E({textData:{layer:"text",count:t.items.length}}),onGetTextError:t=>null==E?void 0:E({errorData:Ur("text-load",t)}),onRenderTextLayerError:t=>null==E?void 0:E({errorData:Ur("text-render",t)}),children:e})}))};var Ta=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const ka=t=>{var{children:e,file:i=null,pageNumber:n=1,width:s,height:r,scale:a=1,rotate:o=0,renderTextLayer:l=!0,renderAnnotationLayer:h=!0,renderForms:c=!1,renderMode:d="canvas",canvasBackground:u,devicePixelRatio:m,pageColors:f,options:b={},assetBaseUrl:v,workerSrc:y,imageResourcesPath:w,externalLinkRel:x,externalLinkTarget:A,password:_,numPages:S,documentData:C,loadProgress:E,sourceLoaded:T,errorData:k,passwordData:M,itemClickData:D,pageData:P,renderData:I,annotationsData:R,textData:L,loading:B,error:F,noData:O,loading_state:N,setProps:U}=t,j=Ta(t,["children","file","pageNumber","width","height","scale","rotate","renderTextLayer","renderAnnotationLayer","renderForms","renderMode","canvasBackground","devicePixelRatio","pageColors","options","assetBaseUrl","workerSrc","imageResourcesPath","externalLinkRel","externalLinkTarget","password","numPages","documentData","loadProgress","sourceLoaded","errorData","passwordData","itemClickData","pageData","renderData","annotationsData","textData","loading","error","noData","loading_state","setProps"]);const[z,H]=(0,g.useState)(n),$=null!=B?B:Ar(N)||void 0;(0,g.useEffect)(()=>H(n),[n]);const W=(0,g.useCallback)(t=>{"number"==typeof t&&(H(t),null==U||U({pageNumber:t}))},[U]),V=(0,g.useCallback)(t=>{const{loadData:e,itemClickData:i}=t,n=Ta(t,["loadData","itemClickData"]),s=Object.assign({},n);void 0!==e&&(s.documentData=e),void 0!==i&&(s.itemClickData=i,W(null==i?void 0:i.pageNumber)),Object.keys(s).length>0&&(null==U||U(s))},[U,W]),G=(0,g.useCallback)(t=>{const{loadData:e,pageNumber:i}=t,n=Ta(t,["loadData","pageNumber"]);void 0!==e&&(n.pageData=e),void 0!==i&&W(i),Object.keys(n).length>0&&(null==U||U(n))},[U,W]);return(0,p.jsx)(Gr,Object.assign({},j,{file:i,options:b,assetBaseUrl:v,workerSrc:y,imageResourcesPath:w,externalLinkRel:x,externalLinkTarget:A,renderMode:d,password:_,loading:$,error:F,noData:O,loading_state:N,setProps:V,children:(0,p.jsx)(Ea,{pageNumber:z,width:s,height:r,scale:a,rotate:o,renderTextLayer:l,renderAnnotationLayer:h,renderForms:c,renderMode:d,canvasBackground:u,devicePixelRatio:m,imageResourcesPath:w,pageColors:f,loading:$,error:F,noData:O,setProps:G,children:e})}))},Ma=t=>(0,p.jsx)(ka,Object.assign({},t)),Da=t=>(0,p.jsx)(Ea,Object.assign({},t));function Pa(t){const e={...Jr(),...t},{className:i,linkService:n,onItemClick:s,pageIndex:r,pageNumber:a,pdf:o}=e;Qs(o);const l=lr(a)?a-1:null!=r?r:null,h=null!=a?a:lr(r)?r+1:null;const{className:c,onItemClick:d,...u}=t;return(0,p.jsx)("a",{className:f("react-pdf__Thumbnail",i),href:h?"#":void 0,onClick:function(t){t.preventDefault(),lr(l)&&h&&(Qs(s||n),s?s({pageIndex:l,pageNumber:h}):n&&n.goToPage(h))},children:(0,p.jsx)(Sa,{...u,_className:"react-pdf__Thumbnail__page",_enableRegisterUnregisterPage:!1,renderAnnotationLayer:!1,renderTextLayer:!1})})}var Ia=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const Ra=t=>{var{canvasBackground:e,devicePixelRatio:i,height:n,loading:s,error:r,noData:a,pageColors:o,pageIndex:l,pageNumber:h,renderMode:c="canvas",rotate:d,scale:u=1,width:g,loadData:m,renderData:f,errorData:b,itemClickData:v,setProps:y}=t,w=Ia(t,["canvasBackground","devicePixelRatio","height","loading","error","noData","pageColors","pageIndex","pageNumber","renderMode","rotate","scale","width","loadData","renderData","errorData","itemClickData","setProps"]);return(0,p.jsx)($r,Object.assign({},w,{setProps:y,children:(0,p.jsx)(Pa,{canvasBackground:e,devicePixelRatio:i,height:n,loading:s,error:r,noData:a,pageColors:o,pageIndex:l,pageNumber:h,renderMode:c,rotate:d,scale:u,width:g,onItemClick:({pageIndex:t,pageNumber:e})=>null==y?void 0:y({itemClickData:zr(t,e)}),onLoadSuccess:t=>null==y?void 0:y({loadData:Hr(t),errorData:null}),onLoadError:t=>null==y?void 0:y({errorData:Ur("thumbnail-load",t)}),onRenderSuccess:t=>null==y?void 0:y({renderData:Hr(t),errorData:null}),onRenderError:t=>null==y?void 0:y({errorData:Ur("thumbnail-render",t)})})}))},La=t=>(0,p.jsx)(Ra,Object.assign({},t));return s})());
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):"object"==typeof exports?exports.dash_pdf_components=e(require("react")):t.dash_pdf_components=e(t.React)}(self,t=>(()=>{"use strict";var e={810(t,e,i){var n=i(177),s=i.n(n),r=i(274),a=i.n(r)()(s());a.push([t.id,"/* Copyright 2014 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\n:root {\n --react-pdf-annotation-layer: 1;\n --annotation-unfocused-field-background: url(\"data:image/svg+xml;charset=UTF-8,<svg width='1px' height='1px' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' style='fill:rgba(0, 54, 255, 0.13);'/></svg>\");\n --input-focus-border-color: Highlight;\n --input-focus-outline: 1px solid Canvas;\n --input-unfocused-border-color: transparent;\n --input-disabled-border-color: transparent;\n --input-hover-border-color: black;\n --link-outline: none;\n}\n\n@media screen and (forced-colors: active) {\n :root {\n --input-focus-border-color: CanvasText;\n --input-unfocused-border-color: ActiveText;\n --input-disabled-border-color: GrayText;\n --input-hover-border-color: Highlight;\n --link-outline: 1.5px solid LinkText;\n }\n .annotationLayer .textWidgetAnnotation :is(input, textarea):required,\n .annotationLayer .choiceWidgetAnnotation select:required,\n .annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {\n outline: 1.5px solid selectedItem;\n }\n\n .annotationLayer .linkAnnotation:hover {\n backdrop-filter: invert(100%);\n }\n}\n\n.annotationLayer {\n position: absolute;\n top: 0;\n left: 0;\n pointer-events: none;\n transform-origin: 0 0;\n z-index: 3;\n}\n\n.annotationLayer[data-main-rotation='90'] .norotate {\n transform: rotate(270deg) translateX(-100%);\n}\n.annotationLayer[data-main-rotation='180'] .norotate {\n transform: rotate(180deg) translate(-100%, -100%);\n}\n.annotationLayer[data-main-rotation='270'] .norotate {\n transform: rotate(90deg) translateY(-100%);\n}\n\n.annotationLayer canvas {\n position: absolute;\n width: 100%;\n height: 100%;\n}\n\n.annotationLayer section {\n position: absolute;\n text-align: initial;\n pointer-events: auto;\n box-sizing: border-box;\n margin: 0;\n transform-origin: 0 0;\n}\n\n.annotationLayer .linkAnnotation {\n outline: var(--link-outline);\n}\n\n.textLayer.selecting ~ .annotationLayer section {\n pointer-events: none;\n}\n\n.annotationLayer :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a {\n position: absolute;\n font-size: 1em;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n}\n\n.annotationLayer :is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a:hover {\n opacity: 0.2;\n background: rgba(255, 255, 0, 1);\n box-shadow: 0 2px 10px rgba(255, 255, 0, 1);\n}\n\n.annotationLayer .textAnnotation img {\n position: absolute;\n cursor: pointer;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea),\n.annotationLayer .choiceWidgetAnnotation select,\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input {\n background-image: var(--annotation-unfocused-field-background);\n border: 2px solid var(--input-unfocused-border-color);\n box-sizing: border-box;\n font: calc(9px * var(--total-scale-factor)) sans-serif;\n height: 100%;\n margin: 0;\n vertical-align: top;\n width: 100%;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea):required,\n.annotationLayer .choiceWidgetAnnotation select:required,\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {\n outline: 1.5px solid red;\n}\n\n.annotationLayer .choiceWidgetAnnotation select option {\n padding: 0;\n}\n\n.annotationLayer .buttonWidgetAnnotation.radioButton input {\n border-radius: 50%;\n}\n\n.annotationLayer .textWidgetAnnotation textarea {\n resize: none;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea)[disabled],\n.annotationLayer .choiceWidgetAnnotation select[disabled],\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input[disabled] {\n background: none;\n border: 2px solid var(--input-disabled-border-color);\n cursor: not-allowed;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea):hover,\n.annotationLayer .choiceWidgetAnnotation select:hover,\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input:hover {\n border: 2px solid var(--input-hover-border-color);\n}\n.annotationLayer .textWidgetAnnotation :is(input, textarea):hover,\n.annotationLayer .choiceWidgetAnnotation select:hover,\n.annotationLayer .buttonWidgetAnnotation.checkBox input:hover {\n border-radius: 2px;\n}\n\n.annotationLayer .textWidgetAnnotation :is(input, textarea):focus,\n.annotationLayer .choiceWidgetAnnotation select:focus {\n background: none;\n border: 2px solid var(--input-focus-border-color);\n border-radius: 2px;\n outline: var(--input-focus-outline);\n}\n\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) :focus {\n background-image: none;\n background-color: transparent;\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox :focus {\n border: 2px solid var(--input-focus-border-color);\n border-radius: 2px;\n outline: var(--input-focus-outline);\n}\n\n.annotationLayer .buttonWidgetAnnotation.radioButton :focus {\n border: 2px solid var(--input-focus-border-color);\n outline: var(--input-focus-outline);\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after,\n.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before {\n background-color: CanvasText;\n content: '';\n display: block;\n position: absolute;\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before,\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after {\n height: 80%;\n left: 45%;\n width: 1px;\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::before {\n transform: rotate(45deg);\n}\n\n.annotationLayer .buttonWidgetAnnotation.checkBox input:checked::after {\n transform: rotate(-45deg);\n}\n\n.annotationLayer .buttonWidgetAnnotation.radioButton input:checked::before {\n border-radius: 50%;\n height: 50%;\n left: 30%;\n top: 20%;\n width: 50%;\n}\n\n.annotationLayer .textWidgetAnnotation input.comb {\n font-family: monospace;\n padding-left: 2px;\n padding-right: 0;\n}\n\n.annotationLayer .textWidgetAnnotation input.comb:focus {\n /*\n * Letter spacing is placed on the right side of each character. Hence, the\n * letter spacing of the last character may be placed outside the visible\n * area, causing horizontal scrolling. We avoid this by extending the width\n * when the element has focus and revert this when it loses focus.\n */\n width: 103%;\n}\n\n.annotationLayer .buttonWidgetAnnotation:is(.checkBox, .radioButton) input {\n appearance: none;\n}\n\n.annotationLayer .popupTriggerArea {\n height: 100%;\n width: 100%;\n}\n\n.annotationLayer .fileAttachmentAnnotation .popupTriggerArea {\n position: absolute;\n}\n\n.annotationLayer .popupWrapper {\n position: absolute;\n font-size: calc(9px * var(--total-scale-factor));\n width: 100%;\n min-width: calc(180px * var(--total-scale-factor));\n pointer-events: none;\n}\n\n.annotationLayer .popup {\n position: absolute;\n max-width: calc(180px * var(--total-scale-factor));\n background-color: rgba(255, 255, 153, 1);\n box-shadow: 0 calc(2px * var(--total-scale-factor)) calc(5px * var(--total-scale-factor))\n rgba(136, 136, 136, 1);\n border-radius: calc(2px * var(--total-scale-factor));\n padding: calc(6px * var(--total-scale-factor));\n margin-left: calc(5px * var(--total-scale-factor));\n cursor: pointer;\n font: message-box;\n white-space: normal;\n word-wrap: break-word;\n pointer-events: auto;\n}\n\n.annotationLayer .popup > * {\n font-size: calc(9px * var(--total-scale-factor));\n}\n\n.annotationLayer .popup h1 {\n display: inline-block;\n}\n\n.annotationLayer .popupDate {\n display: inline-block;\n margin-left: calc(5px * var(--total-scale-factor));\n}\n\n.annotationLayer .popupContent {\n border-top: 1px solid rgba(51, 51, 51, 1);\n margin-top: calc(2px * var(--total-scale-factor));\n padding-top: calc(2px * var(--total-scale-factor));\n}\n\n.annotationLayer .richText > * {\n white-space: pre-wrap;\n font-size: calc(9px * var(--total-scale-factor));\n}\n\n.annotationLayer .highlightAnnotation,\n.annotationLayer .underlineAnnotation,\n.annotationLayer .squigglyAnnotation,\n.annotationLayer .strikeoutAnnotation,\n.annotationLayer .freeTextAnnotation,\n.annotationLayer .lineAnnotation svg line,\n.annotationLayer .squareAnnotation svg rect,\n.annotationLayer .circleAnnotation svg ellipse,\n.annotationLayer .polylineAnnotation svg polyline,\n.annotationLayer .polygonAnnotation svg polygon,\n.annotationLayer .caretAnnotation,\n.annotationLayer .inkAnnotation svg polyline,\n.annotationLayer .stampAnnotation,\n.annotationLayer .fileAttachmentAnnotation {\n cursor: pointer;\n}\n\n.annotationLayer section svg {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n}\n\n.annotationLayer .annotationTextContent {\n position: absolute;\n width: 100%;\n height: 100%;\n opacity: 0;\n color: transparent;\n user-select: none;\n pointer-events: none;\n}\n\n.annotationLayer .annotationTextContent span {\n width: 100%;\n display: inline-block;\n}\n",""]);const o=a;i.d(e,["A",0,o])},808(t,e,i){var n=i(177),s=i.n(n),r=i(274),a=i.n(r)()(s());a.push([t.id,"/* Copyright 2014 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\n:root {\n --react-pdf-text-layer: 1;\n}\n\n[data-main-rotation='90'] {\n transform: rotate(90deg) translateY(-100%);\n}\n[data-main-rotation='180'] {\n transform: rotate(180deg) translate(-100%, -100%);\n}\n[data-main-rotation='270'] {\n transform: rotate(270deg) translateX(-100%);\n}\n\n.textLayer {\n color-scheme: only light;\n\n position: absolute;\n text-align: initial;\n inset: 0;\n overflow: clip;\n opacity: 1;\n line-height: 1;\n text-size-adjust: none;\n forced-color-adjust: none;\n transform-origin: 0 0;\n caret-color: CanvasText;\n z-index: 0;\n\n /* We multiply the font size by --min-font-size, and then scale the text\n * elements by 1/--min-font-size. This allows us to effectively ignore the\n * minimum font size enforced by the browser, so that the text layer <span>s\n * can always match the size of the text in the canvas. */\n --min-font-size: 1;\n --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size));\n --min-font-size-inv: calc(1 / var(--min-font-size));\n}\n\n.textLayer :is(span, br) {\n color: transparent;\n position: absolute;\n white-space: pre;\n cursor: text;\n margin: 0;\n transform-origin: 0 0;\n}\n\n.textLayer > :not(.markedContent),\n.textLayer .markedContent span:not(.markedContent) {\n z-index: 1;\n\n --font-height: 0; /* set by text_layer.js */\n font-size: calc(var(--text-scale-factor) * var(--font-height));\n\n --scale-x: 1;\n --rotate: 0deg;\n transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv));\n}\n\n.textLayer .markedContent {\n display: contents;\n}\n\n.textLayer span[role='img'] {\n user-select: none;\n cursor: default;\n}\n\n.textLayer .highlight {\n --highlight-bg-color: rgb(180 0 170 / 0.25);\n --highlight-selected-bg-color: rgb(0 100 0 / 0.25);\n --highlight-backdrop-filter: none;\n --highlight-selected-backdrop-filter: none;\n\n margin: -1px;\n padding: 1px;\n background-color: var(--highlight-bg-color);\n backdrop-filter: var(--highlight-backdrop-filter);\n border-radius: 4px;\n}\n\n@media screen and (forced-colors: active) {\n .textLayer .highlight {\n --highlight-bg-color: Highlight;\n --highlight-selected-bg-color: ButtonText;\n }\n}\n\n.textLayer .highlight.appended {\n position: initial;\n}\n\n.textLayer .highlight.begin {\n border-radius: 4px 0 0 4px;\n}\n\n.textLayer .highlight.end {\n border-radius: 0 4px 4px 0;\n}\n\n.textLayer .highlight.middle {\n border-radius: 0;\n}\n\n.textLayer .highlight.selected {\n background-color: var(--highlight-selected-bg-color);\n backdrop-filter: var(--highlight-selected-backdrop-filter);\n}\n\n.textLayer ::selection {\n background: rgba(0 0 255 / 0.25);\n}\n\n@supports (background: color-mix(in srgb, AccentColor, transparent 75%)) {\n .textLayer ::selection {\n background: color-mix(in srgb, AccentColor, transparent 75%);\n }\n}\n\n/* Avoids https://github.com/mozilla/pdf.js/issues/13840 in Chrome */\n.textLayer br::selection {\n background: transparent;\n}\n\n.textLayer .endOfContent {\n display: block;\n position: absolute;\n inset: 100% 0 0;\n z-index: 0;\n cursor: default;\n user-select: none;\n}\n\n.textLayer.selecting .endOfContent {\n top: 0;\n}\n\n.hiddenCanvasElement {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 0;\n display: none;\n}\n",""]);const o=a;i.d(e,["A",0,o])},274(t){t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var i="",n=void 0!==e[5];return e[4]&&(i+="@supports (".concat(e[4],") {")),e[2]&&(i+="@media ".concat(e[2]," {")),n&&(i+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),i+=t(e),n&&(i+="}"),e[2]&&(i+="}"),e[4]&&(i+="}"),i}).join("")},e.i=function(t,i,n,s,r){"string"==typeof t&&(t=[[null,t,void 0]]);var a={};if(n)for(var o=0;o<this.length;o++){var l=this[o][0];null!=l&&(a[l]=!0)}for(var h=0;h<t.length;h++){var c=[].concat(t[h]);n&&a[c[0]]||(void 0!==r&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=r),i&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=i):c[2]=i),s&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=s):c[4]="".concat(s)),e.push(c))}},e}},177(t){t.exports=function(t){return t[1]}},295(e){e.exports=t}};const i={};function n(t){const s=i[t];if(void 0!==s)return s.exports;const r=i[t]={id:t,exports:{}};return e[t](r,r.exports,n),r.exports}n.n=t=>{const e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.cw=t=>{var e;return()=>{if(t){var i=t;t=0,e={exports:{}},i.call(e.exports,e,e.exports)}return e.exports}},n.d=(t,e)=>{if(Array.isArray(e))for(var i=0;i<e.length;){var s=e[i++],r=e[i++],a=0===r?{enumerable:!0,value:e[i++]}:{enumerable:!0,get:r};n.o(t,s)||Object.defineProperty(t,s,a)}else for(var s in e)n.o(e,s)&&!n.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{let t;n.g.importScripts&&(t=n.g.location+"");const e=n.g.document;if(!t&&e&&("SCRIPT"===e.currentScript?.tagName.toUpperCase()&&(t=e.currentScript.src),!t)){const i=e.getElementsByTagName("script");if(i.length){let e=i.length-1;for(;e>-1&&(!t||!/^https?:/.test(t));)t=i[e--].src}}if(!t)throw new Error("Automatic publicPath is not supported in this browser");t=t.replace(/^blob:|[?#].*$/g,"").replace(/\/[^/]+$/,"/"),n.p=t})(),n.nc=void 0;let s={};n.r(s),n.d(s,{Document:()=>Gr,Outline:()=>ia,PDF:()=>Da,Page:()=>Ma,Thumbnail:()=>La});var r=n.cw(function(t,e){var i=[];function n(t){for(var e=-1,n=0;n<i.length;n++)if(i[n].identifier===t){e=n;break}return e}function s(t,e){for(var s={},a=[],o=0;o<t.length;o++){var l=t[o],h=e.base?l[0]+e.base:l[0],c=s[h]||0,d="".concat(h," ").concat(c);s[h]=c+1;var u=n(d),p={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==u)i[u].references++,i[u].updater(p);else{var g=r(p,e);e.byIndex=o,i.splice(o,0,{identifier:d,updater:g,references:1})}a.push(d)}return a}function r(t,e){var i=e.domAPI(e);i.update(t);return function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap&&e.supports===t.supports&&e.layer===t.layer)return;i.update(t=e)}else i.remove()}}t.exports=function(t,e){var r=s(t=t||[],e=e||{});return function(t){t=t||[];for(var a=0;a<r.length;a++){var o=n(r[a]);i[o].references--}for(var l=s(t,e),h=0;h<r.length;h++){var c=n(r[h]);0===i[c].references&&(i[c].updater(),i.splice(c,1))}r=l}}}),a=n.cw(function(t,e){var i={};t.exports=function(t,e){var n=function(t){if(void 0===i[t]){var e=document.querySelector(t);if(window.HTMLIFrameElement&&e instanceof window.HTMLIFrameElement)try{e=e.contentDocument.head}catch(t){e=null}i[t]=e}return i[t]}(t);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");n.appendChild(e)}}),o=n.cw(function(t,e){t.exports=function(t){var e=document.createElement("style");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}}),l=n.cw(function(t,e){t.exports=function(t){var e=n.nc;e&&t.setAttribute("nonce",e)}}),h=n.cw(function(t,e){t.exports=function(t){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var e=t.insertStyleElement(t);return{update:function(i){!function(t,e,i){var n="";i.supports&&(n+="@supports (".concat(i.supports,") {")),i.media&&(n+="@media ".concat(i.media," {"));var s=void 0!==i.layer;s&&(n+="@layer".concat(i.layer.length>0?" ".concat(i.layer):""," {")),n+=i.css,s&&(n+="}"),i.media&&(n+="}"),i.supports&&(n+="}");var r=i.sourceMap;r&&"undefined"!=typeof btoa&&(n+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r))))," */")),e.styleTagTransform(n,t,e.options)}(e,t,i)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}}),c=n.cw(function(t,e){t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}}),d=n.cw(function(t,e){var i=function(){};t.exports=i}),u={};n.r(u),n.d(u,{dU:()=>Es,ng:()=>L,EA:()=>sn,Tm:()=>Fn,SS:()=>nt,D6:()=>Rn,YE:()=>Ln});const p=window.ReactJSXRuntime||(window.ReactJSXRuntime=function(t){function e(e,i,n){var s={},r=null;if(null!=i)for(var a in void 0!==i.key&&(s.key=""+i.key),i)Object.prototype.hasOwnProperty.call(i,a)&&"key"!==a&&"__self"!==a&&"__source"!==a&&("children"===a?r=i[a]:s[a]=i[a]);return void 0!==n&&(s.key=""+n),null==r?t.createElement(e,s):Array.isArray(r)?t.createElement.apply(t,[e,s].concat(r)):t.createElement(e,s,r)}return{jsx:e,jsxs:e,jsxDEV:e,Fragment:t.Fragment}}(window.React));var g=n(295);function m(t){var e,i,n="";if("string"==typeof t||"number"==typeof t)n+=t;else if("object"==typeof t)if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(i=m(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}const f=function(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=m(t))&&(n&&(n+=" "),n+=e);return n};var b=Object.prototype.hasOwnProperty;function v(t,e,i){for(i of t.keys())if(y(i,e))return i}function y(t,e){var i,n,s;if(t===e)return!0;if(t&&e&&(i=t.constructor)===e.constructor){if(i===Date)return t.getTime()===e.getTime();if(i===RegExp)return t.toString()===e.toString();if(i===Array){if((n=t.length)===e.length)for(;n--&&y(t[n],e[n]););return-1===n}if(i===Set){if(t.size!==e.size)return!1;for(n of t){if((s=n)&&"object"==typeof s&&!(s=v(e,s)))return!1;if(!e.has(s))return!1}return!0}if(i===Map){if(t.size!==e.size)return!1;for(n of t){if((s=n[0])&&"object"==typeof s&&!(s=v(e,s)))return!1;if(!y(n[1],e.get(s)))return!1}return!0}if(i===ArrayBuffer)t=new Uint8Array(t),e=new Uint8Array(e);else if(i===DataView){if((n=t.byteLength)===e.byteLength)for(;n--&&t.getInt8(n)===e.getInt8(n););return-1===n}if(ArrayBuffer.isView(t)){if((n=t.byteLength)===e.byteLength)for(;n--&&t[n]===e[n];);return-1===n}if(!i||"object"==typeof t){for(i in n=0,t){if(b.call(t,i)&&++n&&!b.call(e,i))return!1;if(!(i in e)||!y(t[i],e[i]))return!1}return Object.keys(e).length===n}}return t!=t&&e!=e}function w(t){let e=!1;return{promise:new Promise((i,n)=>{t.then(t=>!e&&i(t)).catch(t=>!e&&n(t))}),cancel(){e=!0}}}const x=["onCopy","onCut","onPaste","onCompositionEnd","onCompositionStart","onCompositionUpdate","onFocus","onBlur","onInput","onInvalid","onReset","onSubmit","onLoad","onError","onKeyDown","onKeyPress","onKeyUp","onAbort","onCanPlay","onCanPlayThrough","onDurationChange","onEmptied","onEncrypted","onEnded","onError","onLoadedData","onLoadedMetadata","onLoadStart","onPause","onPlay","onPlaying","onProgress","onRateChange","onSeeked","onSeeking","onStalled","onSuspend","onTimeUpdate","onVolumeChange","onWaiting","onClick","onContextMenu","onDoubleClick","onMouseDown","onMouseEnter","onMouseLeave","onMouseMove","onMouseOut","onMouseOver","onMouseUp","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onSelect","onTouchCancel","onTouchEnd","onTouchMove","onTouchStart","onPointerDown","onPointerMove","onPointerUp","onPointerCancel","onGotPointerCapture","onLostPointerCapture","onPointerEnter","onPointerLeave","onPointerOver","onPointerOut","onScroll","onWheel","onAnimationStart","onAnimationEnd","onAnimationIteration","onTransitionEnd","onChange","onToggle"];function A(t,e){const i={};for(const n of x){const s=t[n];s&&(i[n]=e?t=>s(t,e(n)):s)}return i}const _=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),S=[.001,0,0,.001,0,0],C=1.35,E=1,T=2,k=4,D=16,M=32,P=64,I=128,R=256,L={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},B="pdfjs_internal_editor_",F={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},O={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},N=0,U=1,j=2,z=3,H=3,$=4,W={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},V={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},G=1,q=2,X=3,K=4,Y=5,J={ERRORS:0,WARNINGS:1,INFOS:5},Q={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},Z=0,tt=1,et=2,it=3,nt={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let st=J.WARNINGS;function rt(t){Number.isInteger(t)&&(st=t)}function at(){return st}function ot(t){st>=J.INFOS&&console.info(`Info: ${t}`)}function lt(t){st>=J.WARNINGS&&console.warn(`Warning: ${t}`)}function ht(t){throw new Error(t)}function ct(t,e){t||ht(e)}function dt(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=decodeURIComponent(escape(t))}catch{}}const n=e?URL.parse(t,e):URL.parse(t);return function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(n)?n:null}function ut(t,e,i=!1){const n=URL.parse(t);return n?(n.hash=e,n.href):i&&dt(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function pt(t,e,i,n=!1){return Object.defineProperty(t,e,{value:i,enumerable:!n,configurable:!0,writable:!1}),i}const gt=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class mt extends gt{constructor(t,e){super(t,"PasswordException"),this.code=e}}class ft extends gt{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class bt extends gt{constructor(t){super(t,"InvalidPDFException")}}class vt extends gt{constructor(t,e,i){super(t,"ResponseException"),this.status=e,this.missing=i}}class yt extends gt{constructor(t){super(t,"FormatError")}}class wt extends gt{constructor(t){super(t,"AbortException")}}function xt(t){"object"==typeof t&&void 0!==t?.length||ht("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const n=[];for(let s=0;s<e;s+=i){const r=Math.min(s+i,e),a=t.subarray(s,r);n.push(String.fromCharCode.apply(null,a))}return n.join("")}function At(t){"string"!=typeof t&&ht("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let n=0;n<e;++n)i[n]=255&t.charCodeAt(n);return i}class _t{static get isLittleEndian(){return pt(this,"isLittleEndian",function(){const t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return pt(this,"isEvalSupported",function(){try{return new Function(""),!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return pt(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return pt(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){const{platform:t,userAgent:e}=navigator;return pt(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCSSRoundSupported(){return pt(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const St=Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0"));class Ct{static makeHexColor(t,e,i){return`#${St[t]}${St[e]}${St[i]}`}static domMatrixToTransform(t){return[t.a,t.b,t.c,t.d,t.e,t.f]}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,i=0){const n=t[i],s=t[i+1];t[i]=n*e[0]+s*e[2]+e[4],t[i+1]=n*e[1]+s*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const n=e[0],s=e[1],r=e[2],a=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],c=t[i+e+1];t[i+e]=h*n+c*r+o,t[i+e+1]=h*s+c*a+l}}static applyInverseTransform(t,e){const i=t[0],n=t[1],s=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-n*e[2]+e[2]*e[5]-e[4]*e[3])/s,t[1]=(-i*e[1]+n*e[0]+e[4]*e[1]-e[5]*e[0])/s}static axialAlignedBoundingBox(t,e,i){const n=e[0],s=e[1],r=e[2],a=e[3],o=e[4],l=e[5],h=t[0],c=t[1],d=t[2],u=t[3];let p=n*h+o,g=p,m=n*d+o,f=m,b=a*c+l,v=b,y=a*u+l,w=y;if(0!==s||0!==r){const t=s*h,e=s*d,i=r*c,n=r*u;p+=i,f+=i,m+=n,g+=n,b+=t,w+=t,y+=e,v+=e}i[0]=Math.min(i[0],p,m,g,f),i[1]=Math.min(i[1],b,y,v,w),i[2]=Math.max(i[2],p,m,g,f),i[3]=Math.max(i[3],b,y,v,w)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const i=t[0],n=t[1],s=t[2],r=t[3],a=i**2+n**2,o=i*s+n*r,l=s**2+r**2,h=(a+l)/2,c=Math.sqrt(h**2-(a*l-o**2));e[0]=Math.sqrt(h+c||1),e[1]=Math.sqrt(h-c||1)}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),n=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>n)return null;const s=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return s>r?null:[i,s,n,r]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t),i[1]=Math.min(i[1],e),i[2]=Math.max(i[2],t),i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,n,s){s[0]=Math.min(s[0],t,i),s[1]=Math.min(s[1],e,n),s[2]=Math.max(s[2],t,i),s[3]=Math.max(s[3],e,n)}static#t(t,e,i,n,s,r,a,o,l,h){if(l<=0||l>=1)return;const c=1-l,d=l*l,u=d*l,p=c*(c*(c*t+3*l*e)+3*d*i)+u*n,g=c*(c*(c*s+3*l*r)+3*d*a)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,n,s,r,a,o,l,h,c,d){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,n,s,r,a,o,-c/h,d));const u=h**2-4*c*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,n,s,r,a,o,(-h+p)/g,d),this.#t(t,e,i,n,s,r,a,o,(-h-p)/g,d)}static bezierBoundingBox(t,e,i,n,s,r,a,o,l){l[0]=Math.min(l[0],t,a),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,a),l[3]=Math.max(l[3],e,o),this.#e(t,i,s,a,e,n,r,o,3*(3*(i-s)-t+a),6*(t-2*i+s),3*(i-t),l),this.#e(t,i,s,a,e,n,r,o,3*(3*(n-r)-e+o),6*(e-2*n+r),3*(n-e),l)}}let Et=null,Tt=null;function kt(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);return crypto.getRandomValues(t),xt(t)}const Dt="pdfjs_internal_id_";function Mt(t,e,i){return Math.min(Math.max(t,e),i)}function Pt(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(xt(t))}"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise(i=>{i(t(...e))})}),"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(t){return t.reduce((t,e)=>t+e,0)});class It{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let n=null;const s=i.name;if("#text"===s)n=i.value;else{if(!It.shouldBuildText(s))return;i?.attributes?.textContent?n=i.attributes.textContent:i.value&&(n=i.value)}if(null!==n&&e.push({str:n}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class Rt{static setupStorage(t,e,i,n,s){const r=n.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==r.value&&(t.textContent=r.value),"print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})});break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(r.value===i.attributes.xfaOn?t.setAttribute("checked",!0):r.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===s)break;t.addEventListener("change",t=>{n.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{if(null!==r.value&&t.setAttribute("value",r.value),"print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})})}break;case"select":if(null!==r.value){t.setAttribute("value",r.value);for(const t of i.children)t.attributes.value===r.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const i=t.target.options,s=-1===i.selectedIndex?"":i[i.selectedIndex].value;n.setValue(e,{value:s})})}}static setAttributes({html:t,element:e,storage:i=null,intent:n,linkService:s}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${n}`);for(const[e,i]of Object.entries(r))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!a||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}a&&s.addLinkAttributes(t,r.href,r.newWindow),i&&r.dataId&&this.setupStorage(t,r.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,n=t.xfaHtml,s=t.intent||"display",r=document.createElement(n.name);n.attributes&&this.setAttributes({html:r,element:n,intent:s,linkService:i});const a="richText"!==s,o=t.div;if(o.append(r),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}a&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===n.children.length){if(n.value){const t=document.createTextNode(n.value);r.append(t),a&&It.shouldBuildText(n.name)&&l.push(t)}return{textDivs:l}}const h=[[n,-1,r]];for(;h.length>0;){const[t,n,r]=h.at(-1);if(n+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);l.push(t),r.append(t);continue}const d=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);if(r.append(d),o.attributes&&this.setAttributes({html:d,element:o,storage:e,intent:s,linkService:i}),o.children?.length>0)h.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);a&&It.shouldBuildText(c)&&l.push(t),d.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const Lt="http://www.w3.org/2000/svg";class Bt{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Ft(t,e="text"){if(Ht(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise((i,n)=>{const s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE)if(200!==s.status&&0!==s.status)n(new Error(s.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void i(s.response)}i(s.responseText)}},s.send(null)})}class Ot{constructor({viewBox:t,userUnit:e,scale:i,rotation:n,offsetX:s=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t,this.userUnit=e,this.scale=i,this.rotation=n,this.offsetX=s,this.offsetY=r,i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,c,d,u,p,g,m,f;switch((n%=360)<0&&(n+=360),n){case 180:h=-1,c=0,d=0,u=1;break;case 90:h=0,c=1,d=1,u=0;break;case 270:h=0,c=-1,d=-1,u=0;break;case 0:h=1,c=0,d=0,u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,u=-u),0===h?(p=Math.abs(l-t[1])*i+s,g=Math.abs(o-t[0])*i+r,m=(t[3]-t[1])*i,f=(t[2]-t[0])*i):(p=Math.abs(o-t[0])*i+s,g=Math.abs(l-t[1])*i+r,m=(t[2]-t[0])*i,f=(t[3]-t[1])*i),this.transform=[h*i,c*i,d*i,u*i,p-h*i*o-d*i*l,g-c*i*o-u*i*l],this.width=m,this.height=f}get rawDims(){const t=this.viewBox;return pt(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:n=this.offsetY,dontFlip:s=!1}={}){return new Ot({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}convertToViewportPoint(t,e){const i=[t,e];return Ct.applyTransform(i,this.transform),i}convertToViewportRectangle(t){const e=[t[0],t[1]];Ct.applyTransform(e,this.transform);const i=[t[2],t[3]];return Ct.applyTransform(i,this.transform),[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){const i=[t,e];return Ct.applyInverseTransform(i,this.transform),i}}class Nt extends gt{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Ut(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function jt(t){return"string"==typeof t&&/\.pdf$/i.test(t)}class zt{started=Object.create(null);times=[];time(t){t in this.started&<(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||lt(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:n,end:s}of this.times)t.push(`${i.padEnd(e)} ${s-n}ms\n`);return t.join("")}}function Ht(t,e){const i=e?URL.parse(t,e):URL.parse(t);return"http:"===i?.protocol||"https:"===i?.protocol}function $t(t){t.preventDefault()}function Wt(t){t.preventDefault(),t.stopPropagation()}class Vt{static#i;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#i.exec(t);if(!e)return null;const i=parseInt(e[1],10);let n=parseInt(e[2],10);n=n>=1&&n<=12?n-1:0;let s=parseInt(e[3],10);s=s>=1&&s<=31?s:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let c=parseInt(e[9],10)||0;return c=c>=0&&c<=59?c:0,"-"===l?(r+=h,a+=c):"+"===l&&(r-=h,a-=c),new Date(Date.UTC(i,n,s,r,a,o))}}function Gt(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map(t=>parseInt(t)):t.startsWith("rgba(")?t.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(lt(`Not a valid color format: "${t}"`),[0,0,0])}function qt(t){const{a:e,b:i,c:n,d:s,e:r,f:a}=t.getTransform();return[e,i,n,s,r,a]}function Xt(t){const{a:e,b:i,c:n,d:s,e:r,f:a}=t.getTransform().invertSelf();return[e,i,n,s,r,a]}function Kt(t,e,i=!1,n=!0){if(e instanceof Ot){const{pageWidth:n,pageHeight:s}=e.rawDims,{style:r}=t,a=_t.isCSSRoundSupported,o=`var(--total-scale-factor) * ${n}px`,l=`var(--total-scale-factor) * ${s}px`,h=a?`round(down, ${o}, var(--scale-round-x))`:`calc(${o})`,c=a?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;i&&e.rotation%180!=0?(r.width=c,r.height=h):(r.width=h,r.height=c)}n&&t.setAttribute("data-main-rotation",e.rotation)}class Yt{constructor(){const{pixelRatio:t}=Yt;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,i,n,s=-1){let r=1/0,a=1/0,o=1/0;(i=Yt.capPixels(i,s))>0&&(r=Math.sqrt(i/(t*e))),-1!==n&&(a=n/t,o=n/e);const l=Math.min(r,a,o);return(this.sx>l||this.sy>l)&&(this.sx=l,this.sy=l,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}}const Jt=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class Qt{static get isDarkMode(){return pt(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}function Zt(t,e){const i=t[0]/255,n=t[1]/255,s=t[2]/255,r=Math.max(i,n,s),a=Math.min(i,n,s),o=(r+a)/2;if(r===a)e[0]=e[1]=0;else{const t=r-a;switch(e[1]=o<.5?t/(r+a):t/(2-r-a),r){case i:e[0]=60*((n-s)/t+(n<s?6:0));break;case n:e[0]=60*((s-i)/t+2);break;case s:e[0]=60*((i-n)/t+4)}}e[2]=o}function te(t,e){const i=t[0],n=t[1],s=t[2],r=(1-Math.abs(2*s-1))*n,a=r*(1-Math.abs(i/60%2-1)),o=s-r/2;switch(Math.floor(i/60)){case 0:e[0]=r+o,e[1]=a+o,e[2]=o;break;case 1:e[0]=a+o,e[1]=r+o,e[2]=o;break;case 2:e[0]=o,e[1]=r+o,e[2]=a+o;break;case 3:e[0]=o,e[1]=a+o,e[2]=r+o;break;case 4:e[0]=a+o,e[1]=o,e[2]=r+o;break;case 5:case 6:e[0]=r+o,e[1]=o,e[2]=a+o}}function ee(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function ie(t,e,i){te(t,i),i.map(ee);const n=.2126*i[0]+.7152*i[1]+.0722*i[2];te(e,i),i.map(ee);const s=.2126*i[0]+.7152*i[1]+.0722*i[2];return n>s?(n+.05)/(s+.05):(s+.05)/(n+.05)}const ne=new Map;function se({html:t,dir:e,className:i},n){const s=document.createDocumentFragment();if("string"==typeof t){const i=document.createElement("p");i.dir=e||"auto";const n=t.split(/(?:\r\n?|\n)/);for(let t=0,e=n.length;t<e;++t){const s=n[t];i.append(document.createTextNode(s)),t<e-1&&i.append(document.createElement("br"))}s.append(i)}else Rt.render({xfaHtml:t,div:s,intent:"richText"});s.firstChild.classList.add("richText",i),n.append(s)}class re{#n=null;#s=null;#r;#a=null;#o=null;#l=null;#h=null;#c=null;static#d=null;constructor(t){this.#r=t,re.#d||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#n=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#r._uiManager._signal;e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("contextmenu",$t,{signal:e}),t.addEventListener("pointerdown",re.#u,{signal:e}));const i=this.#a=document.createElement("div");i.className="buttons",t.append(i);const n=this.#r.toolbarPosition;if(n){const{style:e}=t,i="ltr"===this.#r._uiManager.direction?1-n[0]:n[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*n[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#n}static#u(t){t.stopPropagation()}#p(t){this.#r._focusEventsAllowed=!1,Wt(t)}#g(t){this.#r._focusEventsAllowed=!0,Wt(t)}#m(t){const e=this.#r._uiManager._signal;return e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("focusin",this.#p.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#g.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",$t,{signal:e}),!0)}hide(){this.#n.classList.add("hidden"),this.#s?.hideDropdown()}show(){this.#n.classList.remove("hidden"),this.#o?.shown(),this.#l?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#r,i=document.createElement("button");i.classList.add("basic","deleteButton"),i.tabIndex=0,i.setAttribute("data-l10n-id",re.#d[t]),this.#m(i)&&i.addEventListener("click",t=>{e.delete()},{signal:e._signal}),this.#a.append(i)}get#f(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#m(e),this.#a.append(e,this.#f),this.#o=t}addComment(t,e=null){if(this.#l)return;const i=t.renderForToolbar();if(!i)return;this.#m(i);const n=this.#h=this.#f;e?(this.#a.insertBefore(i,e),this.#a.insertBefore(n,e)):this.#a.append(i,n),this.#l=t,t.toolbar=this}addColorPicker(t){if(this.#s)return;this.#s=t;const e=t.renderButton();this.#m(e),this.#a.append(e,this.#f)}async addEditSignatureButton(t){const e=this.#c=await t.renderEditButton(this.#r);this.#m(e),this.#a.append(e,this.#f)}removeButton(t){if("comment"===t)this.#l?.removeToolbarCommentButton(),this.#l=null,this.#h?.remove(),this.#h=null}async addButton(t,e){switch(t){case"colorPicker":this.addColorPicker(e);break;case"altText":await this.addAltText(e);break;case"editSignature":await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":this.addComment(e)}}async addButtonBefore(t,e,i){const n=this.#a.querySelector(i);n&&"comment"===t&&this.addComment(e,n)}updateEditSignatureButton(t){this.#c&&(this.#c.title=t)}remove(){this.#n.remove(),this.#s?.destroy(),this.#s=null}}class ae{#a=null;#n=null;#b;constructor(t){this.#b=t}#v(){const t=this.#n=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar");const e=this.#b._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",$t,{signal:e});const i=this.#a=document.createElement("div");return i.className="buttons",t.append(i),this.#b.hasCommentManager()&&this.#y("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#b.commentSelection("floating_button")}),this.#y("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#b.highlightSelection("floating_button")}),t}#w(t,e){let i=0,n=0;for(const s of t){const t=s.y+s.height;if(t<i)continue;const r=s.x+(e?s.width:0);t>i?(n=r,i=t):e?r>n&&(n=r):r<n&&(n=r)}return[e?1-n:n,i]}show(t,e,i){const[n,s]=this.#w(e,i),{style:r}=this.#n||=this.#v();t.append(this.#n),r.insetInlineEnd=100*n+"%",r.top=`calc(${100*s}% + var(--editor-toolbar-vert-offset))`}hide(){this.#n.remove()}#y(t,e,i,n){const s=document.createElement("button");s.classList.add("basic",t),s.tabIndex=0,s.setAttribute("data-l10n-id",e);const r=document.createElement("span");s.append(r),r.className="visuallyHidden",r.setAttribute("data-l10n-id",i);const a=this.#b._signal;a instanceof AbortSignal&&!a.aborted&&(s.addEventListener("contextmenu",$t,{signal:a}),s.addEventListener("click",n,{signal:a})),this.#a.append(s)}}function oe(t,e,i){for(const n of i)e.addEventListener(n,t[n].bind(t))}class le{#x=0;get id(){return`${B}${this.#x++}`}}class he{#A=kt();#x=0;#_=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';return pt(this,"_isSVGFittingCanvas",e.decode().then(()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0])))}async#S(t,e){this.#_||=new Map;let i=this.#_.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#A}_${this.#x++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await Ft(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=he._isSVGFittingCanvas,n=new FileReader,s=new Image,r=new Promise((t,r)=>{s.onload=()=>{i.bitmap=s,i.isSvg=!0,t()},n.onload=async()=>{const t=i.svgUrl=n.result;s.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},s.onerror=n.onerror=r});n.readAsDataURL(t),await r}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){lt(t),i=null}return this.#_.set(t,i),i&&this.#_.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:n,type:s}=t;return this.#S(`${e}_${i}_${n}_${s}`,t)}async getFromUrl(t){return this.#S(t,t)}async getFromBlob(t,e){const i=await e;return this.#S(t,i)}async getFromId(t){this.#_||=new Map;const e=this.#_.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#_||=new Map;let i=this.#_.get(t);if(i?.bitmap)return i.refCounter+=1,i;const n=new OffscreenCanvas(e.width,e.height);return n.getContext("2d").drawImage(e,0,0),i={bitmap:n.transferToImageBitmap(),id:`image_${this.#A}_${this.#x++}`,refCounter:1,isSvg:!1},this.#_.set(t,i),this.#_.set(i.id,i),i}getSvgUrl(t){const e=this.#_.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#_||=new Map;const e=this.#_.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#A}_`)}}class ce{#C=[];#E=!1;#T;#k=-1;constructor(t=128){this.#T=t}add({cmd:t,undo:e,post:i,mustExec:n,type:s=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){if(n&&t(),this.#E)return;const o={cmd:t,undo:e,post:i,type:s};if(-1===this.#k)return this.#C.length>0&&(this.#C.length=0),this.#k=0,void this.#C.push(o);if(r&&this.#C[this.#k].type===s)return a&&(o.undo=this.#C[this.#k].undo),void(this.#C[this.#k]=o);const l=this.#k+1;l===this.#T?this.#C.splice(0,1):(this.#k=l,l<this.#C.length&&this.#C.splice(l)),this.#C.push(o)}undo(){if(-1===this.#k)return;this.#E=!0;const{undo:t,post:e}=this.#C[this.#k];t(),e?.(),this.#E=!1,this.#k-=1}redo(){if(this.#k<this.#C.length-1){this.#k+=1,this.#E=!0;const{cmd:t,post:e}=this.#C[this.#k];t(),e?.(),this.#E=!1}}hasSomethingToUndo(){return-1!==this.#k}hasSomethingToRedo(){return this.#k<this.#C.length-1}cleanType(t){if(-1!==this.#k){for(let e=this.#k;e>=0;e--)if(this.#C[e].type!==t)return this.#C.splice(e+1,this.#k-e),void(this.#k=e);this.#C.length=0,this.#k=-1}}destroy(){this.#C=null}}class de{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=_t.platform;for(const[i,n,s={}]of t)for(const t of i){const i=t.startsWith("mac+");e&&i?(this.callbacks.set(t.slice(4),{callback:n,options:s}),this.allKeys.add(t.split("+").at(-1))):e||i||(this.callbacks.set(t,{callback:n,options:s}),this.allKeys.add(t.split("+").at(-1)))}}#D(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#D(e));if(!i)return;const{callback:n,options:{bubbles:s=!1,args:r=[],checker:a=null}}=i;a&&!a(t,e)||(n.bind(t,...r,e)(),s||Wt(e))}}class ue{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return function(t){const e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(const i of t.keys()){e.style.color=i;const n=window.getComputedStyle(e).color;t.set(i,Gt(n))}e.remove()}(t),pt(this,"_colors",t)}convert(t){const e=Gt(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every((t,i)=>t===e[i]))return ue._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Ct.makeHexColor(...e):t}}class pe{#M=new AbortController;#P=null;#I=null;#R=new Map;#L=new Map;#B=null;#F=null;#O=null;#N=new ce;#U=null;#j=null;#z=null;#H=0;#$=new Set;#W=null;#V=null;#G=new Set;_editorUndoBar=null;#q=!1;#X=!1;#K=!1;#Y=null;#J=null;#Q=null;#Z=null;#tt=!1;#et=null;#it=new le;#nt=!1;#st=!1;#rt=!1;#at=null;#ot=null;#lt=null;#ht=null;#ct=null;#dt=F.NONE;#ut=new Set;#pt=null;#gt=null;#mt=null;#ft=null;#bt=null;#vt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#yt=[0,0];#wt=null;#xt=null;#At=null;#_t=null;#St=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=pe.prototype,e=t=>t.#xt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},n=this.TRANSLATE_SMALL,s=this.TRANSLATE_BIG;return pt(this,"_keyboardManager",new de([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#xt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#xt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}]]))}constructor(t,e,i,n,s,r,a,o,l,h,c,d,u,p,g,m){const f=this._signal=this.#M.signal;this.#xt=t,this.#At=e,this.#_t=i,this.#B=n,this.#U=s,this.#gt=r,this.#bt=o,this._eventBus=a,a._on("editingaction",this.onEditingAction.bind(this),{signal:f}),a._on("pagechanging",this.onPageChanging.bind(this),{signal:f}),a._on("scalechanging",this.onScaleChanging.bind(this),{signal:f}),a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:f}),a._on("setpreference",this.onSetPreference.bind(this),{signal:f}),a._on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),{signal:f}),window.addEventListener("pointerdown",()=>{this.#st=!0},{capture:!0,signal:f}),window.addEventListener("pointerup",()=>{this.#st=!1},{capture:!0,signal:f}),this.#Ct(),this.#Et(),this.#Tt(),this.#F=o.annotationStorage,this.#Y=o.filterFactory,this.#mt=l,this.#Z=h||null,this.#q=c,this.#X=d,this.#K=u,this.#ct=p||null,this.viewParameters={realScale:Bt.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=g||null,this._supportsPinchToZoom=!1!==m,s?.setSidebarUiManager(this)}destroy(){this.#St?.resolve(),this.#St=null,this.#M?.abort(),this.#M=null,this._signal=null;for(const t of this.#L.values())t.destroy();this.#L.clear(),this.#R.clear(),this.#G.clear(),this.#ht?.clear(),this.#P=null,this.#ut.clear(),this.#N.destroy(),this.#B?.destroy(),this.#U?.destroy(),this.#gt?.destroy(),this.#et?.hide(),this.#et=null,this.#lt?.destroy(),this.#lt=null,this.#I=null,this.#J&&(clearTimeout(this.#J),this.#J=null),this.#wt&&(clearTimeout(this.#wt),this.#wt=null),this._editorUndoBar?.destroy(),this.#bt=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#ct}get useNewAltTextFlow(){return this.#X}get useNewAltTextWhenAddingImage(){return this.#K}get hcmFilter(){return pt(this,"hcmFilter",this.#mt?this.#Y.addHCMFilter(this.#mt.foreground,this.#mt.background):"none")}get direction(){return pt(this,"direction",getComputedStyle(this.#xt).direction)}get _highlightColors(){return pt(this,"_highlightColors",this.#Z?new Map(this.#Z.split(",").map(t=>((t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase(),t))):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return pt(this,"highlightColors",null);const e=new Map,i=!!this.#mt;for(const[n,s]of t){const t=n.endsWith("_HCM");i&&t?e.set(n.replace("_HCM",""),s):i||t||e.set(n,s)}return pt(this,"highlightColors",e)}get highlightColorNames(){return pt(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#z=t}setMainHighlightColorPicker(t){this.#lt=t}editAltText(t,e=!1){this.#B?.editAltText(this,t,e)}hasCommentManager(){return!!this.#U}editComment(t,e,i,n){this.#U?.showDialog(this,t,e,i,n)}selectComment(t,e){const i=this.#L.get(t),n=i?.getEditorByUID(e);n?.toggleComment(!0,!0)}updateComment(t){this.#U?.updateComment(t.getData())}updatePopupColor(t){this.#U?.updatePopupColor(t)}removeComment(t){this.#U?.removeComments([t.uid])}toggleComment(t,e,i=void 0){this.#U?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#U?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#U?.dialogElement||null}async waitForEditorsRendered(t){if(this.#L.has(t-1))return;const{resolve:e,promise:i}=Promise.withResolvers(),n=i=>{i.pageNumber===t&&(this._eventBus._off("editorsrendered",n),e())};this._eventBus.on("editorsrendered",n),await i}getSignature(t){this.#gt?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#gt}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#K=e}onPageChanging({pageNumber:t}){this.#H=t-1}focusMainContainer(){this.#xt.focus()}findParent(t,e){for(const i of this.#L.values()){const{x:n,y:s,width:r,height:a}=i.div.getBoundingClientRect();if(t>=n&&t<=n+r&&e>=s&&e<=s+a)return i}return null}disableUserSelect(t=!1){this.#At.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#G.add(t)}removeShouldRescale(t){this.#G.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Bt.PDF_TO_CSS_UNITS;for(const t of this.#G)t.onScaleChanging();this.#z?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#kt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Dt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#L.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t="",e=!1){const i=document.getSelection();if(!i||i.isCollapsed)return;const{anchorNode:n,anchorOffset:s,focusNode:r,focusOffset:a}=i,o=i.toString(),l=this.#kt(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();const c=this.#Dt(l),d=this.#dt===F.NONE,u=()=>{const i=c?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:n,anchorOffset:s,focusNode:r,focusOffset:a,text:o});d&&this.showAllEditors("highlight",!0,!0),e&&i?.editComment()};d?this.switchToMode(F.HIGHLIGHT,u):u()}commentSelection(t=""){this.highlightSelection(t,!0)}#Mt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#kt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#et||=new ae(this),this.#et.show(e,i,"ltr"===this.direction))}getAndRemoveDataFromAnnotationStorage(t){if(!this.#F)return null;const e=`${B}${t}`,i=this.#F.getRawValue(e);return i&&this.#F.remove(e),i}addToAnnotationStorage(t){t.isEmpty()||!this.#F||this.#F.has(t.id)||this.#F.setValue(t.id,t)}a11yAlert(t,e=null){const i=this.#_t;i&&(i.setAttribute("data-l10n-id",t),e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args"))}#Pt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#pt&&(this.#et?.hide(),this.#pt=null,this.#It({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#pt)return;const i=this.#kt(t).closest(".textLayer");if(i){if(this.#et?.hide(),this.#pt=e,this.#It({hasSelectedText:!0}),(this.#dt===F.HIGHLIGHT||this.#dt===F.NONE)&&(this.#dt===F.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#tt=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#dt===F.HIGHLIGHT?this.#Dt(i):null;if(t?.toggleDrawing(),this.#st){const e=new AbortController,i=this.combinedSignal(e),n=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#Rt("main_toolbar"))};window.addEventListener("pointerup",n,{signal:i}),window.addEventListener("blur",n,{signal:i})}else t?.toggleDrawing(!0),this.#Rt("main_toolbar")}}else this.#pt&&(this.#et?.hide(),this.#pt=null,this.#It({hasSelectedText:!1}))}#Rt(t=""){this.#dt===F.HIGHLIGHT?this.highlightSelection(t):this.#q&&this.#Mt()}#Ct(){document.addEventListener("selectionchange",this.#Pt.bind(this),{signal:this._signal})}#Lt(){if(this.#Q)return;this.#Q=new AbortController;const t=this.combinedSignal(this.#Q);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Bt(){this.#Q?.abort(),this.#Q=null}blur(){if(this.isShiftKeyDown=!1,this.#tt&&(this.#tt=!1,this.#Rt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#ut)if(e.div.contains(t)){this.#ot=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#ot)return;const[t,e]=this.#ot;this.#ot=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#Tt(){if(this.#at)return;this.#at=new AbortController;const t=this.combinedSignal(this.#at);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Ft(){this.#at?.abort(),this.#at=null}#Ot(){if(this.#j)return;this.#j=new AbortController;const t=this.combinedSignal(this.#j);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Nt(){this.#j?.abort(),this.#j=null}#Et(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Tt(),this.#Ot()}removeEditListeners(){this.#Ft(),this.#Nt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#V)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#V)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#P?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#ut){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#V)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void lt(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const n=this.currentLayer;try{const t=[];for(const e of i){const i=await n.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#Ut(e);this.#jt(t)},s=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:s,mustExec:!0})}catch(t){lt(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#dt===F.NONE||this.isEditorHandlingKeyboard||pe._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#tt&&(this.#tt=!1,this.#Rt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}#It(t){Object.entries(t).some(([t,e])=>this.#vt[t]!==e)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#vt,t)}),this.#dt===F.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#zt([[O.HIGHLIGHT_FREE,!0]]))}#zt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Lt(),this.#Ot(),this.#It({isEditing:this.#dt!==F.NONE,isEmpty:this.#Ht(),hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:this.#N.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Bt(),this.#Nt(),this.#It({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#V){this.#V=t;for(const t of this.#V)this.#zt(t.defaultPropertiesToUpdate)}}getId(){return this.#it.id}get currentLayer(){return this.#L.get(this.#H)}getLayer(t){return this.#L.get(t)}get currentPageIndex(){return this.#H}addLayer(t){this.#L.set(t.pageIndex,t),this.#nt?t.enable():t.disable()}removeLayer(t){this.#L.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,n=!1,s=!1){if(this.#dt!==t&&(!this.#St||(await this.#St.promise,this.#St))){if(this.#St=Promise.withResolvers(),this.#z?.commitOrRemove(),this.#dt===F.POPUP&&this.#U?.hideSidebar(),this.#U?.destroyPopup(),this.#dt=t,t===F.NONE){this.setEditingState(!1),this.#$t();for(const t of this.#R.values())t.hideStandaloneCommentButton();return this._editorUndoBar?.hide(),this.toggleComment(null),void this.#St.resolve()}for(const t of this.#R.values())t.addStandaloneCommentButton();t===F.SIGNATURE&&await(this.#gt?.loadSignatures()),this.setEditingState(!0),await this.#Wt(),this.unselectAll();for(const e of this.#L.values())e.updateMode(t);if(t===F.POPUP){this.#I||=await this.#bt.getAnnotationsByType(new Set(this.#V.map(t=>t._editorType)));const t=new Set,e=[];for(const i of this.#R.values()){const{annotationElementId:n,hasComment:s,deleted:r}=i;n&&t.add(n),s&&!r&&e.push(i.getData())}for(const i of this.#I){const{id:n,popupRef:s,contentsObj:r}=i;s&&r?.str&&!t.has(n)&&!this.#$.has(n)&&e.push(i)}this.#U?.showSidebar(e)}if(!e)return i&&this.addNewEditorFromKeyboard(),void this.#St.resolve();for(const t of this.#R.values())t.uid===e?(this.setSelected(t),s?t.editComment():n?t.enterInEditMode():t.focus()):t.unselect();this.#St.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#dt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#V){switch(t){case O.CREATE:return void this.currentLayer.addNewEditor(e);case O.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#ft||=new Map).set(t,e),this.showAllEditors("highlight",e)}if(this.hasSelection)for(const i of this.#ut)i.updateParams(t,e);else for(const i of this.#V)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#R.values())i.editorType===t&&i.show(e);(this.#ft?.get(O.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#zt([[O.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#rt!==t){this.#rt=t;for(const e of this.#L.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Wt(){if(!this.#nt){this.#nt=!0;const t=[];for(const e of this.#L.values())t.push(e.enable());await Promise.all(t);for(const t of this.#R.values())t.enable()}}#$t(){if(this.unselectAll(),this.#nt){this.#nt=!1;for(const t of this.#L.values())t.disable();for(const t of this.#R.values())t.disable()}}*getEditors(t){for(const e of this.#R.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#R.get(t)}addEditor(t){this.#R.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#J&&clearTimeout(this.#J),this.#J=setTimeout(()=>{this.focusMainContainer(),this.#J=null},0)),this.#R.delete(t.id),t.annotationElementId&&this.#ht?.delete(t.annotationElementId),this.unselect(t),t.annotationElementId&&this.#$.has(t.annotationElementId)||this.#F?.remove(t.id)}addDeletedAnnotationElement(t){this.#$.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#$.has(t)}removeDeletedAnnotationElement(t){this.#$.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#Ut(t){const e=this.#L.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#P!==t&&(this.#P=t,t&&this.#zt(t.propertiesToUpdate))}get#Vt(){let t=null;for(t of this.#ut);return t}updateUI(t){this.#Vt===t&&this.#zt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#zt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#ut.has(t))return this.#ut.delete(t),t.unselect(),void this.#It({hasSelectedEditor:this.hasSelection});this.#ut.add(t),t.select(),this.#zt(t.propertiesToUpdate),this.#It({hasSelectedEditor:!0})}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.id}),this.#z?.commitOrRemove();for(const e of this.#ut)e!==t&&e.unselect();this.#ut.clear(),this.#ut.add(t),t.select(),this.#zt(t.propertiesToUpdate),this.#It({hasSelectedEditor:!0})}isSelected(t){return this.#ut.has(t)}get firstSelectedEditor(){return this.#ut.values().next().value}unselect(t){t.unselect(),this.#ut.delete(t),this.#It({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#ut.size}get isEnterHandled(){return 1===this.#ut.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#N.undo(),this.#It({hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Ht()}),this._editorUndoBar?.hide()}redo(){this.#N.redo(),this.#It({hasSomethingToUndo:!0,hasSomethingToRedo:this.#N.hasSomethingToRedo(),isEmpty:this.#Ht()})}addCommands(t){this.#N.add(t),this.#It({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Ht()})}cleanUndoStack(t){this.#N.cleanType(t)}#Ht(){if(0===this.#R.size)return!0;if(1===this.#R.size)for(const t of this.#R.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#ut],i=()=>{for(const t of e)this.#Ut(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo:i,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#jt(t){for(const t of this.#ut)t.unselect();this.#ut.clear();for(const e of t)e.isEmpty()||(this.#ut.add(e),e.select());this.#It({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#ut)t.commit();this.#jt(this.#R.values())}unselectAll(){if((!this.#P||(this.#P.commitOrRemove(),this.#dt===F.NONE))&&!this.#z?.commitOrRemove()&&this.hasSelection){for(const t of this.#ut)t.unselect();this.#ut.clear(),this.#It({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#yt[0]+=t,this.#yt[1]+=e;const[n,s]=this.#yt,r=[...this.#ut];this.#wt&&clearTimeout(this.#wt),this.#wt=setTimeout(()=>{this.#wt=null,this.#yt[0]=this.#yt[1]=0,this.addCommands({cmd:()=>{for(const t of r)this.#R.has(t.id)&&(t.translateInPage(n,s),t.translationDone())},undo:()=>{for(const t of r)this.#R.has(t.id)&&(t.translateInPage(-n,-s),t.translationDone())},mustExec:!1})},1e3);for(const i of r)i.translateInPage(t,e),i.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#W=new Map;for(const t of this.#ut)this.#W.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#W)return!1;this.disableUserSelect(!1);const t=this.#W;this.#W=null;let e=!1;for(const[{x:i,y:n,pageIndex:s},r]of t)r.newX=i,r.newY=n,r.newPageIndex=s,e||=i!==r.savedX||n!==r.savedY||s!==r.savedPageIndex;if(!e)return!1;const i=(t,e,i,n)=>{if(this.#R.has(t.id)){const s=this.#L.get(n);s?t._setParentAndPosition(s,e,i):(t.pageIndex=n,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:n,newY:s,newPageIndex:r}]of t)i(e,n,s,r)},undo:()=>{for(const[e,{savedX:n,savedY:s,savedPageIndex:r}]of t)i(e,n,s,r)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#W)for(const i of this.#W.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#ut.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#dt}isEditingMode(){return this.#dt!==F.NONE}get imageManager(){return pt(this,"imageManager",new he)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,n=e.rangeCount;i<n;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;const{x:i,y:n,width:s,height:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(t,e,a,o)=>({x:(e-n)/r,y:1-(t+a-i)/s,width:o/r,height:a/s});break;case"180":a=(t,e,a,o)=>({x:1-(t+a-i)/s,y:1-(e+o-n)/r,width:a/s,height:o/r});break;case"270":a=(t,e,a,o)=>({x:1-(e+o-n)/r,y:(t-i)/s,width:o/r,height:a/s});break;default:a=(t,e,a,o)=>({x:(t-i)/s,y:(e-n)/r,width:a/s,height:o/r})}const o=[];for(let t=0,i=e.rangeCount;t<i;t++){const i=e.getRangeAt(t);if(!i.collapsed)for(const{x:t,y:e,width:n,height:s}of i.getClientRects())0!==n&&0!==s&&o.push(a(t,e,n,s))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#O||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#O?.delete(t)}renderAnnotationElement(t){const e=this.#O?.get(t.data.id);if(!e)return;const i=this.#F.getRawValue(e);i&&(this.#dt!==F.NONE||i.hasBeenModified)&&i.renderAnnotationElement(t)}setMissingCanvas(t,e,i){const n=this.#ht?.get(t);n&&(n.setCanvas(e,i),this.#ht.delete(t))}addMissingCanvas(t,e){(this.#ht||=new Map).set(t,e)}}class ge{#o=null;#Gt=!1;#qt=null;#Xt=null;#Kt=null;#Yt=null;#Jt=!1;#Qt=null;#r=null;#Zt=null;#te=null;#ee=!1;static#ie=null;static _l10n=null;constructor(t){this.#r=t,this.#ee=t._uiManager.useNewAltTextFlow,ge.#ie||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){ge._l10n??=t}async render(){const t=this.#qt=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#Xt=document.createElement("span");t.append(e),this.#ee?(t.classList.add("new"),t.setAttribute("data-l10n-id",ge.#ie.missing),e.setAttribute("data-l10n-id",ge.#ie["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const i=this.#r._uiManager._signal;t.addEventListener("contextmenu",$t,{signal:i}),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const n=t=>{t.preventDefault(),this.#r._uiManager.editAltText(this.#r),this.#ee&&this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#ne}})};return t.addEventListener("click",n,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#Jt=!0,n(e))},{signal:i}),await this.#se(),t}get#ne(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){this.#qt&&(this.#qt.focus({focusVisible:this.#Jt}),this.#Jt=!1)}isEmpty(){return this.#ee?null===this.#o:!this.#o&&!this.#Gt}hasData(){return this.#ee?null!==this.#o||!!this.#Zt:this.isEmpty()}get guessedText(){return this.#Zt}async setGuessedText(t){null===this.#o&&(this.#Zt=t,this.#te=await ge._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#se())}toggleAltTextBadge(t=!1){if(!this.#ee||this.#o)return this.#Qt?.remove(),void(this.#Qt=null);if(!this.#Qt){const t=this.#Qt=document.createElement("div");t.className="noAltTextBadge",this.#r.div.append(t)}this.#Qt.classList.toggle("hidden",!t)}serialize(t){let e=this.#o;return t||this.#Zt!==e||(e=this.#te),{altText:e,decorative:this.#Gt,guessedText:this.#Zt,textWithDisclaimer:this.#te}}get data(){return{altText:this.#o,decorative:this.#Gt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:n,cancel:s=!1}){i&&(this.#Zt=i,this.#te=n),this.#o===t&&this.#Gt===e||(s||(this.#o=t,this.#Gt=e),this.#se())}toggle(t=!1){this.#qt&&(!t&&this.#Yt&&(clearTimeout(this.#Yt),this.#Yt=null),this.#qt.disabled=!t)}shown(){this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#ne}})}destroy(){this.#qt?.remove(),this.#qt=null,this.#Xt=null,this.#Kt=null,this.#Qt?.remove(),this.#Qt=null}async#se(){const t=this.#qt;if(!t)return;if(this.#ee){if(t.classList.toggle("done",!!this.#o),t.setAttribute("data-l10n-id",ge.#ie[this.#ne]),this.#Xt?.setAttribute("data-l10n-id",ge.#ie[`${this.#ne}-label`]),!this.#o)return void this.#Kt?.remove()}else{if(!this.#o&&!this.#Gt)return t.classList.remove("done"),void this.#Kt?.remove();t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#Kt;if(!e){this.#Kt=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#r.id}`;const i=100,n=this.#r._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#Yt),this.#Yt=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#Yt=setTimeout(()=>{this.#Yt=null,this.#Kt.classList.add("show"),this.#r._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#Yt&&(clearTimeout(this.#Yt),this.#Yt=null),this.#Kt?.classList.remove("show")},{signal:n})}this.#Gt?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#o),e.parentNode||t.append(e);const i=this.#r.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class me{#re=null;#ae=null;#oe=!1;#r=null;#le=null;#he=null;#ce=null;#de=null;#ue=!1;#pe=null;constructor(t){this.#r=t}renderForToolbar(){const t=this.#ae=document.createElement("button");return t.className="comment",this.#v(t,!1)}renderForStandalone(){const t=this.#re=document.createElement("button");t.className="annotationCommentButton";const e=this.#r.commentButtonPosition;if(e){const{style:i}=t;i.insetInlineEnd=`calc(${100*("ltr"===this.#r._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`,i.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const n=this.#r.commentButtonColor;n&&(i.backgroundColor=n)}return this.#v(t,!0)}focusButton(){setTimeout(()=>{(this.#re??this.#ae)?.focus()},0)}onUpdatedColor(){if(!this.#re)return;const t=this.#r.commentButtonColor;t&&(this.#re.style.backgroundColor=t),this.#r._uiManager.updatePopupColor(this.#r)}get commentButtonWidth(){return(this.#re?.getBoundingClientRect().width??0)/this.#r.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#pe)return this.#pe;if(!this.#re)return null;const{x:t,y:e,height:i}=this.#re.getBoundingClientRect(),{x:n,y:s,width:r,height:a}=this.#r.parent.boundingClientRect;return[(t-n)/r,(e+i-s)/a]}set commentPopupPositionInLayer(t){this.#pe=t}hasDefaultPopupPosition(){return null===this.#pe}removeStandaloneCommentButton(){this.#re?.remove(),this.#re=null}removeToolbarCommentButton(){this.#ae?.remove(),this.#ae=null}setCommentButtonStates({selected:t,hasPopup:e}){this.#re&&(this.#re.classList.toggle("selected",t),this.#re.ariaExpanded=e)}#v(t,e){if(!this.#r._uiManager.hasCommentManager())return null;t.tabIndex="0",t.ariaHasPopup="dialog",e?(t.ariaControls="commentPopup",t.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(t.ariaControlsElements=[this.#r._uiManager.getCommentDialogElement()],t.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-button"));const i=this.#r._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",$t,{signal:i}),e&&(t.addEventListener("focusin",t=>{this.#r._focusEventsAllowed=!1,Wt(t)},{capture:!0,signal:i}),t.addEventListener("focusout",t=>{this.#r._focusEventsAllowed=!0,Wt(t)},{capture:!0,signal:i})),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const n=e=>{e.preventDefault(),t===this.#ae?this.edit():this.#r.toggleComment(!0)};return t.addEventListener("click",n,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#oe=!0,n(e))},{signal:i}),t.addEventListener("pointerenter",()=>{this.#r.toggleComment(!1,!0)},{signal:i}),t.addEventListener("pointerleave",()=>{this.#r.toggleComment(!1,!1)},{signal:i}),t}edit(t){const e=this.commentPopupPositionInLayer;let i,n;if(e)[i,n]=e;else{[i,n]=this.#r.commentButtonPosition;const{width:t,height:e,x:s,y:r}=this.#r;i=s+i*t,n=r+n*e}const s=this.#r.parent.boundingClientRect,{x:r,y:a,width:o,height:l}=s;this.#r._uiManager.editComment(this.#r,r+i*o,a+n*l,{...t,parentDimensions:s})}finish(){this.#ae&&(this.#ae.focus({focusVisible:this.#oe}),this.#oe=!1)}isDeleted(){return this.#ue||""===this.#ce}isEmpty(){return null===this.#ce}hasBeenEdited(){return this.isDeleted()||this.#ce!==this.#le}serialize(){return this.data}get data(){return{text:this.#ce,richText:this.#he,date:this.#de,deleted:this.isDeleted()}}set data(t){if(t!==this.#ce&&(this.#he=null),null===t)return this.#ce="",void(this.#ue=!0);this.#ce=t,this.#de=new Date,this.#ue=!1}setInitialText(t,e=null){this.#le=t,this.data=t,this.#de=null,this.#he=e}shown(){}destroy(){this.#ae?.remove(),this.#ae=null,this.#re?.remove(),this.#re=null,this.#ce="",this.#he=null,this.#de=null,this.#r=null,this.#oe=!1,this.#ue=!1}}class fe{#xt;#ge=!1;#me=null;#fe;#be;#ve;#ye;#we=null;#xe;#Ae=null;#_e;#Se=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:n=null,onPinching:s=null,onPinchEnd:r=null,signal:a}){this.#xt=t,this.#me=i,this.#fe=e,this.#be=n,this.#ve=s,this.#ye=r,this.#_e=new AbortController,this.#xe=AbortSignal.any([a,this.#_e.signal]),t.addEventListener("touchstart",this.#Ce.bind(this),{passive:!1,signal:this.#xe})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Yt.pixelRatio}#Ce(t){if(this.#fe?.())return;if(1===t.touches.length){if(this.#we)return;const t=this.#we=new AbortController,e=AbortSignal.any([this.#xe,t.signal]),i=this.#xt,n={capture:!0,signal:e,passive:!1},s=t=>{"touch"===t.pointerType&&(this.#we?.abort(),this.#we=null)};return i.addEventListener("pointerdown",t=>{"touch"===t.pointerType&&(Wt(t),s(t))},n),i.addEventListener("pointerup",s,n),void i.addEventListener("pointercancel",s,n)}if(!this.#Se){this.#Se=new AbortController;const t=AbortSignal.any([this.#xe,this.#Se.signal]),e=this.#xt,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Ee.bind(this),i);const n=this.#Te.bind(this);e.addEventListener("touchend",n,i),e.addEventListener("touchcancel",n,i),i.capture=!0,e.addEventListener("pointerdown",Wt,i),e.addEventListener("pointermove",Wt,i),e.addEventListener("pointercancel",Wt,i),e.addEventListener("pointerup",Wt,i),this.#be?.()}if(Wt(t),2!==t.touches.length||this.#me?.())return void(this.#Ae=null);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]),this.#Ae={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#Ee(t){if(!this.#Ae||2!==t.touches.length)return;Wt(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:n,screenY:s}=e,{screenX:r,screenY:a}=i,o=this.#Ae,{touch0X:l,touch0Y:h,touch1X:c,touch1Y:d}=o,u=c-l,p=d-h,g=r-n,m=a-s,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#ge&&Math.abs(b-f)<=fe.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(o.touch0X=n,o.touch0Y=s,o.touch1X=r,o.touch1Y=a,!this.#ge)return void(this.#ge=!0);const v=[(n+r)/2,(s+a)/2];this.#ve?.(v,b,f)}#Te(t){t.touches.length>=2||(this.#Se&&(this.#Se.abort(),this.#Se=null,this.#ye?.()),this.#Ae&&(Wt(t),this.#Ae=null,this.#ge=!1))}destroy(){this.#_e?.abort(),this.#_e=null,this.#we?.abort(),this.#we=null}}class be{#ke=null;#De=null;#o=null;#l=null;#re=null;#Me=!1;#Pe=null;#Ie="";#Re=null;#Le=null;#Be=null;#Fe=null;#Oe=null;#Ne="";#Ue=!1;#je=null;#ze=!1;#He=!1;#$e=!1;#We=null;#Ve=0;#Ge=0;#qe=null;#Xe=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#Ke=!1;#Ye=be._zIndex++;static _borderLineWidth=-1;static _colorManager=new ue;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=be.prototype._resizeWithKeyboard,e=pe.TRANSLATE_SMALL,i=pe.TRANSLATE_BIG;return pt(this,"_resizerKeyboardManager",new de([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],be.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null,this.annotationElementId=t.annotationElementId||null,this.creationDate=t.creationDate||new Date,this.modificationDate=t.modificationDate||null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,n],this.pageTranslation=[s,r];const[a,o]=this.parentDimensions;this.x=t.x/a,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return pt(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new ve({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(be._l10n??=t,be._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),-1!==be._borderLineWidth)return;const i=getComputedStyle(document.documentElement);be._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){ht("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#Ke}set _isDraggable(t){this.#Ke=t,this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#Ye}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):(this.#Je(),this.#Fe?.remove(),this.#Fe=null),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ue?this.#Ue=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;e?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,n){const[s,r]=this.parentDimensions;[i,n]=this.screenToPageTranslation(i,n),this.x=(t+i)/s,this.y=(e+n)/r,this.fixAndSetPosition()}_moveAfterPaste(t,e){const[i,n]=this.parentDimensions;this.setAt(t*i,e*n,this.width*i,this.height*n),this._onTranslated()}#Qe([t,e],i,n){[i,n]=this.screenToPageTranslation(i,n),this.x+=i/t,this.y+=n/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#Qe(this.parentDimensions,t,e)}translateInPage(t,e){this.#je||=[this.x,this.y,this.width,this.height],this.#Qe(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#je||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[n,s]}=this;if(this.x+=t/n,this.y+=e/s,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:a}=this;const[o,l]=this.getBaseTranslation();r+=o,a+=l;const{style:h}=i;h.left=`${(100*r).toFixed(2)}%`,h.top=`${(100*a).toFixed(2)}%`,this._onTranslating(r,a),i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#je&&(this.#je[0]!==this.x||this.#je[1]!==this.y)}get _hasBeenResized(){return!!this.#je&&(this.#je[2]!==this.width||this.#je[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=be,n=i/t,s=i/e;switch(this.rotation){case 90:return[-n,s];case 180:return[n,s];case 270:return[n,-s];default:return[-n,-s]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,n]}=this;let{x:s,y:r,width:a,height:o}=this;if(a*=i,o*=n,s*=i,r*=n,this._mustFixPosition)switch(t){case 0:s=Mt(s,0,i-a),r=Mt(r,0,n-o);break;case 90:s=Mt(s,0,i-o),r=Mt(r,a,n);break;case 180:s=Mt(s,a,i),r=Mt(r,o,n);break;case 270:s=Mt(s,o,i),r=Mt(r,0,n-a)}this.x=s/=i,this.y=r/=n;const[l,h]=this.getBaseTranslation();s+=l,r+=h,e.left=`${(100*s).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#Ze(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return be.#Ze(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return be.#Ze(t,e,360-this.parentRotation)}#ti(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(){const{div:{style:t},width:e,height:i}=this;t.width=`${(100*e).toFixed(2)}%`,t.height=`${(100*i).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#ei(){if(this.#Re)return;this.#Re=document.createElement("div"),this.#Re.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#Re.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#ii.bind(this,i),{signal:e}),t.addEventListener("contextmenu",$t,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#Re)}#ii(t,e){e.preventDefault();const{isMac:i}=_t.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const n=this._isDraggable;this._isDraggable=!1,this.#Le=[e.screenX,e.screenY];const s=new AbortController,r=this._uiManager.combinedSignal(s);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#ni.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",Wt,{passive:!1,signal:r}),window.addEventListener("contextmenu",$t,{signal:r}),this.#Be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{s.abort(),this.parent.togglePointerEvents(!0),this.#o?.toggle(!0),this._isDraggable=n,this.parent.div.style.cursor=a,this.div.style.cursor=o,this.#si()};window.addEventListener("pointerup",l,{signal:r}),window.addEventListener("blur",l,{signal:r})}#ri(t,e,i,n){this.width=i,this.height=n,this.x=t,this.y=e,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#si(){if(!this.#Be)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:n}=this.#Be;this.#Be=null;const s=this.x,r=this.y,a=this.width,o=this.height;s===t&&r===e&&a===i&&o===n||this.addCommands({cmd:this.#ri.bind(this,s,r,a,o),undo:this.#ri.bind(this,t,e,i,n),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#ni(t,e){const[i,n]=this.parentDimensions,s=this.x,r=this.y,a=this.width,o=this.height,l=be.MIN_SIZE/i,h=be.MIN_SIZE/n,c=this.#ti(this.rotation),d=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],u=this.#ti(360-this.rotation);let p,g,m=!1,f=!1;switch(t){case"topLeft":m=!0,p=(t,e)=>[0,0],g=(t,e)=>[t,e];break;case"topMiddle":p=(t,e)=>[t/2,0],g=(t,e)=>[t/2,e];break;case"topRight":m=!0,p=(t,e)=>[t,0],g=(t,e)=>[0,e];break;case"middleRight":f=!0,p=(t,e)=>[t,e/2],g=(t,e)=>[0,e/2];break;case"bottomRight":m=!0,p=(t,e)=>[t,e],g=(t,e)=>[0,0];break;case"bottomMiddle":p=(t,e)=>[t/2,e],g=(t,e)=>[t/2,0];break;case"bottomLeft":m=!0,p=(t,e)=>[0,e],g=(t,e)=>[t,0];break;case"middleLeft":f=!0,p=(t,e)=>[0,e/2],g=(t,e)=>[t,e/2]}const b=p(a,o),v=g(a,o);let y=d(...v);const w=be._round(s+y[0]),x=be._round(r+y[1]);let A,_,S=1,C=1;if(e.fromKeyboard)({deltaX:A,deltaY:_}=e);else{const{screenX:t,screenY:i}=e,[n,s]=this.#Le;[A,_]=this.screenToPageTranslation(t-n,i-s),this.#Le[0]=t,this.#Le[1]=i}var E,T;if([A,_]=(E=A/i,T=_/n,[u[0]*E+u[2]*T,u[1]*E+u[3]*T]),m){const t=Math.hypot(a,o);S=C=Math.max(Math.min(Math.hypot(v[0]-b[0]-A,v[1]-b[1]-_)/t,1/a,1/o),l/a,h/o)}else f?S=Mt(Math.abs(v[0]-b[0]-A),l,1)/a:C=Mt(Math.abs(v[1]-b[1]-_),h,1)/o;const k=be._round(a*S),D=be._round(o*C);y=d(...g(k,D));const M=w-y[0],P=x-y[1];this.#je||=[this.x,this.y,this.width,this.height],this.width=k,this.height=D,this.x=M,this.y=P,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#He)return this._editToolbar;this._editToolbar=new re(this),this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,i]of t)await this._editToolbar.addButton(e,i);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#o?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#o||(ge.initialize(be._l10n),this.#o=new ge(this),this.#ke&&(this.#o.data=this.#ke,this.#ke=null)),this.#o}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}focusCommentButton(){this.#l?.focusButton()}addCommentButton(){return this.#l||=new me(this)}addStandaloneCommentButton(){this.#re?this._uiManager.isEditingMode()&&this.#re.classList.remove("hidden"):this.hasComment&&(this.#re=this.#l.renderForStandalone(),this.div.append(this.#re))}removeStandaloneCommentButton(){this.#l.removeStandaloneCommentButton(),this.#re=null}hideStandaloneCommentButton(){this.#re?.classList.add("hidden")}get comment(){const{data:{richText:t,text:e,date:i,deleted:n}}=this.#l;return{text:e,richText:t,date:i,deleted:n,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#l||=new me(this),this.#l.data=t,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:t,popupRef:e,richText:i}){if(!e)return;if(this.#l||=new me(this),this.#l.setInitialText(t,i),!this.annotationElementId)return;const n=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);n&&this.updateFromAnnotationLayer(n)}get hasEditedComment(){return this.#l?.hasBeenEdited()}get hasDeletedComment(){return this.#l?.isDeleted()}get hasComment(){return!!this.#l&&!this.#l.isEmpty()&&!this.#l.isDeleted()}async editComment(t){this.#l||=new me(this),this.#l.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#l.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,i=100,[,,,n]=t.rect,[s]=this.pageDimensions,[r]=this.pageTranslation,a=r+s+1,o=n-i,l=a+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,o,l,n]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#l.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#Me?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#ai();const[e,i]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*i/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/i).toFixed(2)}%`);const[n,s]=this.getInitialTranslation();return this.translate(n,s),oe(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Xe||=new fe({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#oi.bind(this),onPinching:this.#li.bind(this),onPinchEnd:this.#hi.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),t}#oi(){this.#Be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#o?.toggle(!1),this.parent.togglePointerEvents(!1)}#li(t,e,i){let n=i/e*.7+1-.7;if(1===n)return;const s=this.#ti(this.rotation),r=(t,e)=>[s[0]*t+s[2]*e,s[1]*t+s[3]*e],[a,o]=this.parentDimensions,l=this.x,h=this.y,c=this.width,d=this.height,u=be.MIN_SIZE/a,p=be.MIN_SIZE/o;n=Math.max(Math.min(n,1/c,1/d),u/c,p/d);const g=be._round(c*n),m=be._round(d*n);if(g===c&&m===d)return;this.#je||=[l,h,c,d];const f=r(c/2,d/2),b=be._round(l+f[0]),v=be._round(h+f[1]),y=r(g/2,m/2);this.x=b-y[0],this.y=v-y[1],this.width=g,this.height=m,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#hi(){this.#o?.toggle(!0),this.parent.togglePointerEvents(!0),this.#si()}pointerdown(t){const{isMac:e}=_t.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#Ue=!0,this._isDraggable?this.#ci(t):this.#di(t))}#di(t){const{isMac:e}=_t.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#ci(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const n=new AbortController,s=this._uiManager.combinedSignal(n),r={capture:!0,passive:!1,signal:s},a=t=>{n.abort(),this.#Pe=null,this.#Ue=!1,this._uiManager.endDragSession()||this.#di(t),i&&this._onStopDragging()};e&&(this.#Ve=t.clientX,this.#Ge=t.clientY,this.#Pe=t.pointerId,this.#Ie=t.pointerType,window.addEventListener("pointermove",t=>{i||(i=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:e,clientY:n,pointerId:s}=t;if(s!==this.#Pe)return void Wt(t);const[r,a]=this.screenToPageTranslation(e-this.#Ve,n-this.#Ge);this.#Ve=e,this.#Ge=n,this._uiManager.dragSelectedEditors(r,a)},r),window.addEventListener("touchmove",Wt,r),window.addEventListener("pointerdown",t=>{t.pointerType===this.#Ie&&(this.#Xe||t.isPrimary)&&a(t),Wt(t)},r));const o=t=>{this.#Pe&&this.#Pe!==t.pointerId?Wt(t):a(t)};window.addEventListener("pointerup",o,{signal:s}),window.addEventListener("blur",o,{signal:s})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#We&&clearTimeout(this.#We),this.#We=setTimeout(()=>{this.#We=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,i=this.rotation){const n=this.parentScale,[s,r]=this.pageDimensions,[a,o]=this.pageTranslation,l=t/n,h=e/n,c=this.x*s,d=this.y*r,u=this.width*s,p=this.height*r;switch(i){case 0:return[c+l+a,r-d-h-p+o,c+l+u+a,r-d-h+o];case 90:return[c+h+a,r-d+l+o,c+h+p+a,r-d+l+u+o];case 180:return[c-l-u+a,r-d+h+o,c-l+a,r-d+h+p+o];case 270:return[c-h-p+a,r-d-l-u+o,c-h+a,r-d-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,n,s,r]=t,a=s-i,o=r-n;switch(this.rotation){case 0:return[i,e-r,a,o];case 90:return[i,e-n,o,a];case 180:return[s,e-n,a,o];case 270:return[s,e-r,o,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&be._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#l?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:i,opacity:n,deleted:s,richText:r},uid:a,pageIndex:o,creationDate:l,modificationDate:h}=this;return{id:a,pageIndex:o,rect:this.getPDFRect(),richText:r,contentsObj:{str:t},creationDate:l,modificationDate:i||h,popupRef:!s,color:e,opacity:n}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#He=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#He=!1,!0)}isInEditMode(){return this.#He}shouldGetKeyboardEvents(){return this.#$e}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:n}=this.getClientDimensions(),{innerHeight:s,innerWidth:r}=window;return e<r&&n>0&&t<s&&i>0}#ai(){if(this.#Oe||!this.div)return;this.#Oe=new AbortController;const t=this._uiManager.combinedSignal(this.#Oe);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#ai()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,i){const n=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});n.rotation=t.rotation,n.#ke=t.accessibilityData,n._isCopy=t.isCopy||!1;const[s,r]=n.pageDimensions,[a,o,l,h]=n.getRectInCurrentCoords(t.rect,r);return n.x=a/s,n.y=o/r,n.width=l/s,n.height=h/r,n}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#Oe?.abort(),this.#Oe=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#We&&(clearTimeout(this.#We),this.#We=null),this.#Je(),this.removeEditToolbar(),this.#qe){for(const t of this.#qe.values())clearTimeout(t);this.#qe=null}this.parent=null,this.#Xe?.destroy(),this.#Xe=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#ei(),this.#Re.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[i,n,s,r]=this.getPDFRect();return[be._round(i+(s-i)*t),be._round(n+(r-n)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#l.commentPopupPositionInLayer}set commentPopupPosition(t){this.#l.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#l.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#l.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#l.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Re.children;if(!this.#De){this.#De=Array.from(e);const t=this.#ui.bind(this),i=this.#pi.bind(this),n=this._uiManager._signal;for(const e of this.#De){const s=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:n}),e.addEventListener("blur",i,{signal:n}),e.addEventListener("focus",this.#gi.bind(this,s),{signal:n}),e.setAttribute("data-l10n-id",be._l10nResizer[s])}}const i=this.#De[0];let n=0;for(const t of e){if(t===i)break;n++}const s=(360-this.rotation+this.parentRotation)%360/90*(this.#De.length/4);if(s!==n){if(s<n)for(let t=0;t<n-s;t++)this.#Re.append(this.#Re.firstChild);else if(s>n)for(let t=0;t<s-n;t++)this.#Re.firstChild.before(this.#Re.lastChild);let t=0;for(const i of e){const e=this.#De[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",be._l10nResizer[e])}}this.#mi(0),this.#$e=!0,this.#Re.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#ui(t){be._resizerKeyboardManager.exec(this,t)}#pi(t){this.#$e&&t.relatedTarget?.parentNode!==this.#Re&&this.#Je()}#gi(t){this.#Ne=this.#$e?t:""}#mi(t){if(this.#De)for(const e of this.#De)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#$e&&this.#ni(this.#Ne,{deltaX:t,deltaY:e,fromKeyboard:!0})}#Je(){this.#$e=!1,this.#mi(-1),this.#si()}_stopResizingWithKeyboard(){this.#Je(),this.div.focus()}select(){this.isSelected&&this._editToolbar?this._editToolbar.show():(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),this._editToolbar?(this._editToolbar?.show(),this.#o?.toggleAltTextBadge(!1)):this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#Re?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#o?.toggleAltTextBadge(!0),this.hasComment&&this._uiManager.toggleComment(this,!1,!1))}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){"BUTTON"!==t.target.nodeName&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.id}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#ze}set isEditing(t){this.#ze=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#qe||=new Map;const{action:e}=t;let i=this.#qe.get(e);return i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#qe.delete(e),0===this.#qe.size&&(this.#qe=null)},be._telemetryTimeout),void this.#qe.set(e,i)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#Me=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Me=!0}updateFakeAnnotationElement(t){if(this.#Fe||this.deleted)return this.deleted?(this.#Fe.remove(),void(this.#Fe=null)):void((this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#Fe.updateEdited({rect:this.getPDFRect(),popup:this.comment}));this.#Fe=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class ve extends be{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const ye=3285377520,we=4294901760,xe=65535;class Ae{constructor(t){this.h1=t?4294967295&t:ye,this.h2=t?4294967295&t:ye}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let n=0,s=t.length;n<s;n++){const s=t.charCodeAt(n);s<=255?e[i++]=s:(e[i++]=s>>>8,e[i++]=255&s)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const n=i>>2,s=i-4*n,r=new Uint32Array(e.buffer,0,n);let a=0,o=0,l=this.h1,h=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let t=0;t<n;t++)1&t?(a=r[t],a=a*c&we|a*u&xe,a=a<<15|a>>>17,a=a*d&we|a*p&xe,l^=a,l=l<<13|l>>>19,l=5*l+3864292196):(o=r[t],o=o*c&we|o*u&xe,o=o<<15|o>>>17,o=o*d&we|o*p&xe,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(a=0,s){case 3:a^=e[4*n+2]<<16;case 2:a^=e[4*n+1]<<8;case 1:a^=e[4*n],a=a*c&we|a*u&xe,a=a<<15|a>>>17,a=a*d&we|a*p&xe,1&n?l^=a:h^=a}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&we|36045*t&xe,e=4283543511*e&we|(2950163797*(e<<16|t>>>16)&we)>>>16,t^=e>>>1,t=444984403*t&we|60499*t&xe,e=3301882366*e&we|(3120437893*(e<<16|t>>>16)&we)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const _e=Object.freeze({map:null,hash:"",transfer:void 0});class Se{#fi=!1;#bi=null;#vi=null;#yi=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const i=this.#yi.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#yi.get(t)}remove(t){const e=this.#yi.get(t);if(void 0!==e&&(e instanceof be&&this.#vi.delete(e.annotationElementId),this.#yi.delete(t),0===this.#yi.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor)){for(const t of this.#yi.values())if(t instanceof be)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#yi.get(t);let n=!1;if(void 0!==i)for(const[t,s]of Object.entries(e))i[t]!==s&&(n=!0,i[t]=s);else n=!0,this.#yi.set(t,e);n&&this.#wi(),e instanceof be&&((this.#vi||=new Map).set(e.annotationElementId,e),"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type))}has(t){return this.#yi.has(t)}get size(){return this.#yi.size}#wi(){this.#fi||(this.#fi=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#fi&&(this.#fi=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new Ce(this)}get serializable(){if(0===this.#yi.size)return _e;const t=new Map,e=new Ae,i=[],n=Object.create(null);let s=!1;for(const[i,r]of this.#yi){const a=r instanceof be?r.serialize(!1,n):r;a&&(t.set(i,a),e.update(`${i}:${JSON.stringify(a)}`),s||=!!a.bitmap)}if(s)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:_e}get editorStats(){let t=null;const e=new Map;let i=0,n=0;for(const s of this.#yi.values()){if(!(s instanceof be)){s.popup&&(s.popup.deleted?n+=1:i+=1);continue}s.isCommentDeleted?n+=1:s.hasEditedComment&&(i+=1);const r=s.telemetryFinalData;if(!r)continue;const{type:a}=r;e.has(a)||e.set(a,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const o=t[a]||=new Map;for(const[t,e]of Object.entries(r)){if("type"===t)continue;let i=o.get(t);i||(i=new Map,o.set(t,i));const n=i.get(e)??0;i.set(e,n+1)}}if((n>0||i>0)&&(t||=Object.create(null),t.comments={deleted:n,edited:i}),!t)return null;for(const[i,n]of e)t[i]=n.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#bi=null}updateEditor(t,e){const i=this.#vi?.get(t);return!!i&&(i.updateFromAnnotationLayer(e),!0)}getEditor(t){return this.#vi?.get(t)||null}get modifiedIds(){if(this.#bi)return this.#bi;const t=[];if(this.#vi)for(const e of this.#vi.values())e.serialize()&&t.push(e.annotationElementId);return this.#bi={ids:new Set(t),hash:t.join(",")}}[Symbol.iterator](){return this.#yi.entries()}}class Ce extends Se{#xi;constructor(t){super();const{map:e,hash:i,transfer:n}=t.serializable,s=structuredClone(e,n?{transfer:n}:null);this.#xi={map:s,hash:i,transfer:n}}get print(){ht("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#xi}get modifiedIds(){return pt(this,"modifiedIds",{ids:new Set,hash:""})}}class Ee{#Ai=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#Ai.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#Ai.has(t.loadedName)){if(ct(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:e,src:n,style:s}=t,r=new FontFace(e,n,s);this.addNativeFontFace(r);try{await r.load(),this.#Ai.add(e),i?.(t)}catch{lt(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}ht("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){throw lt(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return pt(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return pt(this,"isSyncFontLoadingSupported",_||_t.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(ct(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return pt(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function n(t,e,i,n){return t.substring(0,e)+n+t.substring(e+i)}let s,r;const a=this._document.createElement("canvas");a.width=1,a.height=1;const o=a.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=n(c,976,h.length,h);const d=1482184792;let u=i(c,16);for(s=0,r=h.length-3;s<r;s+=4)u=u-d+i(h,s)|0;var p;s<h.length&&(u=u-d+i(h+"XXX",s)|0),c=n(c,16,4,(p=u,String.fromCharCode(p>>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${h}";src:${`url(data:font/opentype;base64,${btoa(c)});`}}`;this.insertRule(g);const m=this._document.createElement("div");m.style.visibility="hidden",m.style.width=m.style.height="10px",m.style.position="absolute",m.style.top=m.style.left="0px";for(const e of[t.loadedName,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,i){if(++l>30)return lt("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,()=>{m.remove(),e.complete()})}}class Te{#_i;constructor(t,e=null,i,n){this.compiledGlyphs=Object.create(null),this.#_i=t,this._inspectFont=e,i&&Object.assign(this,i),n&&(this.charProcOperatorList=n)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Pt(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let n;try{n=t.get(i)}catch(t){lt(`getPathGenerator - ignoring character: "${t}".`)}const s=new Path2D(n||"");return this.fontExtraProperties||t.delete(i),this.compiledGlyphs[e]=s}get black(){return this.#_i.black}get bold(){return this.#_i.bold}get disableFontFace(){return this.#_i.disableFontFace??!1}get fontExtraProperties(){return this.#_i.fontExtraProperties??!1}get isInvalidPDFjsFont(){return this.#_i.isInvalidPDFjsFont}get isType3Font(){return this.#_i.isType3Font}get italic(){return this.#_i.italic}get missingFile(){return this.#_i.missingFile}get remeasure(){return this.#_i.remeasure}get vertical(){return this.#_i.vertical}get ascent(){return this.#_i.ascent}get defaultWidth(){return this.#_i.defaultWidth}get descent(){return this.#_i.descent}get bbox(){return this.#_i.bbox}get fontMatrix(){return this.#_i.fontMatrix}get fallbackName(){return this.#_i.fallbackName}get loadedName(){return this.#_i.loadedName}get mimetype(){return this.#_i.mimetype}get name(){return this.#_i.name}get data(){return this.#_i.data}clearData(){this.#_i.clearData()}get cssFontInfo(){return this.#_i.cssFontInfo}get systemFontInfo(){return this.#_i.systemFontInfo}get defaultVMetrics(){return this.#_i.defaultVMetrics}}function ke(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const De=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,Me=function(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[n,s,...r]=i;if(!t(n)&&!Number.isInteger(n))return!1;if(!e(s))return!1;const a=r.length;let o=!0;switch(s.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return 0===a;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(4!==a)return!1;o=!1;break;default:return!1}for(const t of r)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,De,t=>"object"==typeof t&&"string"==typeof t?.name);class Pe{#Si=new Map;#Ci=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#Ci.then(()=>{for(const[t]of this.#Si)t.call(this,i)})}addEventListener(t,e,i=null){let n=null;if(i?.signal instanceof AbortSignal){const{signal:s}=i;if(s.aborted)return void lt("LoopbackPort - cannot use an `aborted` signal.");const r=()=>this.removeEventListener(t,e);n=()=>s.removeEventListener("abort",r),s.addEventListener("abort",r)}this.#Si.set(e,n)}removeEventListener(t,e){const i=this.#Si.get(e);i?.(),this.#Si.delete(e)}terminate(){for(const[,t]of this.#Si)t?.();this.#Si.clear()}}const Ie=1,Re=2,Le=1,Be=2,Fe=3,Oe=4,Ne=5,Ue=6,je=7,ze=8;function He(){}function $e(t){if(t instanceof wt||t instanceof bt||t instanceof mt||t instanceof vt||t instanceof ft)return t;switch(t instanceof Error||"object"==typeof t&&null!==t||ht('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new wt(t.message);case"InvalidPDFException":return new bt(t.message);case"PasswordException":return new mt(t.message,t.code);case"ResponseException":return new vt(t.message,t.status,t.missing);case"UnknownErrorException":return new ft(t.message,t.details)}return new ft(t.message,t.toString())}class We{#Ei=new AbortController;constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),i.addEventListener("message",this.#Ti.bind(this),{signal:this.#Ei.signal})}#Ti({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#ki(t);if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===Ie)i.resolve(t.data);else{if(t.callback!==Re)throw new Error("Unexpected callback case");i.reject($e(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,n=t.sourceName,s=this.comObj;return void Promise.try(e,t.data).then(function(e){s.postMessage({sourceName:i,targetName:n,callback:Ie,callbackId:t.callbackId,data:e})},function(e){s.postMessage({sourceName:i,targetName:n,callback:Re,callbackId:t.callbackId,reason:$e(e)})})}t.streamId?this.#Di(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const n=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[n]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:n,data:e},i)}catch(t){s.reject(t)}return s.promise}sendWithStream(t,e,i,n){const s=this.streamId++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[s]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:r,targetName:a,action:t,streamId:s,data:e,desiredSize:i.desiredSize},n),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[s].pullCall=e,o.postMessage({sourceName:r,targetName:a,stream:Ue,streamId:s,desiredSize:t.desiredSize}),e.promise},cancel:t=>{ct(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[s].cancelCall=e,this.streamControllers[s].isClosed=!0,o.postMessage({sourceName:r,targetName:a,stream:Le,streamId:s,reason:$e(t)}),e.promise}},i)}#Di(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,r=this,a=this.actionHandler[t.action],o={enqueue(t,r=1,a){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=r,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),s.postMessage({sourceName:i,targetName:n,stream:Oe,streamId:e,chunk:t},a)},close(){this.isCancelled||(this.isCancelled=!0,s.postMessage({sourceName:i,targetName:n,stream:Fe,streamId:e}),delete r.streamSinks[e])},error(t){ct(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,s.postMessage({sourceName:i,targetName:n,stream:Ne,streamId:e,reason:$e(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,Promise.try(a,t.data,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:ze,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:ze,streamId:e,reason:$e(t)})})}#ki(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case ze:t.success?r.startCall.resolve():r.startCall.reject($e(t.reason));break;case je:t.success?r.pullCall.resolve():r.pullCall.reject($e(t.reason));break;case Ue:if(!a){s.postMessage({sourceName:i,targetName:n,stream:je,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=t.desiredSize,Promise.try(a.onPull||He).then(function(){s.postMessage({sourceName:i,targetName:n,stream:je,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:je,streamId:e,reason:$e(t)})});break;case Oe:if(ct(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Fe:if(ct(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#Mi(r,e);break;case Ne:ct(r,"error should have stream controller"),r.controller.error($e(t.reason)),this.#Mi(r,e);break;case Be:t.success?r.cancelCall.resolve():r.cancelCall.reject($e(t.reason)),this.#Mi(r,e);break;case Le:if(!a)break;const o=$e(t.reason);Promise.try(a.onCancel||He,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:Be,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:Be,streamId:e,reason:$e(t)})}),a.sinkCapability.reject(o),a.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#Mi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#Ei?.abort(),this.#Ei=null}}class Ve{#Pi=!1;constructor({enableHWA:t=!1}){this.#Pi=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#Pi})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){ht("Abstract method `_createCanvas` called.")}}class Ge extends Ve{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}}class qe{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(t=>({cMapData:t,isCompressed:this.isCompressed})).catch(t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){ht("Abstract method `_fetch` called.")}}class Xe extends qe{async _fetch(t){const e=await Ft(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):At(e)}}class Ke{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,n,s){return"none"}destroy(t=!1){}}class Ye extends Ke{#Ii;#Ri;#Li;#Bi;#Fi;#Oi;#x=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#Bi=t,this.#Fi=e}get#_(){return this.#Ri||=new Map}get#Ni(){return this.#Oi||=new Map}get#Ui(){if(!this.#Li){const t=this.#Fi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#Fi.createElementNS(Lt,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#Li=this.#Fi.createElementNS(Lt,"defs"),t.append(i),i.append(this.#Li),this.#Fi.body.append(t)}return this.#Li}#ji(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const n=i.join(",");return[n,n,n]}const[e,i,n]=t,s=new Array(256),r=new Array(256),a=new Array(256);for(let t=0;t<256;t++)s[t]=e[t]/255,r[t]=i[t]/255,a[t]=n[t]/255;return[s.join(","),r.join(","),a.join(",")]}#zi(t){if(void 0===this.#Ii){this.#Ii="";const t=this.#Fi.URL;t!==this.#Fi.baseURI&&(Ut(t)?lt('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ii=ut(t,""))}return`url(${this.#Ii}#${t})`}addFilter(t){if(!t)return"none";let e=this.#_.get(t);if(e)return e;const[i,n,s]=this.#ji(t),r=1===t.length?i:`${i}${n}${s}`;if(e=this.#_.get(r),e)return this.#_.set(t,e),e;const a=`g_${this.#Bi}_transfer_map_${this.#x++}`,o=this.#zi(a);this.#_.set(t,o),this.#_.set(r,o);const l=this.#Hi(a);return this.#$i(i,n,s,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,n="base";let s=this.#Ni.get(n);if(s?.key===i)return s.url;if(s?(s.filter?.remove(),s.key=i,s.url="none",s.filter=null):(s={key:i,url:"none",filter:null},this.#Ni.set(n,s)),!t||!e)return s.url;const r=this.#Wi(t);t=Ct.makeHexColor(...r);const a=this.#Wi(e);if(e=Ct.makeHexColor(...a),this.#Ui.style.color="","#000000"===t&&"#ffffff"===e||t===e)return s.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#Bi}_hcm_filter`,c=s.filter=this.#Hi(h);this.#$i(l,l,l,c),this.#Vi(c);const d=(t,e)=>{const i=r[t]/255,n=a[t]/255,s=new Array(e+1);for(let t=0;t<=e;t++)s[t]=i+t/e*(n-i);return s.join(",")};return this.#$i(d(0,5),d(1,5),d(2,5),c),s.url=this.#zi(h),s.url}addAlphaFilter(t){let e=this.#_.get(t);if(e)return e;const[i]=this.#ji([t]),n=`alpha_${i}`;if(e=this.#_.get(n),e)return this.#_.set(t,e),e;const s=`g_${this.#Bi}_alpha_map_${this.#x++}`,r=this.#zi(s);this.#_.set(t,r),this.#_.set(n,r);const a=this.#Hi(s);return this.#Gi(i,a),r}addLuminosityFilter(t){let e,i,n=this.#_.get(t||"luminosity");if(n)return n;if(t?([e]=this.#ji([t]),i=`luminosity_${e}`):i="luminosity",n=this.#_.get(i),n)return this.#_.set(t,n),n;const s=`g_${this.#Bi}_luminosity_map_${this.#x++}`,r=this.#zi(s);this.#_.set(t,r),this.#_.set(i,r);const a=this.#Hi(s);return this.#qi(a),t&&this.#Gi(e,a),r}addHighlightHCMFilter(t,e,i,n,s){const r=`${e}-${i}-${n}-${s}`;let a=this.#Ni.get(t);if(a?.key===r)return a.url;if(a?(a.filter?.remove(),a.key=r,a.url="none",a.filter=null):(a={key:r,url:"none",filter:null},this.#Ni.set(t,a)),!e||!i)return a.url;const[o,l]=[e,i].map(this.#Wi.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,u]=[n,s].map(this.#Wi.bind(this));c<h&&([h,c,d,u]=[c,h,u,d]),this.#Ui.style.color="";const p=(t,e,i)=>{const n=new Array(256),s=(c-h)/i,r=t/255,a=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*s),i=r+t*a;for(let t=o;t<=e;t++)n[t]=i;o=e+1}for(let t=o;t<256;t++)n[t]=n[o-1];return n.join(",")},g=`g_${this.#Bi}_hcm_${t}_filter`,m=a.filter=this.#Hi(g);return this.#Vi(m),this.#$i(p(d[0],u[0],5),p(d[1],u[1],5),p(d[2],u[2],5),m),a.url=this.#zi(g),a.url}destroy(t=!1){t&&this.#Oi?.size||(this.#Li?.parentNode.parentNode.remove(),this.#Li=null,this.#Ri?.clear(),this.#Ri=null,this.#Oi?.clear(),this.#Oi=null,this.#x=0)}#qi(t){const e=this.#Fi.createElementNS(Lt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#Vi(t){const e=this.#Fi.createElementNS(Lt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#Hi(t){const e=this.#Fi.createElementNS(Lt,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#Ui.append(e),e}#Xi(t,e,i){const n=this.#Fi.createElementNS(Lt,e);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),t.append(n)}#$i(t,e,i,n){const s=this.#Fi.createElementNS(Lt,"feComponentTransfer");n.append(s),this.#Xi(s,"feFuncR",t),this.#Xi(s,"feFuncG",e),this.#Xi(s,"feFuncB",i)}#Gi(t,e){const i=this.#Fi.createElementNS(Lt,"feComponentTransfer");e.append(i),this.#Xi(i,"feFuncA",t)}#Wi(t){return this.#Ui.style.color=t,Gt(getComputedStyle(this.#Ui).getPropertyValue("color"))}}class Je{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){ht("Abstract method `_fetch` called.")}}class Qe extends Je{async _fetch(t){const e=await Ft(t,"arraybuffer");return new Uint8Array(e)}}class Ze{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!t)throw new Error("Wasm filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load wasm data at: ${e}`)})}async _fetch(t){ht("Abstract method `_fetch` called.")}}class ti extends Ze{async _fetch(t){const e=await Ft(t,"arraybuffer");return new Uint8Array(e)}}async function ei(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}_&<("Please use the `legacy` build in Node.js environments.");class ii extends Ke{}class ni extends Ve{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire("file:///home/ubuntu/projects/dash-pdf-components/node_modules/.pnpm/pdfjs-dist@5.4.296/node_modules/pdfjs-dist/build/pdf.mjs")("@napi-rs/canvas").createCanvas(t,e)}}class si extends qe{async _fetch(t){return ei(t)}}class ri extends Je{async _fetch(t){return ei(t)}}class ai extends Ze{async _fetch(t){return ei(t)}}const oi="__forcedDependency",{floor:li,ceil:hi}=Math;function ci(t,e,i,n,s,r){t[4*e+0]=Math.min(t[4*e+0],i),t[4*e+1]=Math.min(t[4*e+1],n),t[4*e+2]=Math.max(t[4*e+2],s),t[4*e+3]=Math.max(t[4*e+3],r)}const di=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class ui{#Ki;#Yi;constructor(t,e){this.#Ki=t,this.#Yi=e}get length(){return this.#Ki.length}isEmpty(t){return this.#Ki[t]===di}minX(t){return this.#Yi[4*t+0]/256}minY(t){return this.#Yi[4*t+1]/256}maxX(t){return(this.#Yi[4*t+2]+1)/256}maxY(t){return(this.#Yi[4*t+3]+1)/256}}const pi=(t,e)=>{if(!t)return;let i=t.get(e);return i||(i={dependencies:new Set,isRenderingOperation:!1},t.set(e,i)),i};class gi{#Ji={__proto__:null};#Qi={__proto__:null,transform:[],moveText:[],sameLineText:[],[oi]:[]};#Zi=new Map;#tn=[];#en=[];#in=[[1,0,0,1,0,0]];#nn=[-1/0,-1/0,1/0,1/0];#sn=new Float64Array([1/0,1/0,-1/0,-1/0]);#rn=-1;#an=new Set;#on=new Map;#ln=new Map;#hn;#cn;#dn;#Ki;#un;constructor(t,e,i=!1){this.#hn=t.width,this.#cn=t.height,this.#pn(e),i&&(this.#un=new Map)}growOperationsCount(t){t>=this.#Ki.length&&this.#pn(t,this.#Ki)}#pn(t,e){const i=new ArrayBuffer(4*t);this.#dn=new Uint8ClampedArray(i),this.#Ki=new Uint32Array(i),e&&e.length>0?(this.#Ki.set(e),this.#Ki.fill(di,e.length)):this.#Ki.fill(di)}save(t){return this.#Ji={__proto__:this.#Ji},this.#Qi={__proto__:this.#Qi,transform:{__proto__:this.#Qi.transform},moveText:{__proto__:this.#Qi.moveText},sameLineText:{__proto__:this.#Qi.sameLineText},[oi]:{__proto__:this.#Qi[oi]}},this.#nn={__proto__:this.#nn},this.#tn.push(t),this}restore(t){const e=Object.getPrototypeOf(this.#Ji);if(null===e)return this;this.#Ji=e,this.#Qi=Object.getPrototypeOf(this.#Qi),this.#nn=Object.getPrototypeOf(this.#nn);const i=this.#tn.pop();return void 0!==i&&(pi(this.#un,t)?.dependencies.add(i),this.#Ki[t]=this.#Ki[i]),this}recordOpenMarker(t){return this.#tn.push(t),this}getOpenMarker(){return 0===this.#tn.length?null:this.#tn.at(-1)}recordCloseMarker(t){const e=this.#tn.pop();return void 0!==e&&(pi(this.#un,t)?.dependencies.add(e),this.#Ki[t]=this.#Ki[e]),this}beginMarkedContent(t){return this.#en.push(t),this}endMarkedContent(t){const e=this.#en.pop();return void 0!==e&&(pi(this.#un,t)?.dependencies.add(e),this.#Ki[t]=this.#Ki[e]),this}pushBaseTransform(t){return this.#in.push(Ct.multiplyByDOMMatrix(this.#in.at(-1),t.getTransform())),this}popBaseTransform(){return this.#in.length>1&&this.#in.pop(),this}recordSimpleData(t,e){return this.#Ji[t]=e,this}recordIncrementalData(t,e){return this.#Qi[t].push(e),this}resetIncrementalData(t,e){return this.#Qi[t].length=0,this}recordNamedData(t,e){return this.#Zi.set(t,e),this}recordSimpleDataFromNamed(t,e,i){this.#Ji[t]=this.#Zi.get(e)??i}recordFutureForcedDependency(t,e){return this.recordIncrementalData(oi,e),this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Ji&&this.recordFutureForcedDependency(e,this.#Ji[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#an)this.recordFutureForcedDependency(oi,t);return this}resetBBox(t){return this.#rn!==t&&(this.#rn=t,this.#sn[0]=1/0,this.#sn[1]=1/0,this.#sn[2]=-1/0,this.#sn[3]=-1/0),this}recordClipBox(t,e,i,n,s,r){const a=Ct.multiplyByDOMMatrix(this.#in.at(-1),e.getTransform()),o=[1/0,1/0,-1/0,-1/0];Ct.axialAlignedBoundingBox([i,s,n,r],a,o);const l=Ct.intersect(this.#nn,o);return l?(this.#nn[0]=l[0],this.#nn[1]=l[1],this.#nn[2]=l[2],this.#nn[3]=l[3]):(this.#nn[0]=this.#nn[1]=1/0,this.#nn[2]=this.#nn[3]=-1/0),this}recordBBox(t,e,i,n,s,r){const a=this.#nn;if(a[0]===1/0)return this;const o=Ct.multiplyByDOMMatrix(this.#in.at(-1),e.getTransform());if(a[0]===-1/0)return Ct.axialAlignedBoundingBox([i,s,n,r],o,this.#sn),this;const l=[1/0,1/0,-1/0,-1/0];return Ct.axialAlignedBoundingBox([i,s,n,r],o,l),this.#sn[0]=Math.min(this.#sn[0],Math.max(l[0],a[0])),this.#sn[1]=Math.min(this.#sn[1],Math.max(l[1],a[1])),this.#sn[2]=Math.max(this.#sn[2],Math.min(l[2],a[2])),this.#sn[3]=Math.max(this.#sn[3],Math.min(l[3],a[3])),this}recordCharacterBBox(t,e,i,n=1,s=0,r=0,a){const o=i.bbox;let l,h;if(o&&(l=o[2]!==o[0]&&o[3]!==o[1]&&this.#ln.get(i),!1!==l&&(h=[0,0,0,0],Ct.axialAlignedBoundingBox(o,i.fontMatrix,h),1===n&&0===s&&0===r||Ct.scaleMinMax([n,0,0,-n,s,r],h),l)))return this.recordBBox(t,e,h[0],h[2],h[1],h[3]);if(!a)return this.recordFullPageBBox(t);const c=a();return o&&h&&void 0===l&&(l=h[0]<=s-c.actualBoundingBoxLeft&&h[2]>=s+c.actualBoundingBoxRight&&h[1]<=r-c.actualBoundingBoxAscent&&h[3]>=r+c.actualBoundingBoxDescent,this.#ln.set(i,l),l)?this.recordBBox(t,e,h[0],h[2],h[1],h[3]):this.recordBBox(t,e,s-c.actualBoundingBoxLeft,s+c.actualBoundingBoxRight,r-c.actualBoundingBoxAscent,r+c.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#sn[0]=Math.max(0,this.#nn[0]),this.#sn[1]=Math.max(0,this.#nn[1]),this.#sn[2]=Math.min(this.#hn,this.#nn[2]),this.#sn[3]=Math.min(this.#cn,this.#nn[3]),this}getSimpleIndex(t){return this.#Ji[t]}recordDependencies(t,e){const i=this.#an,n=this.#Ji,s=this.#Qi;for(const t of e)t in this.#Ji?i.add(n[t]):t in s&&s[t].forEach(i.add,i);return this}recordNamedDependency(t,e){return this.#Zi.has(e)&&this.#an.add(this.#Zi.get(e)),this}recordOperation(t,e=!1){if(this.recordDependencies(t,[oi]),this.#un){const e=pi(this.#un,t),{dependencies:i}=e;this.#an.forEach(i.add,i),this.#tn.forEach(i.add,i),this.#en.forEach(i.add,i),i.delete(t),e.isRenderingOperation=!0}if(this.#rn===t){const i=li(256*this.#sn[0]/this.#hn),n=li(256*this.#sn[1]/this.#cn),s=hi(256*this.#sn[2]/this.#hn),r=hi(256*this.#sn[3]/this.#cn);ci(this.#dn,t,i,n,s,r);for(const e of this.#an)e!==t&&ci(this.#dn,e,i,n,s,r);for(const e of this.#tn)e!==t&&ci(this.#dn,e,i,n,s,r);for(const e of this.#en)e!==t&&ci(this.#dn,e,i,n,s,r);e||(this.#an.clear(),this.#rn=-1)}return this}recordShowTextOperation(t,e=!1){const i=Array.from(this.#an);this.recordOperation(t,e),this.recordIncrementalData("sameLineText",t);for(const t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){return this.#rn===t&&(this.#rn=-1,this.#nn[0]=Math.max(this.#nn[0],this.#sn[0]),this.#nn[1]=Math.max(this.#nn[1],this.#sn[1]),this.#nn[2]=Math.min(this.#nn[2],this.#sn[2]),this.#nn[3]=Math.min(this.#nn[3],this.#sn[3]),e||this.#an.clear()),this}_takePendingDependencies(){const t=this.#an;return this.#an=new Set,t}_extractOperation(t){const e=this.#on.get(t);return this.#on.delete(t),e}_pushPendingDependencies(t){for(const e of t)this.#an.add(e)}take(){return this.#ln.clear(),new ui(this.#Ki,this.#dn)}takeDebugMetadata(){return this.#un}}class mi{#gn;#mn;#fn;#bn=0;#vn=0;constructor(t,e,i){if(t instanceof mi&&t.#fn===!!i)return t;this.#gn=t,this.#mn=e,this.#fn=!!i}growOperationsCount(){throw new Error("Unreachable")}save(t){return this.#vn++,this.#gn.save(this.#mn),this}restore(t){return this.#vn>0&&(this.#gn.restore(this.#mn),this.#vn--),this}recordOpenMarker(t){return this.#bn++,this}getOpenMarker(){return this.#bn>0?this.#mn:this.#gn.getOpenMarker()}recordCloseMarker(t){return this.#bn--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#gn.pushBaseTransform(t),this}popBaseTransform(){return this.#gn.popBaseTransform(),this}recordSimpleData(t,e){return this.#gn.recordSimpleData(t,this.#mn),this}recordIncrementalData(t,e){return this.#gn.recordIncrementalData(t,this.#mn),this}resetIncrementalData(t,e){return this.#gn.resetIncrementalData(t,this.#mn),this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){return this.#gn.recordSimpleDataFromNamed(t,e,this.#mn),this}recordFutureForcedDependency(t,e){return this.#gn.recordFutureForcedDependency(t,this.#mn),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#gn.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#gn.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#fn||this.#gn.resetBBox(this.#mn),this}recordClipBox(t,e,i,n,s,r){return this.#fn||this.#gn.recordClipBox(this.#mn,e,i,n,s,r),this}recordBBox(t,e,i,n,s,r){return this.#fn||this.#gn.recordBBox(this.#mn,e,i,n,s,r),this}recordCharacterBBox(t,e,i,n,s,r,a){return this.#fn||this.#gn.recordCharacterBBox(this.#mn,e,i,n,s,r,a),this}recordFullPageBBox(t){return this.#fn||this.#gn.recordFullPageBBox(this.#mn),this}getSimpleIndex(t){return this.#gn.getSimpleIndex(t)}recordDependencies(t,e){return this.#gn.recordDependencies(this.#mn,e),this}recordNamedDependency(t,e){return this.#gn.recordNamedDependency(this.#mn,e),this}recordOperation(t){return this.#gn.recordOperation(this.#mn,!0),this}recordShowTextOperation(t){return this.#gn.recordShowTextOperation(this.#mn,!0),this}bboxToClipBoxDropOperation(t){return this.#fn||this.#gn.bboxToClipBoxDropOperation(this.#mn,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const fi=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],bi=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],vi=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],yi=["filter","fillColor","fillAlpha"],wi=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],xi=["transform"],Ai=["transform","fillColor"],_i="Fill",Si="Stroke",Ci="Shading";function Ei(t,e){if(!e)return;const i=e[2]-e[0],n=e[3]-e[1],s=new Path2D;s.rect(e[0],e[1],i,n),t.clip(s)}class Ti{isModifyingCurrentTransform(){return!1}getPattern(){ht("Abstract method `getPattern` called.")}}class ki extends Ti{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,n){let s;if(n===Si||n===_i){const r=e.current.getClippedPathBoundingBox(n,qt(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,o=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",a,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-r[0],-r[1]),i=Ct.transform(i,[1,0,0,1,r[0],r[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),Ei(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),s=t.createPattern(l.canvas,"no-repeat");const c=new DOMMatrix(i);s.setTransform(c)}else Ei(t,this._bbox),s=this._createGradient(t);return s}}function Di(t,e,i,n,s,r,a,o){const l=e.coords,h=e.colors,c=t.data,d=4*t.width;let u;l[i+1]>l[n+1]&&(u=i,i=n,n=u,u=r,r=a,a=u),l[n+1]>l[s+1]&&(u=n,n=s,s=u,u=a,a=o,o=u),l[i+1]>l[n+1]&&(u=i,i=n,n=u,u=r,r=a,a=u);const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[n]+e.offsetX)*e.scaleX,f=(l[n+1]+e.offsetY)*e.scaleY,b=(l[s]+e.offsetX)*e.scaleX,v=(l[s+1]+e.offsetY)*e.scaleY;if(g>=v)return;const y=h[r],w=h[r+1],x=h[r+2],A=h[a],_=h[a+1],S=h[a+2],C=h[o],E=h[o+1],T=h[o+2],k=Math.round(g),D=Math.round(v);let M,P,I,R,L,B,F,O;for(let t=k;t<=D;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);M=p-(p-m)*e,P=y-(y-A)*e,I=w-(w-_)*e,R=x-(x-S)*e}else{let e;e=t>v?1:f===v?0:(f-t)/(f-v),M=m-(m-b)*e,P=A-(A-C)*e,I=_-(_-E)*e,R=S-(S-T)*e}let e;e=t<g?0:t>v?1:(g-t)/(g-v),L=p-(p-b)*e,B=y-(y-C)*e,F=w-(w-E)*e,O=x-(x-T)*e;const i=Math.round(Math.min(M,L)),n=Math.round(Math.max(M,L));let s=d*t+4*i;for(let t=i;t<=n;t++)e=(M-t)/(M-L),e<0?e=0:e>1&&(e=1),c[s++]=P-(P-B)*e|0,c[s++]=I-(I-F)*e|0,c[s++]=R-(R-O)*e|0,c[s++]=255}}function Mi(t,e,i){const n=e.coords,s=e.colors;let r,a;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(n.length/o)-1,h=o-1;for(r=0;r<l;r++){let e=r*o;for(let r=0;r<h;r++,e++)Di(t,i,n[e],n[e+1],n[e+o],s[e],s[e+1],s[e+o]),Di(t,i,n[e+o+1],n[e+1],n[e+o],s[e+o+1],s[e+1],s[e+o])}break;case"triangles":for(r=0,a=n.length;r<a;r+=3)Di(t,i,n[r],n[r+1],n[r+2],s[r],s[r+1],s[r+2]);break;default:throw new Error("illegal figure")}}class Pi extends Ti{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null}_createMeshCanvas(t,e,i){const n=Math.floor(this._bounds[0]),s=Math.floor(this._bounds[1]),r=Math.ceil(this._bounds[2])-n,a=Math.ceil(this._bounds[3])-s,o=Math.min(Math.ceil(Math.abs(r*t[0]*1.1)),3e3),l=Math.min(Math.ceil(Math.abs(a*t[1]*1.1)),3e3),h=r/o,c=a/l,d={coords:this._coords,colors:this._colors,offsetX:-n,offsetY:-s,scaleX:1/h,scaleY:1/c},u=o+4,p=l+4,g=i.getCanvas("mesh",u,p),m=g.context,f=m.createImageData(o,l);if(e){const t=f.data;for(let i=0,n=t.length;i<n;i+=4)t[i]=e[0],t[i+1]=e[1],t[i+2]=e[2],t[i+3]=255}for(const t of this._figures)Mi(f,t,d);m.putImageData(f,2,2);return{canvas:g.canvas,offsetX:n-2*h,offsetY:s-2*c,scaleX:h,scaleY:c}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,n){Ei(t,this._bbox);const s=new Float32Array(2);if(n===Ci)Ct.singularValueDecompose2dScale(qt(t),s);else if(this.matrix){Ct.singularValueDecompose2dScale(this.matrix,s);const[t,i]=s;Ct.singularValueDecompose2dScale(e.baseTransform,s),s[0]*=t,s[1]*=i}else Ct.singularValueDecompose2dScale(e.baseTransform,s);const r=this._createMeshCanvas(s,n===Ci?null:this._background,e.cachedCanvases);return n!==Ci&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class Ii extends Ti{getPattern(){return"hotpink"}}const Ri=1,Li=2;class Bi{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,n){this.color=t[1],this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.ctx=e,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t,e){const{bbox:i,operatorList:n,paintType:s,tilingType:r,color:a,canvasGraphicsFactory:o}=this;let{xstep:l,ystep:h}=this;l=Math.abs(l),h=Math.abs(h),ot("TilingType: "+r);const c=i[0],d=i[1],u=i[2],p=i[3],g=u-c,m=p-d,f=new Float32Array(2);Ct.singularValueDecompose2dScale(this.matrix,f);const[b,v]=f;Ct.singularValueDecompose2dScale(this.baseTransform,f);const y=b*f[0],w=v*f[1];let x=g,A=m,_=!1,S=!1;const C=Math.ceil(l*y),E=Math.ceil(h*w);C>=Math.ceil(g*y)?x=l:_=!0,E>=Math.ceil(m*w)?A=h:S=!0;const T=this.getSizeAndScale(x,this.ctx.canvas.width,y),k=this.getSizeAndScale(A,this.ctx.canvas.height,w),D=t.cachedCanvases.getCanvas("pattern",T.size,k.size),M=D.context,P=o.createCanvasGraphics(M,e);if(P.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(P,s,a),M.translate(-T.scale*c,-k.scale*d),P.transform(0,T.scale,0,0,k.scale,0,0),M.save(),P.dependencyTracker?.save(),this.clipBbox(P,c,d,u,p),P.baseTransform=qt(P.ctx),P.executeOperatorList(n),P.endDrawing(),P.dependencyTracker?.restore(),M.restore(),_||S){const e=D.canvas;_&&(x=l),S&&(A=h);const i=this.getSizeAndScale(x,this.ctx.canvas.width,y),n=this.getSizeAndScale(A,this.ctx.canvas.height,w),s=i.size,r=n.size,a=t.cachedCanvases.getCanvas("pattern-workaround",s,r),o=a.context,u=_?Math.floor(g/l):0,p=S?Math.floor(m/h):0;for(let t=0;t<=u;t++)for(let i=0;i<=p;i++)o.drawImage(e,s*t,r*i,s,r,0,0,s,r);return{canvas:a.canvas,scaleX:i.scale,scaleY:n.scale,offsetX:c,offsetY:d}}return{canvas:D.canvas,scaleX:T.scale,scaleY:k.scale,offsetX:c,offsetY:d}}getSizeAndScale(t,e,i){const n=Math.max(Bi.MAX_PATTERN_SIZE,e);let s=Math.ceil(t*i);return s>=n?s=n:i=s/t,{scale:i,size:s}}clipBbox(t,e,i,n,s){const r=n-e,a=s-i;t.ctx.rect(e,i,r,a),Ct.axialAlignedBoundingBox([e,i,n,s],qt(t.ctx),t.current.minMax),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const n=t.ctx,s=t.current;switch(e){case Ri:const{fillStyle:t,strokeStyle:r}=this.ctx;n.fillStyle=s.fillColor=t,n.strokeStyle=s.strokeColor=r;break;case Li:n.fillStyle=n.strokeStyle=i,s.fillColor=s.strokeColor=i;break;default:throw new yt(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,n,s){let r=i;n!==Ci&&(r=Ct.transform(r,e.baseTransform),this.matrix&&(r=Ct.transform(r,this.matrix)));const a=this.createPatternCanvas(e,s);let o=new DOMMatrix(r);o=o.translate(a.offsetX,a.offsetY),o=o.scale(1/a.scaleX,1/a.scaleY);const l=t.createPattern(a.canvas,"repeat");return l.setTransform(o),l}}function Fi({src:t,srcPos:e=0,dest:i,width:n,height:s,nonBlackColor:r=4294967295,inverseDecode:a=!1}){const o=_t.isLittleEndian?4278190080:255,[l,h]=a?[r,o]:[o,r],c=n>>3,d=7&n,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let n=0;n<s;n++){for(const n=e+c;e<n;e++){const n=e<u?t[e]:255;i[p++]=128&n?h:l,i[p++]=64&n?h:l,i[p++]=32&n?h:l,i[p++]=16&n?h:l,i[p++]=8&n?h:l,i[p++]=4&n?h:l,i[p++]=2&n?h:l,i[p++]=1&n?h:l}if(0===d)continue;const n=e<u?t[e++]:255;for(let t=0;t<d;t++)i[p++]=n&1<<7-t?h:l}return{srcPos:e,destPos:p}}const Oi=16,Ni=new DOMMatrix,Ui=new Float32Array(2),ji=new Float32Array([1/0,1/0,-1/0,-1/0]);class zi{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,i){let n;return void 0!==this.cache[t]?(n=this.cache[t],this.canvasFactory.reset(n,e,i)):(n=this.canvasFactory.create(e,i),this.cache[t]=n),n}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function Hi(t,e,i,n,s,r,a,o,l,h){const[c,d,u,p,g,m]=qt(t);if(0===d&&0===u){const f=a*c+g,b=Math.round(f),v=o*p+m,y=Math.round(v),w=(a+l)*c+g,x=Math.abs(Math.round(w)-b)||1,A=(o+h)*p+m,_=Math.abs(Math.round(A)-y)||1;return t.setTransform(Math.sign(c),0,0,Math.sign(p),b,y),t.drawImage(e,i,n,s,r,0,0,x,_),t.setTransform(c,d,u,p,g,m),[x,_]}if(0===c&&0===p){const f=o*u+g,b=Math.round(f),v=a*d+m,y=Math.round(v),w=(o+h)*u+g,x=Math.abs(Math.round(w)-b)||1,A=(a+l)*d+m,_=Math.abs(Math.round(A)-y)||1;return t.setTransform(0,Math.sign(d),Math.sign(u),0,b,y),t.drawImage(e,i,n,s,r,0,0,_,x),t.setTransform(c,d,u,p,g,m),[_,x]}t.drawImage(e,i,n,s,r,a,o,l,h);return[Math.hypot(c,d)*l,Math.hypot(u,p)*h]}class $i{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=S;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=N;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(t,e,i){i?.(this),this.clipBox=new Float32Array([0,0,t,e]),this.minMax=ji.slice()}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t}getPathBoundingBox(t=_i,e=null){const i=this.minMax.slice();if(t===Si){e||ht("Stroke bounding box must include transform."),Ct.singularValueDecompose2dScale(e,Ui);const t=Ui[0]*this.lineWidth/2,n=Ui[1]*this.lineWidth/2;i[0]-=t,i[1]-=n,i[2]+=t,i[3]+=n}return i}updateClipFromPath(){const t=Ct.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(ji,0)}getClippedPathBoundingBox(t=_i,e=null){return Ct.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function Wi(t,e){if(e instanceof ImageData)return void t.putImageData(e,0,0);const i=e.height,n=e.width,s=i%Oi,r=(i-s)/Oi,a=0===s?r:r+1,o=t.createImageData(n,Oi);let l,h=0;const c=e.data,d=o.data;let u,p,g,m;if(e.kind===W.GRAYSCALE_1BPP){const e=c.byteLength,i=new Uint32Array(d.buffer,0,d.byteLength>>2),m=i.length,f=n+7>>3,b=4294967295,v=_t.isLittleEndian?4278190080:255;for(u=0;u<a;u++){for(g=u<r?Oi:s,l=0,p=0;p<g;p++){const t=e-h;let s=0;const r=t>f?n:8*t-7,a=-8&r;let o=0,d=0;for(;s<a;s+=8)d=c[h++],i[l++]=128&d?b:v,i[l++]=64&d?b:v,i[l++]=32&d?b:v,i[l++]=16&d?b:v,i[l++]=8&d?b:v,i[l++]=4&d?b:v,i[l++]=2&d?b:v,i[l++]=1&d?b:v;for(;s<r;s++)0===o&&(d=c[h++],o=128),i[l++]=d&o?b:v,o>>=1}for(;l<m;)i[l++]=0;t.putImageData(o,0,u*Oi)}}else if(e.kind===W.RGBA_32BPP){for(p=0,m=n*Oi*4,u=0;u<r;u++)d.set(c.subarray(h,h+m)),h+=m,t.putImageData(o,0,p),p+=Oi;u<a&&(m=n*s*4,d.set(c.subarray(h,h+m)),t.putImageData(o,0,p))}else{if(e.kind!==W.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=Oi,m=n*g,u=0;u<a;u++){for(u>=r&&(g=s,m=n*g),l=0,p=m;p--;)d[l++]=c[h++],d[l++]=c[h++],d[l++]=c[h++],d[l++]=255;t.putImageData(o,0,u*Oi)}}}function Vi(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,n=e.width,s=i%Oi,r=(i-s)/Oi,a=0===s?r:r+1,o=t.createImageData(n,Oi);let l=0;const h=e.data,c=o.data;for(let e=0;e<a;e++){const i=e<r?Oi:s;({srcPos:l}=Fi({src:h,srcPos:l,dest:c,width:n,height:i,nonBlackColor:0})),t.putImageData(o,0,e*Oi)}}function Gi(t,e){const i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const n of i)void 0!==t[n]&&(e[n]=t[n]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function qi(t){t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0);const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function Xi(t,e){if(e)return!0;Ct.singularValueDecompose2dScale(t,Ui);const i=Math.fround(Yt.pixelRatio*Bt.PDF_TO_CSS_UNITS);return Ui[0]<=i&&Ui[1]<=i}const Ki=["butt","round","square"],Yi=["miter","round","bevel"],Ji={},Qi={};class Zi{constructor(t,e,i,n,s,{optionalContentConfig:r,markedContentStack:a=null},o,l,h){this.ctx=t,this.current=new $i(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=i,this.canvasFactory=n,this.filterFactory=s,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=a||[],this.optionalContentConfig=r,this.cachedCanvases=new zi(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=h??null}getObject(t,e,i=null){return"string"==typeof e?(this.dependencyTracker?.recordNamedDependency(t,e),e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)):i}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:n=null}){const s=this.ctx.canvas.width,r=this.ctx.canvas.height,a=this.ctx.fillStyle;if(this.ctx.fillStyle=n||"#ffffff",this.ctx.fillRect(0,0,s,r),this.ctx.fillStyle=a,i){const t=this.cachedCanvases.getCanvas("transparent",s,r);this.compositeCtx=this.ctx,this.transparentCanvas=t.canvas,this.ctx=t.context,this.ctx.save(),this.ctx.transform(...qt(this.compositeCtx))}this.ctx.save(),qi(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=qt(this.ctx)}executeOperatorList(t,e,i,n,s){const r=t.argsArray,a=t.fnArray;let o=e||0;const l=r.length;if(l===o)return o;const h=l-o>10&&"function"==typeof i,c=h?Date.now()+15:0;let d=0;const u=this.commonObjs,p=this.objs;let g,m;for(;;){if(void 0!==n&&o===n.nextBreakPoint)return n.breakIt(o,i),o;if(!s||s(o))if(g=a[o],m=r[o]??null,g!==Q.dependency)null===m?this[g](o):this[g](o,...m);else for(const t of m){this.dependencyTracker?.recordNamedData(t,o);const e=t.startsWith("g_")?u:p;if(!e.has(t))return e.get(t,i),o}if(o++,o===l)return o;if(h&&++d>10){if(Date.now()>c)return i(),o;d=0}}}#yn(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#yn(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#wn()}#wn(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,n=t.height??t.displayHeight;let s,r,a=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=n,c="prescale1";for(;a>2&&l>1||o>2&&h>1;){let e=l,i=h;a>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),a/=l/e),o>2&&h>1&&(i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/i),s=this.cachedCanvases.getCanvas(c,e,i),r=s.context,r.clearRect(0,0,e,i),r.drawImage(t,0,0,l,h,0,0,e,i),t=s.canvas,l=e,h=i,c="prescale1"===c?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t,e){const i=this.ctx,{width:n,height:s}=e,r=this.current.fillColor,a=this.current.patternFill,o=qt(i);let l,h,c,d;if((e.bitmap||e.data)&&e.count>1){const i=e.bitmap||e.data.buffer;h=JSON.stringify(a?o:[o.slice(0,4),r]),l=this._cachedBitmapsMap.get(i),l||(l=new Map,this._cachedBitmapsMap.set(i,l));const n=l.get(h);if(n&&!a){const e=Math.round(Math.min(o[0],o[2])+o[4]),i=Math.round(Math.min(o[1],o[3])+o[5]);return this.dependencyTracker?.recordDependencies(t,Ai),{canvas:n,offsetX:e,offsetY:i}}c=n}c||(d=this.cachedCanvases.getCanvas("maskCanvas",n,s),Vi(d.context,e));let u=Ct.transform(o,[1/n,0,0,-1/s,0,0]);u=Ct.transform(u,[1,0,0,1,0,-s]);const p=ji.slice();Ct.axialAlignedBoundingBox([0,0,n,s],u,p);const[g,m,f,b]=p,v=Math.round(f-g)||1,y=Math.round(b-m)||1,w=this.cachedCanvases.getCanvas("fillCanvas",v,y),x=w.context,A=g,_=m;x.translate(-A,-_),x.transform(...u),c||(c=this._scaleImage(d.canvas,Xt(x)),c=c.img,l&&a&&l.set(h,c)),x.imageSmoothingEnabled=Xi(qt(x),e.interpolate),Hi(x,c,0,0,c.width,c.height,0,0,n,s),x.globalCompositeOperation="source-in";const S=Ct.transform(Xt(x),[1,0,0,1,-A,-_]);return x.fillStyle=a?r.getPattern(i,this,S,_i,t):r,x.fillRect(0,0,n,s),l&&!a&&(this.cachedCanvases.delete("fillCanvas"),l.set(h,w.canvas)),this.dependencyTracker?.recordDependencies(t,Ai),{canvas:w.canvas,offsetX:Math.round(A),offsetY:Math.round(_)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t),e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=Ki[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=Yi[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=e}setDash(t,e,i){this.dependencyTracker?.recordSimpleData("dash",t);const n=this.ctx;void 0!==n.setLineDash&&(n.setLineDash(e),n.lineDashOffset=i)}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[i,n]of e)switch(i){case"LW":this.setLineWidth(t,n);break;case"LC":this.setLineCap(t,n);break;case"LJ":this.setLineJoin(t,n);break;case"ML":this.setMiterLimit(t,n);break;case"D":this.setDash(t,n[0],n[1]);break;case"RI":this.setRenderingIntent(t,n);break;case"FL":this.setFlatness(t,n);break;case"Font":this.setFont(t,n[0],n[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=n;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=n;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=n;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=n?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(n)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const e=this.ctx.canvas.width,i=this.ctx.canvas.height,n="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(n,e,i);this.suspendedCtx=this.ctx;const r=this.ctx=s.context;r.setTransform(this.suspendedCtx.getTransform()),Gi(this.suspendedCtx,r),function(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,n,s,r,a){e.transform(t,i,n,s,r,a),this.__originalTransform(t,i,n,s,r,a)},t.setTransform=function(t,i,n,s,r,a){e.setTransform(t,i,n,s,r,a),this.__originalSetTransform(t,i,n,s,r,a)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,n,s,r,a){e.bezierCurveTo(t,i,n,s,r,a),this.__originalBezierCurveTo(t,i,n,s,r,a)},t.rect=function(t,i,n,s){e.rect(t,i,n,s),this.__originalRect(t,i,n,s)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(r,this.suspendedCtx),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Gi(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,n){const s=n[0],r=n[1],a=n[2]-s,o=n[3]-r;0!==a&&0!==o&&(this.genericComposeSMask(e.context,i,a,o,e.subtype,e.backdrop,e.transferMap,s,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,n,s,r,a,o,l,h,c){let d=t.canvas,u=o-h,p=l-c;if(r)if(u<0||p<0||u+i>d.width||p+n>d.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,n),e=t.context;e.drawImage(d,-u,-p),e.globalCompositeOperation="destination-atop",e.fillStyle=r,e.fillRect(0,0,i,n),e.globalCompositeOperation="source-over",d=t.canvas,u=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,n),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=r,t.fillRect(u,p,i,n),t.restore()}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===s&&a?e.filter=this.filterFactory.addAlphaFilter(a):"Luminosity"===s&&(e.filter=this.filterFactory.addLuminosityFilter(a));const g=new Path2D;g.rect(o,l,i,n),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(d,u,p,i,n,o,l,i,n),e.restore()}save(t){this.inSMaskMode&&Gi(this.ctx,this.suspendedCtx),this.ctx.save();const e=this.current;this.stateStack.push(e),this.current=e.clone(),this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t),0!==this.stateStack.length?(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&Gi(this.suspendedCtx,this.ctx),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,n,s,r,a){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(e,i,n,s,r,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,n){let[s]=i;if(!n)return s||=i[0]=new Path2D,void this[e](t,s);if(null!==this.dependencyTracker){const i=e===Q.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,n[0]-i,n[2]+i,n[1]-i,n[3]+i).recordDependencies(t,["transform"])}if(!(s instanceof Path2D)){const t=i[0]=new Path2D;for(let e=0,i=s.length;e<i;)switch(s[e++]){case Z:t.moveTo(s[e++],s[e++]);break;case tt:t.lineTo(s[e++],s[e++]);break;case et:t.bezierCurveTo(s[e++],s[e++],s[e++],s[e++],s[e++],s[e++]);break;case it:t.closePath();break;default:lt(`Unrecognized drawing path operator: ${s[e-1]}`)}s=t}Ct.axialAlignedBoundingBox(n,qt(this.ctx),this.current.minMax),this[e](t,s),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){const n=this.ctx,s=this.current.strokeColor;if(n.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof s&&s?.getPattern){const i=s.isModifyingCurrentTransform()?n.getTransform():null;if(n.save(),n.strokeStyle=s.getPattern(n,this,Xt(n),Si,t),i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i)),e=t}this.rescaleAndStroke(e,!1),n.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,fi),i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(Si,qt(this.ctx))),n.globalAlpha=this.current.fillAlpha}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){const n=this.ctx,s=this.current.fillColor;let r=!1;if(this.current.patternFill){const i=s.isModifyingCurrentTransform()?n.getTransform():null;if(this.dependencyTracker?.save(t),n.save(),n.fillStyle=s.getPattern(n,this,Xt(n),_i,t),i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i)),e=t}r=!0}const a=this.current.getClippedPathBoundingBox();this.contentVisible&&null!==a&&(this.pendingEOFill?(n.fill(e,"evenodd"),this.pendingEOFill=!1):n.fill(e)),this.dependencyTracker?.recordDependencies(t,bi),r&&(n.restore(),this.dependencyTracker?.restore(t)),i&&this.consumePath(t,e,a)}eoFill(t,e){this.pendingEOFill=!0,this.fill(t,e)}fillStroke(t,e){this.fill(t,e,!1),this.stroke(t,e,!1),this.consumePath(t,e)}eoFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){this.ctx.fill(e),this.dependencyTracker?.recordDependencies(t,yi).recordOperation(t)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Ji}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Qi}beginText(t){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,i=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;void 0!==e&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t),i.recordCloseMarker(t)}if(void 0!==e){const t=new Path2D,n=i.getTransform().invertSelf();for(const{transform:i,x:s,y:r,fontSize:a,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(n).translate(s,r).scale(a,-a));i.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-e}setFont(t,e,i){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);const n=this.commonObjs.get(e),s=this.current;if(!n)throw new Error(`Can't find font for ${e}`);if(s.fontMatrix=n.fontMatrix||S,0!==s.fontMatrix[0]&&0!==s.fontMatrix[3]||lt("Invalid font matrix for font "+e),i<0?(i=-i,s.fontDirection=-1):s.fontDirection=1,this.current.font=n,this.current.fontSize=i,n.isType3Font)return;const r=n.loadedName||"sans-serif",a=n.systemFontInfo?.css||`"${r}", ${n.fallbackName}`;let o="normal";n.black?o="900":n.bold&&(o="bold");const l=n.italic?"italic":"normal";let h=i;i<16?h=16:i>100&&(h=100),this.current.fontSizeScale=i/h,this.ctx.font=`${l} ${o} ${h}px ${a}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=e}moveText(t,e,i){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=i}setLeadingMoveText(t,e,i){this.setLeading(t,-i),this.moveText(t,e,i)}setTextMatrix(t,e){this.dependencyTracker?.recordSimpleData("textMatrix",t);const{current:i}=this;i.textMatrix=e,i.textMatrixScale=Math.hypot(e[0],e[1]),i.x=i.lineX=0,i.y=i.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#xn(t,e,i){const n=new Path2D;return n.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e)),n}paintChar(t,e,i,n,s,r){const a=this.ctx,o=this.current,l=o.font,h=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,d=h&H,u=!!(h&$),p=o.patternFill&&!l.missingFile,g=o.patternStroke&&!l.missingFile;let m;if((l.disableFontFace||u||p||g)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,e)),m&&(l.disableFontFace||p||g)){let e;if(a.save(),a.translate(i,n),a.scale(c,-c),this.dependencyTracker?.recordCharacterBBox(t,a,l),d===N||d===j)if(s){e=a.getTransform(),a.setTransform(...s);const t=this.#xn(m,e,s);a.fill(t)}else a.fill(m);if(d===U||d===j)if(r){e||=a.getTransform(),a.setTransform(...r);const{a:t,b:i,c:n,d:s}=e,o=Ct.inverseTransform(r),l=Ct.transform([t,i,n,s,0,0],o);Ct.singularValueDecompose2dScale(l,Ui),a.lineWidth*=Math.max(Ui[0],Ui[1])/c,a.stroke(this.#xn(m,e,r))}else a.lineWidth/=c,a.stroke(m);a.restore()}else d!==N&&d!==j||(a.fillText(e,i,n),this.dependencyTracker?.recordCharacterBBox(t,a,l,c,i,n,()=>a.measureText(e))),d!==U&&d!==j||(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,a,l,c,i,n,()=>a.measureText(e)).recordDependencies(t,fi),a.strokeText(e,i,n));if(u){(this.pendingTextPaths||=[]).push({transform:qt(a),x:i,y:n,fontSize:c,path:m}),this.dependencyTracker?.recordCharacterBBox(t,a,l,c,i,n)}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){i=!0;break}return pt(this,"isFontSubpixelAAEnabled",i)}showText(t,e){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,wi).resetBBox(t),this.current.textRenderingMode&$&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());const i=this.current,n=i.font;if(n.isType3Font)return this.showType3Text(t,e),void this.dependencyTracker?.recordShowTextOperation(t);const s=i.fontSize;if(0===s)return void this.dependencyTracker?.recordOperation(t);const r=this.ctx,a=i.fontSizeScale,o=i.charSpacing,l=i.wordSpacing,h=i.fontDirection,c=i.textHScale*h,d=e.length,u=n.vertical,p=u?1:-1,g=n.defaultVMetrics,m=s*i.fontMatrix[0],f=i.textRenderingMode===N&&!n.disableFontFace&&!i.patternFill;let b,v;if(r.save(),i.textMatrix&&r.transform(...i.textMatrix),r.translate(i.x,i.y+i.textRise),h>0?r.scale(c,-1):r.scale(c,1),i.patternFill){r.save();const e=i.fillColor.getPattern(r,this,Xt(r),_i,t);b=qt(r),r.restore(),r.fillStyle=e}if(i.patternStroke){r.save();const e=i.strokeColor.getPattern(r,this,Xt(r),Si,t);v=qt(r),r.restore(),r.strokeStyle=e}let y=i.lineWidth;const w=i.textMatrixScale;if(0===w||0===y){const t=i.textRenderingMode&H;t!==U&&t!==j||(y=this.getSinglePixelWidth())}else y/=w;if(1!==a&&(r.scale(a,a),y/=a),r.lineWidth=y,n.isInvalidPDFjsFont){const n=[];let s=0;for(const t of e)n.push(t.unicode),s+=t.width;const a=n.join("");if(r.fillText(a,0,0),null!==this.dependencyTracker){const e=r.measureText(a);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}return i.x+=s*m*c,r.restore(),void this.compose()}let x,A=0;for(x=0;x<d;++x){const i=e[x];if("number"==typeof i){A+=p*i*s/1e3;continue}let c=!1;const d=(i.isSpace?l:0)+o,y=i.fontChar,w=i.accent;let _,S,C,E=i.width;if(u){const t=i.vmetric||g,e=-(i.vmetric?t[1]:.5*E)*m,n=t[2]*m;E=t?-t[0]:E,_=e/a,S=(A+n)/a}else _=A/a,S=0;if(n.remeasure&&E>0){C=r.measureText(y);const t=1e3*C.width/s*a;if(E<t&&this.isFontSubpixelAAEnabled){const e=E/t;c=!0,r.save(),r.scale(e,1),_/=e}else E!==t&&(_+=(E-t)/2e3*s/a)}if(this.contentVisible&&(i.isInFont||n.missingFile))if(f&&!w)r.fillText(y,_,S),this.dependencyTracker?.recordCharacterBBox(t,r,C?{bbox:null}:n,s/a,_,S,()=>C??r.measureText(y));else if(this.paintChar(t,y,_,S,b,v),w){const e=_+s*w.offset.x/a,i=S-s*w.offset.y/a;this.paintChar(t,w.fontChar,e,i,b,v)}A+=u?E*m-d*h:E*m+d*h,c&&r.restore()}u?i.y-=A:i.x+=A*c,r.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(t)}showType3Text(t,e){const i=this.ctx,n=this.current,s=n.font,r=n.fontSize,a=n.fontDirection,o=s.vertical?1:-1,l=n.charSpacing,h=n.wordSpacing,c=n.textHScale*a,d=n.fontMatrix||S,u=e.length;let p,g,m,f;if(n.textRenderingMode===z||0===r)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,i.save(),n.textMatrix&&i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),i.scale(c,a);const b=this.dependencyTracker;for(this.dependencyTracker=b?new mi(b,t):null,p=0;p<u;++p){if(g=e[p],"number"==typeof g){f=o*g*r/1e3,this.ctx.translate(f,0),n.x+=f*c;continue}const t=(g.isSpace?h:0)+l,a=s.charProcOperatorList[g.operatorListId];a?this.contentVisible&&(this.save(),i.scale(r,r),i.transform(...d),this.executeOperatorList(a),this.restore()):lt(`Type3 character "${g.operatorListId}" is not available.`);const u=[g.width,0];Ct.applyTransform(u,d),m=u[0]*r+t,i.translate(m,0),n.x+=m*c}i.restore(),b&&(this.dependencyTracker=b)}setCharWidth(t,e,i){}setCharWidthAndBounds(t,e,i,n,s,r,a){const o=new Path2D;o.rect(n,s,r-n,a-s),this.ctx.clip(o),this.dependencyTracker?.recordBBox(t,this.ctx,n,r,s,a).recordClipBox(t,this.ctx,n,r,s,a),this.endPath(t)}getColorN_Pattern(t,e){let i;if("TilingPattern"===e[0]){const t=this.baseTransform||qt(this.ctx),n={createCanvasGraphics:(t,e)=>new Zi(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new mi(this.dependencyTracker,e,!0):null)};i=new Bi(e,this.ctx,n,t)}else i=this._getPattern(t,e[1],e[2]);return i}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,e),this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.current.fillColor=this.getColorN_Pattern(t,e),this.current.patternFill=!0}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=e,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=e,this.current.patternFill=!1}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e,i=null){let n;return this.cachedPatterns.has(e)?n=this.cachedPatterns.get(e):(n=function(t){switch(t[0]){case"RadialAxial":return new ki(t);case"Mesh":return new Pi(t);case"Dummy":return new Ii}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e)),this.cachedPatterns.set(e,n)),i&&(n.matrix=i),n}shadingFill(t,e){if(!this.contentVisible)return;const i=this.ctx;this.save(t);const n=this._getPattern(t,e);i.fillStyle=n.getPattern(i,this,Xt(i),Ci,t);const s=Xt(i);if(s){const{width:t,height:e}=i.canvas,n=ji.slice();Ct.axialAlignedBoundingBox([0,0,t,e],s,n);const[r,a,o,l]=n;this.ctx.fillRect(r,a,o-r,l-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,xi).recordDependencies(t,bi).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t)}beginInlineImage(){ht("Should not call beginInlineImage")}beginImageData(){ht("Should not call beginImageData")}paintFormXObjectBegin(t,e,i){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),e&&this.transform(t,...e),this.baseTransform=qt(this.ctx),i)){Ct.axialAlignedBoundingBox(i,this.baseTransform,this.current.minMax);const[e,n,s,r]=i,a=new Path2D;a.rect(e,n,s-e,r-n),this.ctx.clip(a),this.dependencyTracker?.recordClipBox(t,this.ctx,e,s,n,r),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,e){if(!this.contentVisible)return;this.save(t),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const i=this.ctx;e.isolated||ot("TODO: Support non-isolated groups."),e.knockout&<("Knockout groups not supported.");const n=qt(i);if(e.matrix&&i.transform(...e.matrix),!e.bbox)throw new Error("Bounding box is required.");let s=ji.slice();Ct.axialAlignedBoundingBox(e.bbox,qt(i),s);const r=[0,0,i.canvas.width,i.canvas.height];s=Ct.intersect(s,r)||[0,0,0,0];const a=Math.floor(s[0]),o=Math.floor(s[1]),l=Math.max(Math.ceil(s[2])-a,1),h=Math.max(Math.ceil(s[3])-o,1);this.current.startNewPathAndClipBox([0,0,l,h]);let c="groupAt"+this.groupLevel;e.smask&&(c+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(c,l,h),u=d.context;u.translate(-a,-o),u.transform(...n);let p=new Path2D;const[g,m,f,b]=e.bbox;if(p.rect(g,m,f-g,b-m),e.matrix){const t=new Path2D;t.addPath(p,new DOMMatrix(e.matrix)),p=t}u.clip(p),e.smask&&this.smaskStack.push({canvas:d.canvas,context:u,offsetX:a,offsetY:o,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}),e.smask&&!this.dependencyTracker||(i.setTransform(1,0,0,1,0,0),i.translate(a,o),i.save()),Gi(i,u),this.ctx=u,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(i),this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const i=this.ctx,n=this.groupStack.pop();if(this.ctx=n,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),e.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&this.ctx.restore();else{this.ctx.restore();const e=qt(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...e);const n=ji.slice();Ct.axialAlignedBoundingBox([0,0,i.canvas.width,i.canvas.height],e,n),this.ctx.drawImage(i.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,i,n,s,r){if(this.#yn(),qi(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),i){const s=i[2]-i[0],a=i[3]-i[1];if(r&&this.annotationCanvasMap){(n=n.slice())[4]-=i[0],n[5]-=i[1],(i=i.slice())[0]=i[1]=0,i[2]=s,i[3]=a,Ct.singularValueDecompose2dScale(qt(this.ctx),Ui);const{viewportScale:t}=this,r=Math.ceil(s*this.outputScaleX*t),o=Math.ceil(a*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(r,o);const{canvas:l,context:h}=this.annotationCanvas;this.annotationCanvasMap.set(e,l),this.annotationCanvas.savedCtx=this.ctx,this.ctx=h,this.ctx.save(),this.ctx.setTransform(Ui[0],0,0,-Ui[1],0,a*Ui[1]),qi(this.ctx)}else{qi(this.ctx),this.endPath(t);const e=new Path2D;e.rect(i[0],i[1],s,a),this.ctx.clip(e)}}this.current=new $i(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(t,...n),this.transform(t,...s)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#wn(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const i=e.count;(e=this.getObject(t,e.data,e)).count=i;const n=this.ctx,s=this._createMaskCanvas(t,e),r=s.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(r,s.offsetX,s.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,s.offsetX,s.offsetX+r.width,s.offsetY,s.offsetY+r.height).recordOperation(t),n.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i,n=0,s=0,r,a){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.ctx;o.save();const l=qt(o);o.transform(i,n,s,r,0,0);const h=this._createMaskCanvas(t,e);o.setTransform(1,0,0,1,h.offsetX-l[4],h.offsetY-l[5]),this.dependencyTracker?.resetBBox(t);for(let e=0,c=a.length;e<c;e+=2){const c=Ct.transform(l,[i,n,s,r,a[e],a[e+1]]);o.drawImage(h.canvas,c[4],c[5]),this.dependencyTracker?.recordBBox(t,this.ctx,c[4],c[4]+h.canvas.width,c[5],c[5]+h.canvas.height)}o.restore(),this.compose(),this.dependencyTracker?.recordOperation(t)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.ctx,n=this.current.fillColor,s=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,Ai);for(const r of e){const{data:e,width:a,height:o,transform:l}=r,h=this.cachedCanvases.getCanvas("maskCanvas",a,o),c=h.context;c.save();Vi(c,this.getObject(t,e,r)),c.globalCompositeOperation="source-in",c.fillStyle=s?n.getPattern(c,this,Xt(i),_i,t):n,c.fillRect(0,0,a,o),c.restore(),i.save(),i.transform(...l),i.scale(1,-1),Hi(i,h.canvas,0,0,a,o,0,-1,1,1),this.dependencyTracker?.recordBBox(t,i,0,a,0,o),i.restore()}this.compose(),this.dependencyTracker?.recordOperation(t)}paintImageXObject(t,e){if(!this.contentVisible)return;const i=this.getObject(t,e);i?this.paintInlineImageXObject(t,i):lt("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,i,n,s){if(!this.contentVisible)return;const r=this.getObject(t,e);if(!r)return void lt("Dependent image isn't ready yet");const a=r.width,o=r.height,l=[];for(let t=0,e=s.length;t<e;t+=2)l.push({transform:[i,0,0,n,s[t],s[t+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(t,r,l)}applyTransferMapsToCanvas(t){return"none"!==this.current.transferMaps&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return t.bitmap;const{bitmap:e,width:i,height:n}=t,s=this.cachedCanvases.getCanvas("inlineImage",i,n),r=s.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",s.canvas}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const i=e.width,n=e.height,s=this.ctx;this.save(t);const{filter:r}=s;let a;if("none"!==r&&""!==r&&(s.filter="none"),s.scale(1/i,-1/n),e.bitmap)a=this.applyTransferMapsToBitmap(e);else if("function"==typeof HTMLElement&&e instanceof HTMLElement||!e.data)a=e;else{const t=this.cachedCanvases.getCanvas("inlineImage",i,n).context;Wi(t,e),a=this.applyTransferMapsToCanvas(t)}const o=this._scaleImage(a,Xt(s));s.imageSmoothingEnabled=Xi(qt(s),e.interpolate),this.dependencyTracker?.resetBBox(t).recordBBox(t,s,0,i,-n,0).recordDependencies(t,vi).recordOperation(t),Hi(s,o.img,0,0,o.paintWidth,o.paintHeight,0,-n,i,n),this.compose(),this.restore(t)}paintInlineImageXObjectGroup(t,e,i){if(!this.contentVisible)return;const n=this.ctx;let s;if(e.bitmap)s=e.bitmap;else{const t=e.width,i=e.height,n=this.cachedCanvases.getCanvas("inlineImage",t,i).context;Wi(n,e),s=this.applyTransferMapsToCanvas(n)}this.dependencyTracker?.resetBBox(t);for(const e of i)n.save(),n.transform(...e.transform),n.scale(1,-1),Hi(n,s,e.x,e.y,e.w,e.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,n,0,1,-1,0),n.restore();this.dependencyTracker?.recordOperation(t),this.compose()}paintSolidColorImageMask(t){this.contentVisible&&(this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,bi).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t,e){}markPointProps(t,e,i){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,i){this.dependencyTracker?.beginMarkedContent(t),"OC"===e?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(i)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,i){const n=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(i);const s=this.ctx;this.pendingClip?(n||(this.pendingClip===Qi?s.clip(e,"evenodd"):s.clip(e)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)):this.dependencyTracker?.recordOperation(t),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=qt(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),i=Math.hypot(t[0],t[2]),n=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,n)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:i,c:n,d:s}=this.ctx.getTransform();let r,a;if(0===i&&0===n){const i=Math.abs(e),n=Math.abs(s);if(i===n)if(0===t)r=a=1/i;else{const e=i*t;r=a=e<1?1/e:1}else if(0===t)r=1/i,a=1/n;else{const e=i*t,s=n*t;r=e<1?1/e:1,a=s<1?1/s:1}}else{const o=Math.abs(e*s-i*n),l=Math.hypot(e,i),h=Math.hypot(n,s);if(0===t)r=h/o,a=l/o;else{const e=t*o;r=h>e?h/e:1,a=l>e?l/e:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:n}}=this,[s,r]=this.getScaleForStroking();if(s===r)return i.lineWidth=(n||1)*s,void i.stroke(t);const a=i.getLineDash();e&&i.save(),i.scale(s,r),Ni.a=1/s,Ni.d=1/r;const o=new Path2D;if(o.addPath(t,Ni),a.length>0){const t=Math.max(s,r);i.setLineDash(a.map(e=>e/t)),i.lineDashOffset/=t}i.lineWidth=n||1,i.stroke(o),e&&i.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in Q)void 0!==Zi.prototype[t]&&(Zi.prototype[Q[t]]=Zi.prototype[t]);class tn{#An;#_n;#Sn;static strings=["fontFamily","fontWeight","italicAngle"];static write(t){const e=new TextEncoder,i={};let n=0;for(const s of tn.strings){const r=e.encode(t[s]);i[s]=r,n+=4+r.length}const s=new ArrayBuffer(n),r=new Uint8Array(s),a=new DataView(s);let o=0;for(const t of tn.strings){const e=i[t],n=e.length;a.setUint32(o,n),r.set(e,o+4),o+=4+n}return ct(o===s.byteLength,"CssFontInfo.write: Buffer overflow"),s}constructor(t){this.#An=t,this.#_n=new DataView(this.#An),this.#Sn=new TextDecoder}#Cn(t){ct(t<tn.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#_n.getUint32(e)+4;const i=this.#_n.getUint32(e);return this.#Sn.decode(new Uint8Array(this.#An,e+4,i))}get fontFamily(){return this.#Cn(0)}get fontWeight(){return this.#Cn(1)}get italicAngle(){return this.#Cn(2)}}class en{#An;#_n;#Sn;static strings=["css","loadedName","baseFontName","src"];static write(t){const e=new TextEncoder,i={};let n=0;for(const s of en.strings){const r=e.encode(t[s]);i[s]=r,n+=4+r.length}n+=4;let s,r,a=1+n;t.style&&(s=e.encode(t.style.style),r=e.encode(t.style.weight),a+=4+s.length+4+r.length);const o=new ArrayBuffer(a),l=new Uint8Array(o),h=new DataView(o);let c=0;h.setUint8(c++,t.guessFallback?1:0),h.setUint32(c,0),c+=4,n=0;for(const t of en.strings){const e=i[t],s=e.length;n+=4+s,h.setUint32(c,s),l.set(e,c+4),c+=4+s}return h.setUint32(c-n-4,n),t.style&&(h.setUint32(c,s.length),l.set(s,c+4),c+=4+s.length,h.setUint32(c,r.length),l.set(r,c+4),c+=4+r.length),ct(c<=o.byteLength,"SubstitionInfo.write: Buffer overflow"),o.transferToFixedLength(c)}constructor(t){this.#An=t,this.#_n=new DataView(this.#An),this.#Sn=new TextDecoder}get guessFallback(){return 0!==this.#_n.getUint8(0)}#Cn(t){ct(t<en.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#_n.getUint32(e)+4;const i=this.#_n.getUint32(e);return this.#Sn.decode(new Uint8Array(this.#An,e+4,i))}get css(){return this.#Cn(0)}get loadedName(){return this.#Cn(1)}get baseFontName(){return this.#Cn(2)}get src(){return this.#Cn(3)}get style(){let t=1;t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t),i=this.#Sn.decode(new Uint8Array(this.#An,t+4,e));t+=4+e;const n=this.#_n.getUint32(t);return{style:i,weight:this.#Sn.decode(new Uint8Array(this.#An,t+4,n))}}}class nn{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static#En=Math.ceil(2*this.bools.length/8);static#Tn=this.#En+8*this.numbers.length;static#kn=this.#Tn+1+8;static#Dn=this.#kn+1+48;static#Mn=this.#Dn+1+6;#An;#Sn;#_n;constructor({data:t,extra:e}){this.#An=t,this.#Sn=new TextDecoder,this.#_n=new DataView(this.#An),e&&Object.assign(this,e)}#Pn(t){ct(t<nn.bools.length,"Invalid boolean index");const e=Math.floor(t/4),i=2*t%8,n=this.#_n.getUint8(e)>>i&3;return 0===n?void 0:2===n}get black(){return this.#Pn(0)}get bold(){return this.#Pn(1)}get disableFontFace(){return this.#Pn(2)}get fontExtraProperties(){return this.#Pn(3)}get isInvalidPDFjsFont(){return this.#Pn(4)}get isType3Font(){return this.#Pn(5)}get italic(){return this.#Pn(6)}get missingFile(){return this.#Pn(7)}get remeasure(){return this.#Pn(8)}get vertical(){return this.#Pn(9)}#In(t){return ct(t<nn.numbers.length,"Invalid number index"),this.#_n.getFloat64(nn.#En+8*t)}get ascent(){return this.#In(0)}get defaultWidth(){return this.#In(1)}get descent(){return this.#In(2)}get bbox(){let t=nn.#Tn;if(0===this.#_n.getUint8(t))return;t+=1;const e=[];for(let i=0;i<4;i++)e.push(this.#_n.getInt16(t,!0)),t+=2;return e}get fontMatrix(){let t=nn.#kn;if(0===this.#_n.getUint8(t))return;t+=1;const e=[];for(let i=0;i<6;i++)e.push(this.#_n.getFloat64(t,!0)),t+=8;return e}get defaultVMetrics(){let t=nn.#Dn;if(0===this.#_n.getUint8(t))return;t+=1;const e=[];for(let i=0;i<3;i++)e.push(this.#_n.getInt16(t,!0)),t+=2;return e}#Cn(t){ct(t<nn.strings.length,"Invalid string index");let e=nn.#Mn+4;for(let i=0;i<t;i++)e+=this.#_n.getUint32(e)+4;const i=this.#_n.getUint32(e),n=new Uint8Array(i);return n.set(new Uint8Array(this.#An,e+4,i)),this.#Sn.decode(n)}get fallbackName(){return this.#Cn(0)}get loadedName(){return this.#Cn(1)}get mimetype(){return this.#Cn(2)}get name(){return this.#Cn(3)}get data(){let t=nn.#Mn;t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t);if(0!==e)return new Uint8Array(this.#An,t+4,e)}clearData(){let t=nn.#Mn;t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t);new Uint8Array(this.#An,t+4,e).fill(0),this.#_n.setUint32(t,0)}get cssFontInfo(){let t=nn.#Mn;t+=4+this.#_n.getUint32(t);t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);return i.set(new Uint8Array(this.#An,t+4,e)),new tn(i.buffer)}get systemFontInfo(){let t=nn.#Mn;t+=4+this.#_n.getUint32(t);const e=this.#_n.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);return i.set(new Uint8Array(this.#An,t+4,e)),new en(i.buffer)}static write(t){const e=t.systemFontInfo?en.write(t.systemFontInfo):null,i=t.cssFontInfo?tn.write(t.cssFontInfo):null,n=new TextEncoder,s={};let r=0;for(const e of nn.strings)s[e]=n.encode(t[e]),r+=4+s[e].length;const a=nn.#Mn+4+r+4+(e?e.byteLength:0)+4+(i?i.byteLength:0)+4+(t.data?t.data.length:0),o=new ArrayBuffer(a),l=new Uint8Array(o),h=new DataView(o);let c=0;const d=nn.bools.length;let u=0,p=0;for(let e=0;e<d;e++){const i=t[nn.bools[e]];u|=(void 0===i?0:i?2:1)<<p,p+=2,8!==p&&e!==d-1||(h.setUint8(c++,u),u=0,p=0)}ct(c===nn.#En,"FontInfo.write: Boolean properties offset mismatch");for(const e of nn.numbers)h.setFloat64(c,t[e]),c+=8;if(ct(c===nn.#Tn,"FontInfo.write: Number properties offset mismatch"),t.bbox){h.setUint8(c++,4);for(const e of t.bbox)h.setInt16(c,e,!0),c+=2}else h.setUint8(c++,0),c+=8;if(ct(c===nn.#kn,"FontInfo.write: BBox properties offset mismatch"),t.fontMatrix){h.setUint8(c++,6);for(const e of t.fontMatrix)h.setFloat64(c,e,!0),c+=8}else h.setUint8(c++,0),c+=48;if(ct(c===nn.#Dn,"FontInfo.write: FontMatrix properties offset mismatch"),t.defaultVMetrics){h.setUint8(c++,1);for(const e of t.defaultVMetrics)h.setInt16(c,e,!0),c+=2}else h.setUint8(c++,0),c+=6;ct(c===nn.#Mn,"FontInfo.write: DefaultVMetrics properties offset mismatch"),h.setUint32(nn.#Mn,0),c+=4;for(const t of nn.strings){const e=s[t],i=e.length;h.setUint32(c,i),l.set(e,c+4),c+=4+i}if(h.setUint32(nn.#Mn,c-nn.#Mn-4),e){const t=e.byteLength;h.setUint32(c,t),ct(c+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at systemFontInfo"),l.set(new Uint8Array(e),c+4),c+=4+t}else h.setUint32(c,0),c+=4;if(i){const t=i.byteLength;h.setUint32(c,t),ct(c+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at cssFontInfo"),l.set(new Uint8Array(i),c+4),c+=4+t}else h.setUint32(c,0),c+=4;return void 0===t.data?(h.setUint32(c,0),c+=4):(h.setUint32(c,t.data.length),l.set(t.data,c+4),c+=4+t.data.length),ct(c<=o.byteLength,"FontInfo.write: Buffer overflow"),o.transferToFixedLength(c)}}class sn{static#Rn=null;static#Ln="";static get workerPort(){return this.#Rn}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Rn=t}static get workerSrc(){return this.#Ln}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Ln=t}}class rn{#Bn;#Fn;constructor({parsedData:t,rawData:e}){this.#Bn=t,this.#Fn=e}getRaw(){return this.#Fn}get(t){return this.#Bn.get(t)??null}[Symbol.iterator](){return this.#Bn.entries()}}const an=Symbol("INTERNAL");class on{#On=!1;#Nn=!1;#Un=!1;#jn=!0;constructor(t,{name:e,intent:i,usage:n,rbGroups:s}){this.#On=!!(t&T),this.#Nn=!!(t&k),this.name=e,this.intent=i,this.usage=n,this.rbGroups=s}get visible(){if(this.#Un)return this.#jn;if(!this.#jn)return!1;const{print:t,view:e}=this.usage;return this.#On?"OFF"!==e?.viewState:!this.#Nn||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==an&&ht("Internal method `_setVisible` called."),this.#Un=i,this.#jn=e}}class ln{#zn=null;#Hn=new Map;#$n=null;#Wn=null;constructor(t,e=T){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Wn=t.order;for(const i of t.groups)this.#Hn.set(i.id,new on(e,i));if("OFF"===t.baseState)for(const t of this.#Hn.values())t._setVisible(an,!1);for(const e of t.on)this.#Hn.get(e)._setVisible(an,!0);for(const e of t.off)this.#Hn.get(e)._setVisible(an,!1);this.#$n=this.getHash()}}#Vn(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let n=1;n<e;n++){const e=t[n];let s;if(Array.isArray(e))s=this.#Vn(e);else{if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;s=this.#Hn.get(e).visible}switch(i){case"And":if(!s)return!1;break;case"Or":if(s)return!0;break;case"Not":return!s;default:return!0}}return"And"===i}isVisible(t){if(0===this.#Hn.size)return!0;if(!t)return ot("Optional content group not defined."),!0;if("OCG"===t.type)return this.#Hn.has(t.id)?this.#Hn.get(t.id).visible:(lt(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#Vn(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;if(this.#Hn.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;if(!this.#Hn.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;if(!this.#Hn.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#Hn.has(e))return lt(`Optional content group not found: ${e}`),!0;if(this.#Hn.get(e).visible)return!1}return!0}return lt(`Unknown optional content policy ${t.policy}.`),!0}return lt(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,i=!0){const n=this.#Hn.get(t);if(n){if(i&&e&&n.rbGroups.length)for(const e of n.rbGroups)for(const i of e)i!==t&&this.#Hn.get(i)?._setVisible(an,!1,!0);n._setVisible(an,!!e,!0),this.#zn=null}else lt(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(const n of t){switch(n){case"ON":case"OFF":case"Toggle":i=n;continue}const t=this.#Hn.get(n);if(t)switch(i){case"ON":this.setVisibility(n,!0,e);break;case"OFF":this.setVisibility(n,!1,e);break;case"Toggle":this.setVisibility(n,!t.visible,e)}}this.#zn=null}get hasInitialVisibility(){return null===this.#$n||this.getHash()===this.#$n}getOrder(){return this.#Hn.size?this.#Wn?this.#Wn.slice():[...this.#Hn.keys()]:null}getGroup(t){return this.#Hn.get(t)||null}getHash(){if(null!==this.#zn)return this.#zn;const t=new Ae;for(const[e,i]of this.#Hn)t.update(`${e}:${i.visible}`);return this.#zn=t.hexdigest()}[Symbol.iterator](){return this.#Hn.entries()}}class hn{constructor(t,{disableRange:e=!1,disableStream:i=!1}){ct(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:n,initialData:s,progressiveDone:r,contentDispositionFilename:a}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=a,s?.length>0){const t=s instanceof Uint8Array&&s.byteLength===s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!i,this._isRangeSupported=!e,this._contentLength=n,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((t,e)=>{this._onReceiveData({begin:t,chunk:e})}),t.addProgressListener((t,e)=>{this._onProgress({loaded:t,total:e})}),t.addProgressiveReadListener(t=>{this._onReceiveData({chunk:t})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{ct(this._rangeReaders.some(function(e){return e._begin===t&&(e._enqueue(i),!0)}),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){ct(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new cn(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new dn(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class cn{constructor(t,e,i=!1,n=null){this._stream=t,this._done=i||!1,this._filename=jt(n)?n:null,this._queuedChunks=e||[],this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class dn{constructor(t,e,i){this._stream=t,this._begin=e,this._end=i,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function un(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const n=e[t];void 0!==n&&i.append(t,n)}return i}function pn(t){return URL.parse(t)?.origin??null}function gn({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:n}){const s={allowRangeRequests:!1,suggestedLength:void 0},r=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(r))return s;if(s.suggestedLength=r,r<=2*i)return s;if(n||!e)return s;if("bytes"!==t.get("Accept-Ranges"))return s;return"identity"!==(t.get("Content-Encoding")||"identity")||(s.allowRangeRequests=!0),s}function mn(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=n("filename\\*","i").exec(t);if(i){i=i[1];let t=a(i);return t=unescape(t),t=o(t),t=l(t),r(t)}if(i=function(t){const e=[];let i;const s=n("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,n,s]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[n,s]}const r=[];for(let t=0;t<e.length&&t in e;++t){let[i,n]=e[t];n=a(n),i&&(n=unescape(n),0===t&&(n=o(n))),r.push(n)}return r.join("")}(t),i)return r(l(i));if(i=n("filename","i").exec(t),i){i=i[1];let t=a(i);return t=l(t),r(t)}function n(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function s(t,i){if(t){if(!/^[\x00-\xFF]+$/.test(i))return i;try{const n=new TextDecoder(t,{fatal:!0}),s=At(i);i=n.decode(s),e=!1}catch{}}return i}function r(t){return e&&/[\x80-\xff]/.test(t)&&(t=s("utf-8",t),e&&(t=s("iso-8859-1",t))),t}function a(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const i=e[t].indexOf('"');-1!==i&&(e[t]=e[t].slice(0,i),e.length=t+1),e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function o(t){const e=t.indexOf("'");return-1===e?t:s(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function l(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(t,e,i,n){if("q"===i||"Q"===i)return s(e,n=(n=n.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{n=atob(n)}catch{}return s(e,n)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(jt(t))return t}return null}function fn(t,e){return new vt(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t,404===t||0===t&&e.startsWith("file:"))}function bn(t){return 200===t||206===t}function vn(t,e,i){return{method:"GET",headers:t,signal:i.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function yn(t){return t instanceof Uint8Array?t.buffer:t instanceof ArrayBuffer?t:(lt(`getArrayBuffer - unexpected data format: ${t}`),new Uint8Array(t).buffer)}class wn{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=un(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return ct(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new xn(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new An(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class xn{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const i=new Headers(t.headers),n=e.url;fetch(n,vn(i,this._withCredentials,this._abortController)).then(e=>{if(t._responseOrigin=pn(e.url),!bn(e.status))throw fn(e.status,n);this._reader=e.body.getReader(),this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:s,suggestedLength:r}=gn({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=r||this._contentLength,this._filename=mn(i),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new wt("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:yn(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class An{constructor(t,e,i){this._stream=t,this._reader=null,this._loaded=0;const n=t.source;this._withCredentials=n.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!n.disableStream,this._abortController=new AbortController;const s=new Headers(t.headers);s.append("Range",`bytes=${e}-${i-1}`);const r=n.url;fetch(r,vn(s,this._withCredentials,this._abortController)).then(e=>{const i=pn(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!bn(e.status))throw fn(e.status,r);this._readCapability.resolve(),this._reader=e.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:yn(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class _n{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=un(this.isHttp,e),this.withCredentials=i||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,n=this.pendingRequests[i]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),n.expectedStatus=206):n.expectedStatus=200,e.responseType="arraybuffer",ct(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,i),e.onprogress=this.onProgress.bind(this,i),n.onHeadersReceived=t.onHeadersReceived,n.onDone=t.onDone,n.onError=t.onError,n.onProgress=t.onProgress,e.send(null),i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const n=i.xhr;if(n.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==n.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===n.status&&this.isHttp)return void i.onError(n.status);const s=n.status||200;if(!(200===s&&206===i.expectedStatus)&&s!==i.expectedStatus)return void i.onError(n.status);const r=function(t){const e=t.response;return"string"!=typeof e?e:At(e).buffer}(n);if(206===s){const t=n.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);e?i.onDone({begin:parseInt(e[1],10),chunk:r}):(lt('Missing or invalid "Content-Range" header.'),i.onError(0))}else r?i.onDone({begin:0,chunk:r}):i.onError(n.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Sn{constructor(t){this._source=t,this._manager=new _n(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return ct(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Cn(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const i=new En(this._manager,t,e);return i.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Cn{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=pn(e.responseURL);const i=e.getAllResponseHeaders(),n=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{allowRangeRequests:s,suggestedLength:r}=gn({responseHeaders:n,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});s&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=mn(n),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);if(this._done=!0,!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=fn(t,this._url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class En{constructor(t,e,i){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){const t=pn(this._manager.getRequestXhr(this._requestId)?.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError??=fn(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const Tn=/^[a-z][a-z0-9\-+.]+:/i;class kn{constructor(t){this.source=t,this.url=function(t){if(Tn.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url),ct("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return ct(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Dn(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new Mn(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Dn{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then(t=>{this._contentLength=t.size,this._setReadableStream(i.createReadStream(this._url)),this._headersCapability.resolve()},t=>{"ENOENT"===t.code&&(t=fn(0,this._url.href)),this._storedError=t,this._headersCapability.reject(t)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",t=>{this._error(t)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new wt("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Mn{constructor(t,e,i){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const n=t.source;this._isStreamingSupported=!n.disableStream;const s=process.getBuiltinModule("fs");this._setReadableStream(s.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",t=>{this._error(t)}),this._storedError&&this._readableStream.destroy(this._storedError)}}const Pn=Symbol("INITIAL_DATA");class In{#Gn=Object.create(null);#qn(t){return this.#Gn[t]||={...Promise.withResolvers(),data:Pn}}get(t,e=null){if(e){const i=this.#qn(t);return i.promise.then(()=>e(i.data)),null}const i=this.#Gn[t];if(!i||i.data===Pn)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Gn[t];return!!e&&e.data!==Pn}delete(t){const e=this.#Gn[t];return!(!e||e.data===Pn)&&(delete this.#Gn[t],!0)}resolve(t,e=null){const i=this.#qn(t);i.data=e,i.resolve()}clear(){for(const t in this.#Gn){const{data:e}=this.#Gn[t];e?.bitmap?.close()}this.#Gn=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Gn){const{data:e}=this.#Gn[t];e!==Pn&&(yield[t,e])}}}class Rn{#Xn=Promise.withResolvers();#xt=null;#Kn=!1;#Yn=!!globalThis.FontInspector?.enabled;#Jn=null;#Qn=null;#Zn=0;#ts=0;#es=null;#is=null;#ns=0;#ss=0;#rs=Object.create(null);#as=[];#os=null;#ls=[];#hs=new WeakMap;#cs=null;static#ds=new Map;static#us=new Map;static#ps=new WeakMap;static#gs=null;static#ms=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#os=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#os=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#xt=this.#is=e,this.#ss=i.scale*Yt.pixelRatio,this.#ns=i.rotation,this.#Qn={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:s,pageX:r,pageY:a}=i.rawDims;this.#cs=[1,0,0,-1,-r,a+s],this.#ts=n,this.#Zn=s,Rn.#fs(),Kt(e,i),this.#Xn.promise.finally(()=>{Rn.#ms.delete(this),this.#Qn=null,this.#rs=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=_t.platform;return pt(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const t=()=>{this.#es.read().then(({value:e,done:i})=>{i?this.#Xn.resolve():(this.#Jn??=e.lang,Object.assign(this.#rs,e.styles),this.#bs(e.items),t())},this.#Xn.reject)};return this.#es=this.#os.getReader(),Rn.#ms.add(this),t(),this.#Xn.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*Yt.pixelRatio,n=t.rotation;if(n!==this.#ns&&(e?.(),this.#ns=n,Kt(this.#is,{rotation:n})),i!==this.#ss){e?.(),this.#ss=i;const t={div:null,properties:null,ctx:Rn.#vs(this.#Jn)};for(const e of this.#ls)t.properties=this.#hs.get(e),t.div=e,this.#ys(t)}}cancel(){const t=new wt("TextLayer task cancelled.");this.#es?.cancel(t).catch(()=>{}),this.#es=null,this.#Xn.reject(t)}get textDivs(){return this.#ls}get textContentItemsStr(){return this.#as}#bs(t){if(this.#Kn)return;this.#Qn.ctx??=Rn.#vs(this.#Jn);const e=this.#ls,i=this.#as;for(const n of t){if(e.length>1e5)return lt("Ignoring additional textDivs for performance reasons."),void(this.#Kn=!0);if(void 0!==n.str)i.push(n.str),this.#ws(n);else if("beginMarkedContentProps"===n.type||"beginMarkedContent"===n.type){const t=this.#xt;this.#xt=document.createElement("span"),this.#xt.classList.add("markedContent"),n.id&&this.#xt.setAttribute("id",`${n.id}`),t.append(this.#xt)}else"endMarkedContent"===n.type&&(this.#xt=this.#xt.parentNode)}}#ws(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ls.push(e);const n=Ct.transform(this.#cs,t.transform);let s=Math.atan2(n[1],n[0]);const r=this.#rs[t.fontName];r.vertical&&(s+=Math.PI/2);let a=this.#Yn&&r.fontSubstitution||r.fontFamily;a=Rn.fontFamilyMap.get(a)||a;const o=Math.hypot(n[2],n[3]),l=o*Rn.#xs(a,r,this.#Jn);let h,c;0===s?(h=n[4],c=n[5]-l):(h=n[4]+l*Math.sin(s),c=n[5]-l*Math.cos(s));const d="calc(var(--total-scale-factor) *",u=e.style;this.#xt===this.#is?(u.left=`${(100*h/this.#ts).toFixed(2)}%`,u.top=`${(100*c/this.#Zn).toFixed(2)}%`):(u.left=`${d}${h.toFixed(2)}px)`,u.top=`${d}${c.toFixed(2)}px)`),u.fontSize=`${d}${(Rn.#gs*o).toFixed(2)}px)`,u.fontFamily=a,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#Yn&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),0!==s&&(i.angle=s*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}if(p&&(i.canvasWidth=r.vertical?t.height:t.width),this.#hs.set(e,i),this.#Qn.div=e,this.#Qn.properties=i,this.#ys(this.#Qn),i.hasText&&this.#xt.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#xt.append(t)}}#ys(t){const{div:e,properties:i,ctx:n}=t,{style:s}=e;let r="";if(Rn.#gs>1&&(r=`scale(${1/Rn.#gs})`),0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=s,{canvasWidth:a,fontSize:o}=i;Rn.#As(n,o*this.#ss,t);const{width:l}=n.measureText(e.textContent);l>0&&(r=`scaleX(${a*this.#ss/l}) ${r}`)}0!==i.angle&&(r=`rotate(${i.angle}deg) ${r}`),r.length>0&&(s.transform=r)}static cleanup(){if(!(this.#ms.size>0)){this.#ds.clear();for(const{canvas:t}of this.#us.values())t.remove();this.#us.clear()}}static#vs(t=null){let e=this.#us.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#us.set(t,e),this.#ps.set(e,{size:0,family:""})}return e}static#As(t,e,i){const n=this.#ps.get(t);e===n.size&&i===n.family||(t.font=`${e}px ${i}`,n.size=e,n.family=i)}static#fs(){if(null!==this.#gs)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#gs=t.getBoundingClientRect().height,t.remove()}static#xs(t,e,i){const n=this.#ds.get(t);if(n)return n;const s=this.#vs(i);s.canvas.width=s.canvas.height=30,this.#As(s,30,t);const r=s.measureText(""),a=r.fontBoundingBoxAscent,o=Math.abs(r.fontBoundingBoxDescent);s.canvas.width=s.canvas.height=0;let l=.8;return a?l=a/(a+o):(_t.platform.isFirefox&<("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)),this.#ds.set(t,l),l}}function Ln(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new Bn,{docId:i}=e,n=t.url?function(t){if(t instanceof URL)return t.href;if("string"==typeof t){if(_)return t;const e=URL.parse(t,window.location);if(e)return e.href}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,s=t.data?function(t){if(_&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return At(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,a=!0===t.withCredentials,o=t.password??null,l=t.range instanceof Fn?t.range:null,h=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let c=t.worker instanceof Un?t.worker:null;const d=t.verbosity,u="string"!=typeof t.docBaseUrl||Ut(t.docBaseUrl)?null:t.docBaseUrl,p=ke(t.cMapUrl),g=!1!==t.cMapPacked,m=t.CMapReaderFactory||(_?si:Xe),f=ke(t.iccUrl),b=ke(t.standardFontDataUrl),v=t.StandardFontDataFactory||(_?ri:Qe),y=ke(t.wasmUrl),w=t.WasmFactory||(_?ai:ti),x=!0!==t.stopAtErrors,A=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,S=!1!==t.isEvalSupported,C="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!_,E="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!_&&(_t.platform.isFirefox||!globalThis.chrome),T=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,k="boolean"==typeof t.disableFontFace?t.disableFontFace:_,D=!0===t.fontExtraProperties,M=!0===t.enableXfa,P=t.ownerDocument||globalThis.document,I=!0===t.disableRange,R=!0===t.disableStream,L=!0===t.disableAutoFetch,B=!0===t.pdfBug,F=t.CanvasFactory||(_?ni:Ge),O=t.FilterFactory||(_?ii:Ye),N=!0===t.enableHWA,U=!1!==t.useWasm,j=l?l.length:t.length??NaN,z="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!_&&!k,H="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:!!(m===Xe&&v===Qe&&w===ti&&p&&b&&y&&Ht(p,document.baseURI)&&Ht(b,document.baseURI)&&Ht(y,document.baseURI));rt(d);const $={canvasFactory:new F({ownerDocument:P,enableHWA:N}),filterFactory:new O({docId:i,ownerDocument:P}),cMapReaderFactory:H?null:new m({baseUrl:p,isCompressed:g}),standardFontDataFactory:H?null:new v({baseUrl:b}),wasmFactory:H?null:new w({baseUrl:y})};c||(c=Un.create({verbosity:d,port:sn.workerPort}),e._worker=c);const W={docId:i,apiVersion:"5.4.296",data:s,password:o,disableAutoFetch:L,rangeChunkSize:h,length:j,docBaseUrl:u,enableXfa:M,evaluatorOptions:{maxImageSize:A,disableFontFace:k,ignoreErrors:x,isEvalSupported:S,isOffscreenCanvasSupported:C,isImageDecoderSupported:E,canvasMaxAreaInBytes:T,fontExtraProperties:D,useSystemFonts:z,useWasm:U,useWorkerFetch:H,cMapUrl:p,iccUrl:f,standardFontDataUrl:b,wasmUrl:y}},V={ownerDocument:P,pdfBug:B,styleElement:null,loadingParams:{disableAutoFetch:L,enableXfa:M}};return c.promise.then(function(){if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",W,s?[s.buffer]:null);let o;if(l)o=new hn(l,{disableRange:I,disableStream:R});else if(!s){if(!n)throw new Error("getDocument - no `url` parameter provided.");const t=Ht(n)?wn:_?kn:Sn;o=new t({url:n,length:j,httpHeaders:r,withCredentials:a,rangeChunkSize:h,disableRange:I,disableStream:R})}return t.then(t=>{if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const n=new We(i,t,c.port),s=new jn(n,e,o,V,$,N);e._transport=s,n.send("Ready",null)})}).catch(e._capability.reject),e}class Bn{static#Bi=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+Bn.#Bi++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class Fn{#Xn=Promise.withResolvers();#_s=[];#Ss=[];#Cs=[];#Es=[];constructor(t,e,i=!1,n=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=n}addRangeListener(t){this.#Es.push(t)}addProgressListener(t){this.#Cs.push(t)}addProgressiveReadListener(t){this.#Ss.push(t)}addProgressiveDoneListener(t){this.#_s.push(t)}onDataRange(t,e){for(const i of this.#Es)i(t,e)}onDataProgress(t,e){this.#Xn.promise.then(()=>{for(const i of this.#Cs)i(t,e)})}onDataProgressiveRead(t){this.#Xn.promise.then(()=>{for(const e of this.#Ss)e(t)})}onDataProgressiveDone(){this.#Xn.promise.then(()=>{for(const t of this.#_s)t()})}transportReady(){this.#Xn.resolve()}requestDataRange(t,e){ht("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class On{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return pt(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class Nn{#Ts=!1;constructor(t,e,i,n=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=n?new zt:null,this._pdfBug=n,this.commonObjs=i.commonObjs,this.objs=new In,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:n=0,dontFlip:s=!1}={}){return new Ot({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return pt(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:i,intent:n="display",annotationMode:s=L.ENABLE,transform:r=null,background:a=null,optionalContentConfigPromise:o=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:c=null,isEditing:d=!1,recordOperations:u=!1,operationsFilter:p=null}){this._stats?.time("Overall");const g=this._transport.getRenderingIntent(n,s,c,d),{renderingIntent:m,cacheKey:f}=g;this.#Ts=!1,o||=this._transport.getOptionalContentConfig(m);let b=this._intentStates.get(f);b||(b=Object.create(null),this._intentStates.set(f,b)),b.streamReaderCancelTimeout&&(clearTimeout(b.streamReaderCancelTimeout),b.streamReaderCancelTimeout=null);const v=!!(m&k);b.displayReadyCapability||(b.displayReadyCapability=Promise.withResolvers(),b.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(g));const y=Boolean(this._pdfBug&&globalThis.StepperManager?.enabled),w=!this.recordedBBoxes&&(u||y),x=t=>{if(b.renderTasks.delete(A),w){const t=A.gfx?.dependencyTracker.take();t&&(A.stepper&&A.stepper.setOperatorBBoxes(t,A.gfx.dependencyTracker.takeDebugMetadata()),u&&(this.recordedBBoxes=t))}v&&(this.#Ts=!0),this.#ks(),t?(A.capability.reject(t),this._abortOperatorList({intentState:b,reason:t instanceof Error?t:new Error(t)})):A.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},A=new Hn({callback:x,params:{canvas:e,canvasContext:t,dependencyTracker:w?new gi(e,b.operatorList.length,y):null,viewport:i,transform:r,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:b.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!v,pdfBug:this._pdfBug,pageColors:h,enableHWA:this._transport.enableHWA,operationsFilter:p});(b.renderTasks||=new Set).add(A);const _=A.task;return Promise.all([b.displayReadyCapability.promise,o]).then(([t,e])=>{if(this.destroyed)x();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&m))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:t,optionalContentConfig:e}),A.operatorListChanged()}}).catch(x),_}getOperatorList({intent:t="display",annotationMode:e=L.ENABLE,printAnnotationStorage:i=null,isEditing:n=!1}={}){const s=this._transport.getRenderingIntent(t,e,i,n,!0);let r,a=this._intentStates.get(s.cacheKey);return a||(a=Object.create(null),this._intentStates.set(s.cacheKey,a)),a.opListReadCapability||(r=Object.create(null),r.operatorListChanged=function(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(r))},a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||=new Set).add(r),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(s)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>It.textContent(t));const e=this.streamTextContent(t);return new Promise(function(t,i){const n=e.getReader(),s={items:[],styles:Object.create(null),lang:null};!function e(){n.read().then(function({value:i,done:n}){n?t(s):(s.lang??=i.lang,Object.assign(s.styles,i.styles),s.items.push(...i.items),e())},i)}()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#Ts=!1,Promise.all(t)}cleanup(t=!1){this.#Ts=!0;const e=this.#ks();return t&&e&&(this._stats&&=new zt),e}#ks(){if(!this.#Ts||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#Ts=!1,!0}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,n=t.length;i<n;i++)e.operatorList.fnArray.push(t.fnArray[i]),e.operatorList.argsArray.push(t.argsArray[i]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#ks()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:n}){const{map:s,transfer:r}=i,a=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:s,modifiedIds:n},r).getReader(),o=this._intentStates.get(e);o.streamReader=a;const l=()=>{a.read().then(({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())},t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#ks()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof Nt){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i))}}if(t.streamReader.cancel(new wt(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class Un{#Xn=Promise.withResolvers();#Ds=null;#Rn=null;#Ms=null;static#Ps=0;static#Is=!1;static#Rs=new WeakMap;static{_&&(this.#Is=!0,sn.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const n=new URL(e,i);return i.origin===n.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))},this.fromPort=t=>{var e;if(e="`PDFWorker.fromPort` - please use `PDFWorker.create` instead.",console.log("Deprecated API usage: "+e),!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.create(t)}}constructor({name:t=null,port:e=null,verbosity:i=at()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,e){if(Un.#Rs.has(e))throw new Error("Cannot use more than one PDFWorker per port.");Un.#Rs.set(e,this),this.#Ls(e)}else this.#Bs()}get promise(){return this.#Xn.promise}#Fs(){this.#Xn.resolve(),this.#Ds.send("configure",{verbosity:this.verbosity})}get port(){return this.#Rn}get messageHandler(){return this.#Ds}#Ls(t){this.#Rn=t,this.#Ds=new We("main","worker",t),this.#Ds.on("ready",()=>{}),this.#Fs()}#Bs(){if(Un.#Is||Un.#Os)return void this.#Ns();let{workerSrc:t}=Un;try{Un._isSameOrigin(window.location,t)||(t=Un._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new We("main","worker",e),n=()=>{s.abort(),i.destroy(),e.terminate(),this.destroyed?this.#Xn.reject(new Error("Worker was destroyed")):this.#Ns()},s=new AbortController;e.addEventListener("error",()=>{this.#Ms||n()},{signal:s.signal}),i.on("test",t=>{s.abort(),!this.destroyed&&t?(this.#Ds=i,this.#Rn=e,this.#Ms=e,this.#Fs()):n()}),i.on("ready",t=>{if(s.abort(),this.destroyed)n();else try{r()}catch{this.#Ns()}});const r=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void r()}catch{ot("The worker has been disabled.")}this.#Ns()}#Ns(){Un.#Is||(lt("Setting up fake worker."),Un.#Is=!0),Un._setupFakeWorkerGlobal.then(t=>{if(this.destroyed)return void this.#Xn.reject(new Error("Worker was destroyed"));const e=new Pe;this.#Rn=e;const i="fake"+Un.#Ps++,n=new We(i+"_worker",i,e);t.setup(n,e),this.#Ds=new We(i,i+"_worker",e),this.#Fs()}).catch(t=>{this.#Xn.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this.#Ms?.terminate(),this.#Ms=null,Un.#Rs.delete(this.#Rn),this.#Rn=null,this.#Ds?.destroy(),this.#Ds=null}static create(t){const e=this.#Rs.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new Un(t)}static get workerSrc(){if(sn.workerSrc)return sn.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Os(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return pt(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Os)return this.#Os;return(await(import(this.workerSrc))).WorkerMessageHandler})())}}class jn{#Us=new Map;#js=new Map;#zs=new Map;#Hs=new Map;#$s=null;constructor(t,e,i,n,s,r){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new In,this.fontLoader=new Ee({ownerDocument:n.ownerDocument,styleElement:n.styleElement}),this.loadingParams=n.loadingParams,this._params=n,this.canvasFactory=s.canvasFactory,this.filterFactory=s.filterFactory,this.cMapReaderFactory=s.cMapReaderFactory,this.standardFontDataFactory=s.standardFontDataFactory,this.wasmFactory=s.wasmFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=i,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.enableHWA=r,this.setupMessageHandler()}#Ws(t,e=null){const i=this.#Us.get(t);if(i)return i;const n=this.messageHandler.sendWithPromise(t,e);return this.#Us.set(t,n),n}get annotationStorage(){return pt(this,"annotationStorage",new Se)}getRenderingIntent(t,e=L.ENABLE,i=null,n=!1,s=!1){let r=T,a=_e;switch(t){case"any":r=E;break;case"display":break;case"print":r=k;break;default:lt(`getRenderingIntent - invalid intent: ${t}`)}const o=r&k&&i instanceof Ce?i:this.annotationStorage;switch(e){case L.DISABLE:r+=P;break;case L.ENABLE:break;case L.ENABLE_FORMS:r+=D;break;case L.ENABLE_STORAGE:r+=M,a=o.serializable;break;default:lt(`getRenderingIntent - invalid annotationMode: ${e}`)}n&&(r+=I),s&&(r+=R);const{ids:l,hash:h}=o.modifiedIds;return{renderingIntent:r,cacheKey:[r,a.hash,h].join("_"),annotationStorageSerializable:a,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#$s?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#js.values())t.push(e._destroy());this.#js.clear(),this.#zs.clear(),this.#Hs.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#Us.clear(),this.filterFactory.destroy(),Rn.cleanup(),this._networkStream?.cancelAllRequests(new wt("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{ct(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}},e.onPull=()=>{this._fullReader.read().then(function({value:t,done:i}){i?e.close():(ct(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{this._fullReader.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("ReaderHeadersReady",async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:s}=this._fullReader;return i&&n||(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:s}}),t.on("GetRangeReader",(t,e)=>{ct(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then(function({value:t,done:i}){i?e.close():(ct(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{i.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}):e.close()}),t.on("GetDoc",({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new On(t,this))}),t.on("DocException",t=>{e._capability.reject($e(t))}),t.on("PasswordRequest",t=>{this.#$s=Promise.withResolvers();try{if(!e.onPassword)throw $e(t);const i=t=>{t instanceof Error?this.#$s.reject(t):this.#$s.resolve({password:t})};e.onPassword(i,t.code)}catch(t){this.#$s.reject(t)}return this.#$s.promise}),t.on("DataLoaded",t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)}),t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#js.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}),t.on("commonobj",([e,i,n])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in n){const t=n.error;lt(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const s=new nn(n),r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new Te(s,r,n.extra,n.charProcOperatorList);this.fontLoader.bind(a).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{!a.fontExtraProperties&&a.data&&a.clearData(),this.commonObjs.resolve(e,a)});break;case"CopyLocalImage":const{imageRef:o}=n;ct(o,"The imageRef must be defined.");for(const t of this.#js.values())for(const[,i]of t.objs)if(i?.ref===o)return i.dataLen?(this.commonObjs.resolve(e,structuredClone(i)),i.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([t,e,i,n])=>{if(this.destroyed)return;const s=this.#js.get(e);if(!s.objs.has(t))if(0!==s._intentStates.size)switch(i){case"Image":case"Pattern":s.objs.resolve(t,n);break;default:throw new Error(`Got unknown object type ${i}`)}else n?.bitmap?.close()}),t.on("DocProgress",t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}),t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");const e=this[t.type];if(!e)throw new Error(`${t.type} not initialized, see the \`useWorkerFetch\` parameter.`);return e.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&<("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#zs.get(e);if(i)return i;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#Hs.set(i.refStr,t);const n=new Nn(e,i,this,this._params.pdfBug);return this.#js.set(e,n),n});return this.#zs.set(e,n),n}getPageIndex(t){return De(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Ws("GetFieldObjects")}hasJSActions(){return this.#Ws("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#Ws("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Ws("GetOptionalContentConfig").then(e=>new ln(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Us.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new rn(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#Us.set(t,i),i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#js.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear(),t||this.fontLoader.clear(),this.#Us.clear(),this.filterFactory.destroy(!0),Rn.cleanup()}}cachedPageNumber(t){if(!De(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#Hs.get(e)??null}}class zn{#Vs=null;onContinue=null;onError=null;constructor(t){this.#Vs=t}get promise(){return this.#Vs.capability.promise}cancel(t=0){this.#Vs.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Vs.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Vs;return t.form||t.canvas&&e?.size>0}}class Hn{#Gs=null;static#qs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:n,annotationCanvasMap:s,operatorList:r,pageIndex:a,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:c=!1,pageColors:d=null,enableHWA:u=!1,operationsFilter:p=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=n,this.annotationCanvasMap=s,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=a,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=c,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new zn(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvas,this._canvasContext=e.canvas?null:e.canvasContext,this._enableHWA=u,this._dependencyTracker=e.dependencyTracker,this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Hn.#qs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");Hn.#qs.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{viewport:i,transform:n,background:s,dependencyTracker:r}=this.params,a=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new Zi(a,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,r),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:s}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#Gs&&(window.cancelAnimationFrame(this.#Gs),this.#Gs=null),Hn.#qs.delete(this._canvas),t||=new Nt(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}operatorListChanged(){this.graphicsReady?(this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Gs=window.requestAnimationFrame(()=>{this.#Gs=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),Hn.#qs.delete(this._canvas),this.callback())))}}class $n{#Xs=null;#Ks=null;#Ys;#Js=null;#Qs=!1;#Zs=!1;#r=null;#tr;#er=null;#b=null;static#ir=null;static get _keyboardManager(){return pt(this,"_keyboardManager",new de([[["Escape","mac+Escape"],$n.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],$n.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],$n.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],$n.prototype._moveToPrevious],[["Home","mac+Home"],$n.prototype._moveToBeginning],[["End","mac+End"],$n.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#Zs=!1,this.#r=t):this.#Zs=!0,this.#b=t?._uiManager||e,this.#tr=this.#b._eventBus,this.#Ys=t?.color?.toUpperCase()||this.#b?.highlightColors.values().next().value||"#FFFF98",$n.#ir||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Xs=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.ariaHasPopup="true",this.#r&&(t.ariaControls=`${this.#r.id}_colorpicker_dropdown`);const e=this.#b._signal;t.addEventListener("click",this.#nr.bind(this),{signal:e}),t.addEventListener("keydown",this.#sr.bind(this),{signal:e});const i=this.#Ks=document.createElement("span");return i.className="swatch",i.ariaHidden="true",i.style.backgroundColor=this.#Ys,t.append(i),t}renderMainDropdown(){const t=this.#Js=this.#rr();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#rr(){const t=document.createElement("div"),e=this.#b._signal;t.addEventListener("contextmenu",$t,{signal:e}),t.className="dropdown",t.role="listbox",t.ariaMultiSelectable="false",t.ariaOrientation="vertical",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#r&&(t.id=`${this.#r.id}_colorpicker_dropdown`);for(const[i,n]of this.#b.highlightColors){const s=document.createElement("button");s.tabIndex="0",s.role="option",s.setAttribute("data-color",n),s.title=i,s.setAttribute("data-l10n-id",$n.#ir[i]);const r=document.createElement("span");s.append(r),r.className="swatch",r.style.backgroundColor=n,s.ariaSelected=n===this.#Ys,s.addEventListener("click",this.#ar.bind(this,n),{signal:e}),t.append(s)}return t.addEventListener("keydown",this.#sr.bind(this),{signal:e}),t}#ar(t,e){e.stopPropagation(),this.#tr.dispatch("switchannotationeditorparams",{source:this,type:O.HIGHLIGHT_COLOR,value:t}),this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#Xs)return void this.#nr(t);const e=t.target.getAttribute("data-color");e&&this.#ar(e,t)}_moveToNext(t){this.#or?t.target!==this.#Xs?t.target.nextSibling?.focus():this.#Js.firstChild?.focus():this.#nr(t)}_moveToPrevious(t){t.target!==this.#Js?.firstChild&&t.target!==this.#Xs?(this.#or||this.#nr(t),t.target.previousSibling?.focus()):this.#or&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#or?this.#Js.firstChild?.focus():this.#nr(t)}_moveToEnd(t){this.#or?this.#Js.lastChild?.focus():this.#nr(t)}#sr(t){$n._keyboardManager.exec(this,t)}#nr(t){if(this.#or)return void this.hideDropdown();if(this.#Qs=0===t.detail,this.#er||(this.#er=new AbortController,window.addEventListener("pointerdown",this.#u.bind(this),{signal:this.#b.combinedSignal(this.#er)})),this.#Xs.ariaExpanded="true",this.#Js)return void this.#Js.classList.remove("hidden");const e=this.#Js=this.#rr();this.#Xs.append(e)}#u(t){this.#Js?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#Js?.classList.add("hidden"),this.#Xs.ariaExpanded="false",this.#er?.abort(),this.#er=null}get#or(){return this.#Js&&!this.#Js.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#Zs||(this.#or?(this.hideDropdown(),this.#Xs.focus({preventScroll:!0,focusVisible:this.#Qs})):this.#r?.unselect())}updateColor(t){if(this.#Ks&&(this.#Ks.style.backgroundColor=t),!this.#Js)return;const e=this.#b.highlightColors.values();for(const i of this.#Js.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#Xs?.remove(),this.#Xs=null,this.#Ks=null,this.#Js?.remove(),this.#Js=null}}class Wn{#lr=null;#r=null;#b=null;static#ir=null;constructor(t){this.#r=t,this.#b=t._uiManager,Wn.#ir||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#lr)return this.#lr;const{editorType:t,colorType:e,colorValue:i}=this.#r,n=this.#lr=document.createElement("input");return n.type="color",n.value=i||"#000000",n.className="basicColorPicker",n.tabIndex=0,n.setAttribute("data-l10n-id",Wn.#ir[t]),n.addEventListener("input",()=>{this.#b.updateParams(e,n.value)},{signal:this.#b._signal}),n}update(t){this.#lr&&(this.#lr.value=t)}destroy(){this.#lr?.remove(),this.#lr=null}hideDropdown(){}}function Vn(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function Gn(t){return Math.max(0,Math.min(255,255*t))}class qn{static CMYK_G([t,e,i,n]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+n)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=Gn(t),t,t]}static G_HTML([t]){const e=Vn(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(Gn)}static RGB_HTML(t){return`#${t.map(Vn).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,n]){return["RGB",1-Math.min(1,t+n),1-Math.min(1,i+n),1-Math.min(1,e+n)]}static CMYK_rgb([t,e,i,n]){return[Gn(1-Math.min(1,t+n)),Gn(1-Math.min(1,i+n)),Gn(1-Math.min(1,e+n))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const n=1-t,s=1-e,r=1-i;return["CMYK",n,s,r,Math.min(n,s,r)]}}class Xn{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const n=this._createSVG("svg:svg");return n.setAttribute("version","1.1"),i||(n.setAttribute("width",`${t}px`),n.setAttribute("height",`${e}px`)),n.setAttribute("preserveAspectRatio","none"),n.setAttribute("viewBox",`0 0 ${t} ${e}`),n}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){ht("Abstract method `_createSVG` called.")}}class Kn extends Xn{_createSVG(t){return document.createElementNS(Lt,t)}}const Yn=new WeakSet,Jn=60*(new Date).getTimezoneOffset()*1e3;class Qn{static create(t){switch(t.data.annotationType){case V.LINK:return new es(t);case V.TEXT:return new is(t);case V.WIDGET:switch(t.data.fieldType){case"Tx":return new ss(t);case"Btn":return t.data.radioButton?new os(t):t.data.checkBox?new as(t):new ls(t);case"Ch":return new hs(t);case"Sig":return new rs(t)}return new ns(t);case V.POPUP:return new cs(t);case V.FREETEXT:return new us(t);case V.LINE:return new ps(t);case V.SQUARE:return new gs(t);case V.CIRCLE:return new ms(t);case V.POLYLINE:return new fs(t);case V.CARET:return new vs(t);case V.INK:return new ys(t);case V.POLYGON:return new bs(t);case V.HIGHLIGHT:return new ws(t);case V.UNDERLINE:return new xs(t);case V.SQUIGGLY:return new As(t);case V.STRIKEOUT:return new _s(t);case V.STAMP:return new Ss(t);case V.FILEATTACHMENT:return new Cs(t);default:return new Zn(t)}}}class Zn{#hr=null;#cr=!1;#dr=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:n=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableComment=t.enableComment,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(i)),n&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Zn._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:i,rect:n}=this.data;let s=-1/0,r=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)e[t+1]>r?(r=e[t+1],s=e[t+2]):e[t+1]===r&&(s=Math.max(s,e[t+2]));return[s,r]}if(i?.length>=1){for(const t of i)for(let e=0,i=t.length;e<i;e+=2)t[e+1]>r?(r=t[e+1],s=t[e]):t[e+1]===r&&(s=Math.max(s,t[e]));if(s!==1/0)return[s,r]}return n?[n[2],n[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:r}}}=this.parent;return t[1]=e[3]-t[1]+e[1],t[0]=100*(t[0]-s)/i,t[1]=100*(t[1]-r)/n,t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${B}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,i={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:i})||this.annotationStorage.setValue(`${B}${e.id}`,{id:e.id,annotationType:e.annotationType,pageIndex:this.parent.page._pageIndex,popup:i,popupRef:e.popupRef,modificationDate:new Date}),t||this.removePopup()}removePopup(){(this.#dr?.popup||this.popup)?.remove(),this.#dr=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#hr||={rect:this.data.rect.slice(0)});const{rect:e,popup:i}=t;e&&this.#ur(e);let n=this.#dr?.popup||this.popup;!n&&i?.text&&(this._createPopup(i),n=this.#dr.popup),n&&(n.updateEdited(t),i?.deleted&&(n.remove(),this.#dr=null,this.popup=null))}resetEdited(){this.#hr&&(this.#ur(this.#hr.rect),this.#dr?.popup.resetEdited(),this.#hr=null)}#ur(t){const{container:{style:e},data:{rect:i,rotation:n},parent:{viewport:{rawDims:{pageWidth:s,pageHeight:r,pageX:a,pageY:o}}}}=this;i?.splice(0,4,...t),e.left=100*(t[0]-a)/s+"%",e.top=100*(r-t[3]+o)/r+"%",0===n?(e.width=100*(t[2]-t[0])/s+"%",e.height=100*(t[3]-t[1])/r+"%"):this.setRotation(n)}_createContainer(t){const{data:e,parent:{page:i,viewport:n}}=this,s=document.createElement("section");s.setAttribute("data-annotation-id",e.id),this instanceof ns||this instanceof es||(s.tabIndex=0);const{style:r}=s;if(r.zIndex=this.parent.zIndex,this.parent.zIndex+=2,e.alternativeText&&(s.title=e.alternativeText),e.noRotate&&s.classList.add("norotate"),!e.rect||this instanceof cs){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,s),s}const{width:a,height:o}=this;if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;r.borderRadius=e}else if(this instanceof os){const t=`calc(${a}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;r.borderRadius=t}switch(e.borderStyle.style){case G:r.borderStyle="solid";break;case q:r.borderStyle="dashed";break;case X:lt("Unimplemented border style: beveled");break;case K:lt("Unimplemented border style: inset");break;case Y:r.borderBottomStyle="solid"}const n=e.borderColor||null;n?(this.#cr=!0,r.borderColor=Ct.makeHexColor(0|n[0],0|n[1],0|n[2])):r.borderWidth=0}const l=Ct.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:c,pageX:d,pageY:u}=n.rawDims;r.left=100*(l[0]-d)/h+"%",r.top=100*(l[1]-u)/c+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(r.width=100*a/h+"%",r.height=100*o/c+"%"):this.setRotation(p,s),s}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:n}=this.parent.viewport.rawDims;let{width:s,height:r}=this;t%180!=0&&([s,r]=[r,s]),e.style.width=100*s/i+"%",e.style.height=100*r/n+"%",e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const n=i.detail[t],s=n[0],r=n.slice(1);i.target.style[e]=qn[`${s}_HTML`](r),this.annotationStorage.setValue(this.data.id,{[e]:qn[`${s}_rgb`](r)})};return pt(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const n of Object.keys(e.detail)){const s=t[n]||i[n];s?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[n,s]of Object.entries(e)){const r=i[n];if(r){r({detail:{[n]:s},target:t}),delete e[n]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,n,s]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[r,a,o,l]=t.subarray(2,6);if(n===r&&s===a&&e===o&&i===l)return}const{style:r}=this.container;let a;if(this.#cr){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0,a=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${t}" stroke-width="${e}">`],this.container.classList.add("hasBorder")}const o=n-e,l=s-i,{svgFactory:h}=this,c=h.createElement("svg");c.classList.add("quadrilateralsContainer"),c.setAttribute("width",0),c.setAttribute("height",0),c.role="none";const d=h.createElement("defs");c.append(d);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),d.append(u);for(let i=2,n=t.length;i<n;i+=8){const n=t[i],r=t[i+1],c=t[i+2],d=t[i+3],p=h.createElement("rect"),g=(c-e)/o,m=(s-r)/l,f=(n-c)/o,b=(r-d)/l;p.setAttribute("x",g),p.setAttribute("y",m),p.setAttribute("width",f),p.setAttribute("height",b),u.append(p),a?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}this.#cr&&(a.push("</g></svg>')"),r.backgroundImage=a.join("")),this.container.append(c),this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:e}=this;let i,n;t?(i={str:t.text},n=t.date):(i=e.contentsObj,n=e.modificationDate);const s=this.#dr=new cs({data:{color:e.color,titleObj:e.titleObj,modificationDate:n,contentsObj:i,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]});this.parent._commentManager||this.parent.div.append(s.render())}get hasPopupElement(){return!!(this.#dr||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#dr}render(){ht("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const n=this._fieldObjects[t];if(n)for(const{page:t,id:s,exportValues:r}of n){if(-1===t)continue;if(s===e)continue;const n="string"==typeof r?r:null,a=document.querySelector(`[data-element-id="${s}"]`);!a||Yn.has(a)?i.push({id:s,exportValue:n,domElement:a}):lt(`_getElementsByName - element not allowed: ${s}`)}return i}for(const n of document.getElementsByName(t)){const{exportValue:t}=n,s=n.getAttribute("data-element-id");s!==e&&(Yn.has(n)&&i.push({id:s,exportValue:t,domElement:n}))}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class ts extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.editor=t.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){const{editor:t}=this;t.hasComment&&(this._createPopup(t.comment),this.extraPopupElement.popup.renderCommentButton())}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(t){this.editor.comment=t,t||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.container.remove(),this.container=null,this.removePopup()}}class es extends Zn{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let n=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),n=!0):t.action?(this._bindNamedAction(i,t.action,t.overlaidText),n=!0):t.attachment?(this.#pr(i,t.attachment,t.overlaidText,t.attachmentDest),n=!0):t.setOCGState?(this.#gr(i,t.setOCGState,t.overlaidText),n=!0):t.dest?(this._bindLink(i,t.dest,t.overlaidText),n=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),n=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),n=!0):this.isTooltipOnly&&!n&&(this._bindLink(i,""),n=!0)),this.container.classList.add("linkAnnotation"),n&&this.container.append(i),this.container}#mr(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,i=""){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#mr(),i&&(t.title=i)}_bindNamedAction(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),i&&(t.title=i),this.#mr()}#pr(t,e,i="",n=null){t.href=this.linkService.getAnchorUrl(""),e.description?t.title=e.description:i&&(t.title=i),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,n),!1),this.#mr()}#gr(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),i&&(t.title=i),this.#mr()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(e.actions)){const s=i.get(n);s&&(t[s]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:n}}),!1))}e.overlaidText&&(t.title=e.overlaidText),t.onclick||(t.onclick=()=>!1),this.#mr()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#mr(),!this._fieldObjects)return lt('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:n,include:s}=e,r=[];if(0!==t.length||0!==n.length){const e=new Set(n);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===s&&r.push(i)}else for(const t of Object.values(this._fieldObjects))r.push(...t);const a=this.annotationStorage,o=[];for(const t of r){const{id:e}=t;switch(o.push(e),t.type){case"text":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;a.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Yn.has(i)?i.dispatchEvent(new Event("resetform")):lt(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class is extends Zn{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class ns extends Zn{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return _t.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,n,s){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(i,t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t)}})})}_setEventListeners(t,e,i,n){for(const[s,r]of i)("Action"===r||this.data.actions?.[r])&&("Focus"!==r&&"Blur"!==r||(e||={focused:!1}),this._setEventListener(t,e,s,r,n),"Focus"!==r||this.data.actions?.Blur?"Blur"!==r||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Ct.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,n=this.data.defaultAppearanceData.fontSize||9,s=t.style;let r;const a=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(C*n))||1);r=Math.min(n,a(e/C))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(n,a(t/C))}s.fontSize=`calc(${r}px * var(--total-scale-factor))`,s.color=Ct.makeHexColor(i[0],i[1],i[2]),null!==this.data.textAlignment&&(s.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class ss extends ns{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,n){const s=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=i),s.setValue(r.id,{[n]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const n=t.getValue(e,{value:this.data.fieldValue});let s=n.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&s.length>r&&(s=s.slice(0,r));let a=n.formattedValue||this.data.textContent?.join("\n")||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const o={userValue:s,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(i=document.createElement("textarea"),i.textContent=a??s,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type=this.data.password?"password":"text",i.setAttribute("value",a??s),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),Yn.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=0;const{datetimeFormat:l,datetimeType:h,timeStep:c}=this.data,d=!!h&&this.enableScripting;l&&(i.title=l),this._setRequired(i,this.data.required),r&&(i.maxLength=r),i.addEventListener("input",n=>{t.setValue(e,{value:n.target.value}),this.setPropertyOnSiblings(i,"value",n.target.value,"value"),o.formattedValue=null}),i.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null});let u=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",t=>{if(o.focused)return;const{target:e}=t;if(d&&(e.type=h,c&&(e.step=c)),o.userValue){const t=o.userValue;if(d)if("time"===h){const i=new Date(t),n=[i.getHours(),i.getMinutes(),i.getSeconds()];e.value=n.map(t=>t.toString().padStart(2,"0")).join(":")}else e.value=new Date(t-Jn).toISOString().split("date"===h?"T":".",1)[0];else e.value=t}o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)}),i.addEventListener("updatefromsandbox",i=>{this.showElementAndHideCanvas(i.target);const n={value(i){o.userValue=i.detail.value??"",d||t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:n}=i.detail;o.formattedValue=n,null!=n&&i.target!==document.activeElement&&(i.target.value=n);const s={formattedValue:n};d&&(s.value=n),t.setValue(e,s)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:n}=i.detail,{target:s}=i;if(0===n)return void s.removeAttribute("maxLength");s.setAttribute("maxLength",n);let r=o.userValue;!r||r.length<=n||(r=r.slice(0,n),s.value=o.userValue=r,t.setValue(e,{value:r}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,willCommit:!0,commitKey:1,selStart:s.selectionStart,selEnd:s.selectionEnd}}))}};this._dispatchEventFromSandbox(n,i)}),i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:n}=t.target;o.lastCommittedValue!==n&&(o.lastCommittedValue=n,o.userValue=n,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))});const n=u;u=null,i.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{target:i}=t;let{value:s}=i;if(d){if(s&&"time"===h){const t=s.split(":").map(t=>parseInt(t,10));s=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf(),i.step=""}else s.includes("T")||(s=`${s}T00:00`),s=new Date(s).valueOf();i.type="text"}o.userValue=s,o.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),n(t)}),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;const{data:i,target:n}=t,{value:s,selectionStart:r,selectionEnd:a}=n;let l=r,h=a;switch(t.inputType){case"deleteWordBackward":{const t=s.substring(0,r).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=s.substring(r).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":r===a&&(l-=1);break;case"deleteContentForward":r===a&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}if(u&&i.addEventListener("blur",u),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/r;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--total-scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class rs extends ns{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class as extends ns{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof n&&(n="Off"!==n,t.setValue(i,{value:n})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const s=document.createElement("input");return Yn.add(s),s.setAttribute("data-element-id",i),s.disabled=e.readOnly,this._setRequired(s,this.data.required),s.type="checkbox",s.name=e.fieldName,n&&s.setAttribute("checked",!0),s.setAttribute("exportValue",e.exportValue),s.tabIndex=0,s.addEventListener("change",n=>{const{name:s,checked:r}=n.target;for(const n of this._getElementsByName(s,i)){const i=r&&n.exportValue===e.exportValue;n.domElement&&(n.domElement.checked=i),t.setValue(n.id,{value:i})}t.setValue(i,{value:r})}),s.addEventListener("resetform",t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}),this.enableScripting&&this.hasJSActions&&(s.addEventListener("updatefromsandbox",e=>{const n={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(n,e)}),this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class os extends ns{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof n&&(n=n!==e.buttonValue,t.setValue(i,{value:n})),n)for(const n of this._getElementsByName(e.fieldName,i))t.setValue(n.id,{value:!1});const s=document.createElement("input");if(Yn.add(s),s.setAttribute("data-element-id",i),s.disabled=e.readOnly,this._setRequired(s,this.data.required),s.type="radio",s.name=e.fieldName,n&&s.setAttribute("checked",!0),s.tabIndex=0,s.addEventListener("change",e=>{const{name:n,checked:s}=e.target;for(const e of this._getElementsByName(n,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:s})}),s.addEventListener("resetform",t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}),this.enableScripting&&this.hasJSActions){const n=e.buttonValue;s.addEventListener("updatefromsandbox",e=>{const s={value:e=>{const s=n===e.detail.value;for(const n of this._getElementsByName(e.target.name)){const e=s&&n.id===i;n.domElement&&(n.domElement.checked=e),t.setValue(n.id,{value:e})}}};this._dispatchEventFromSandbox(s,e)}),this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}return this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class ls extends es{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})),t}}class hs extends ns{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),n=document.createElement("select");Yn.add(n),n.setAttribute("data-element-id",e),n.disabled=this.data.readOnly,this._setRequired(n,this.data.required),n.name=this.data.fieldName,n.tabIndex=0;let s=this.data.combo&&this.data.options.length>0;this.data.combo||(n.size=this.data.options.length,this.data.multiSelect&&(n.multiple=!0)),n.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue;for(const t of n.options)t.selected=t.value===e});for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),s=!1),n.append(e)}let r=null;if(s){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),n.prepend(t),r=()=>{t.remove(),n.removeEventListener("input",r),r=null},n.addEventListener("input",r)}const a=t=>{const e=t?"value":"textContent",{options:i,multiple:s}=n;return s?Array.prototype.filter.call(i,t=>t.selected).map(t=>t[e]):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let o=a(!1);const l=t=>{const e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.textContent,exportValue:t.value}))};return this.enableScripting&&this.hasJSActions?(n.addEventListener("updatefromsandbox",i=>{const s={value(i){r?.();const s=i.detail.value,l=new Set(Array.isArray(s)?s:[s]);for(const t of n.options)t.selected=l.has(t.value);t.setValue(e,{value:a(!0)}),o=a(!1)},multipleSelection(t){n.multiple=!0},remove(i){const s=n.options,r=i.detail.remove;if(s[r].selected=!1,n.remove(r),s.length>0){-1===Array.prototype.findIndex.call(s,t=>t.selected)&&(s[0].selected=!0)}t.setValue(e,{value:a(!0),items:l(i)}),o=a(!1)},clear(i){for(;0!==n.length;)n.remove(0);t.setValue(e,{value:null,items:[]}),o=a(!1)},insert(i){const{index:s,displayValue:r,exportValue:h}=i.detail.insert,c=n.children[s],d=document.createElement("option");d.textContent=r,d.value=h,c?c.before(d):n.append(d),t.setValue(e,{value:a(!0),items:l(i)}),o=a(!1)},items(i){const{items:s}=i.detail;for(;0!==n.length;)n.remove(0);for(const t of s){const{displayValue:e,exportValue:i}=t,s=document.createElement("option");s.textContent=e,s.value=i,n.append(s)}n.options.length>0&&(n.options[0].selected=!0),t.setValue(e,{value:a(!0),items:l(i)}),o=a(!1)},indices(i){const n=new Set(i.detail.indices);for(const t of i.target.options)t.selected=n.has(t.index);t.setValue(e,{value:a(!0)}),o=a(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(s,i)}),n.addEventListener("input",i=>{const n=a(!0),s=a(!1);t.setValue(e,{value:n}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:s,changeEx:n,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(n,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],t=>t.target.value)):n.addEventListener("input",function(i){t.setValue(e,{value:a(!0)})}),this.data.combo&&this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class cs extends Zn{constructor(t){const{data:e,elements:i,parent:n}=t,s=!!n._commentManager;if(super(t,{isRenderable:!s&&Zn._hasPopupData(e)}),this.elements=i,s&&Zn._hasPopupData(e)){const t=this.popup=this.#fr();for(const e of i)e.popup=t}else this.popup=null}#fr(){return new ds({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const e=this.popup=this.#fr(),i=[];for(const t of this.elements)t.popup=e,t.container.ariaHasPopup="dialog",i.push(t.data.id),t.addHighlightArea();return this.container.setAttribute("aria-controls",i.map(t=>`${Dt}${t}`).join(",")),this.container}}class ds{#U=null;#br=this.#sr.bind(this);#vr=this.#yr.bind(this);#wr=this.#xr.bind(this);#Ar=this.#_r.bind(this);#Sr=null;#xt=null;#Cr=null;#Er=null;#Tr=null;#kr=null;#Dr=null;#Mr=!1;#Pr=null;#Ir=null;#k=null;#Rr=null;#Lr=null;#pe=null;#Br=null;#he=null;#Fr=null;#hr=null;#Or=!1;#Nr=null;#Ur=null;constructor({container:t,color:e,elements:i,titleObj:n,modificationDate:s,contentsObj:r,richText:a,parent:o,rect:l,parentRect:h,open:c,commentManager:d=null}){this.#xt=t,this.#Fr=n,this.#Cr=r,this.#he=a,this.#kr=o,this.#Sr=e,this.#Br=l,this.#Dr=h,this.#Tr=i,this.#U=d,this.#Nr=i[0],this.#Er=Vt.toDateObject(s),this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup()),d?this.renderCommentButton():(this.#jr(),this.#xt.hidden=!0,c&&this.#_r())}#jr(){if(this.#Ir)return;this.#Ir=new AbortController;const{signal:t}=this.#Ir;for(const e of this.trigger)e.addEventListener("click",this.#Ar,{signal:t}),e.addEventListener("pointerenter",this.#wr,{signal:t}),e.addEventListener("pointerleave",this.#vr,{signal:t}),e.classList.add("popupTriggerArea");for(const e of this.#Tr)e.container?.addEventListener("keydown",this.#br,{signal:t})}#zr(){const t=this.#Tr.find(t=>t.hasCommentButton);t&&(this.#Lr=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#Rr)return;if(this.#Lr||this.#zr(),!this.#Lr)return;const{signal:t}=this.#Ir=new AbortController,e=!!this.#Nr.extraPopupElement,i=()=>{this.#U.toggleCommentPopup(this,!0,void 0,!e)},n=()=>{this.#U.toggleCommentPopup(this,!1,!0,!e)},s=()=>{this.#U.toggleCommentPopup(this,!1,!1)};if(e){this.#Rr=this.#Nr.container;for(const e of this.trigger)e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.addEventListener("keydown",this.#br,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",n,{signal:t}),e.addEventListener("pointerleave",s,{signal:t}),e.classList.add("popupTriggerArea")}else{const e=this.#Rr=document.createElement("button");e.className="annotationCommentButton";const r=this.#Nr.container;e.style.zIndex=r.style.zIndex+1,e.tabIndex=0,e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#Hr(),this.#$r(),e.addEventListener("keydown",this.#br,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",n,{signal:t}),e.addEventListener("pointerleave",s,{signal:t}),r.after(e)}}#$r(){if(this.#Nr.extraPopupElement&&!this.#Nr.editor)return;this.renderCommentButton();const[t,e]=this.#Lr,{style:i}=this.#Rr;i.left=`calc(${t}%)`,i.top=`calc(${e}% - var(--comment-button-dim))`}#Hr(){this.#Nr.extraPopupElement||(this.renderCommentButton(),this.#Rr.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){const{color:t,opacity:e}=this.#Nr.commentData;return t?this.#kr._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#Rr?.focus()},0)}getData(){const{richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}=this.#Nr.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}}get elementBeforePopup(){return this.#Rr}get comment(){return this.#Ur||=this.#Nr.commentText,this.#Ur}set comment(t){t!==this.comment&&(this.#Nr.commentText=this.#Ur=t)}get parentBoundingClientRect(){return this.#Nr.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){this.#Rr&&(this.#Rr.classList.toggle("selected",t),this.#Rr.ariaExpanded=e)}setSelectedCommentButton(t){this.#Rr.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#pe)return this.#pe;const{x:t,y:e,height:i}=this.#Rr.getBoundingClientRect(),{x:n,y:s,width:r,height:a}=this.#Nr.layer.getBoundingClientRect();return[(t-n)/r,(e+i-s)/a]}set commentPopupPosition(t){this.#pe=t}hasDefaultPopupPosition(){return null===this.#pe}get commentButtonPosition(){return this.#Lr}get commentButtonWidth(){return this.#Rr.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,i]=this.#pe||this.commentButtonPosition.map(t=>t/100),n=this.parentBoundingClientRect,{x:s,y:r,width:a,height:o}=n;this.#U.showDialog(null,this,s+e*a,r+i*o,{...t,parentDimensions:n})}render(){if(this.#Pr)return;const t=this.#Pr=document.createElement("div");if(t.className="popup",this.#Sr){const e=t.style.outlineColor=Ct.makeHexColor(...this.#Sr);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");if(e.className="header",this.#Fr?.str){const t=document.createElement("span");t.className="title",e.append(t),({dir:t.dir,str:t.textContent}=this.#Fr)}if(t.append(e),this.#Er){const t=document.createElement("time");t.className="popupDate",t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#Er.valueOf()})),t.dateTime=this.#Er.toISOString(),e.append(t)}se({html:this.#Wr||this.#Cr.str,dir:this.#Cr?.dir,className:"popupContent"},t),this.#xt.append(t)}get#Wr(){const t=this.#he,e=this.#Cr;return!t?.str||e?.str&&e.str!==t.str?null:this.#he.html||null}get#Vr(){return this.#Wr?.attributes?.style?.fontSize||0}get#Gr(){return this.#Wr?.attributes?.style?.color||null}#qr(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},n={style:{color:this.#Gr,fontSize:this.#Vr?`calc(${this.#Vr}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:n});return i}#sr(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#Mr)&&this.#_r()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#U)return i?(this.remove(),this.#Ur=null):e&&(e.deleted?this.remove():(this.#Hr(),this.#Ur=e.text)),void(t&&(this.#Lr=null,this.#zr(),this.#$r()));i||e?.deleted?this.remove():(this.#jr(),this.#hr||={contentsObj:this.#Cr,richText:this.#he},t&&(this.#k=null),e&&e.text&&(this.#he=this.#qr(e.text),this.#Er=Vt.toDateObject(e.date),this.#Cr=null),this.#Pr?.remove(),this.#Pr=null)}resetEdited(){this.#hr&&(({contentsObj:this.#Cr,richText:this.#he}=this.#hr),this.#hr=null,this.#Pr?.remove(),this.#Pr=null,this.#k=null)}remove(){if(this.#Ir?.abort(),this.#Ir=null,this.#Pr?.remove(),this.#Pr=null,this.#Or=!1,this.#Mr=!1,this.#Rr?.remove(),this.#Rr=null,this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#Xr(){if(null!==this.#k)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:n,pageY:s}}}=this.#kr;let r=!!this.#Dr,a=r?this.#Dr:this.#Br;for(const t of this.#Tr)if(!a||null!==Ct.intersect(t.data.rect,a)){a=t.data.rect,r=!0;break}const o=Ct.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),l=r?a[2]-a[0]+5:0,h=o[0]+l,c=o[1];this.#k=[100*(h-n)/e,100*(c-s)/i];const{style:d}=this.#xt;d.left=`${this.#k[0]}%`,d.top=`${this.#k[1]}%`}#_r(){this.#U?this.#U.toggleCommentPopup(this,!1):(this.#Mr=!this.#Mr,this.#Mr?(this.#xr(),this.#xt.addEventListener("click",this.#Ar),this.#xt.addEventListener("keydown",this.#br)):(this.#yr(),this.#xt.removeEventListener("click",this.#Ar),this.#xt.removeEventListener("keydown",this.#br)))}#xr(){this.#Pr||this.render(),this.isVisible?this.#Mr&&this.#xt.classList.add("focused"):(this.#Xr(),this.#xt.hidden=!1,this.#xt.style.zIndex=parseInt(this.#xt.style.zIndex)+1e3)}#yr(){this.#xt.classList.remove("focused"),!this.#Mr&&this.isVisible&&(this.#xt.hidden=!0,this.#xt.style.zIndex=parseInt(this.#xt.style.zIndex)-1e3)}forceHide(){this.#Or=this.isVisible,this.#Or&&(this.#xt.hidden=!0)}maybeShow(){this.#U||(this.#jr(),this.#Or&&(this.#Pr||this.#xr(),this.#Or=!1,this.#xt.hidden=!1))}get isVisible(){return!this.#U&&!1===this.#xt.hidden}}class us extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=F.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const i=document.createElement("span");i.textContent=e,t.append(i)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class ps extends Zn{#Kr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=this.#Kr=this.svgFactory.createElement("svg:line");return s.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),s.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),s.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),s.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),s.setAttribute("stroke-width",t.borderStyle.width||1),s.setAttribute("stroke","transparent"),s.setAttribute("fill","transparent"),n.append(s),this.container.append(n),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Kr}addHighlightArea(){this.container.classList.add("highlightArea")}}class gs extends Zn{#Yr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,r=this.#Yr=this.svgFactory.createElement("svg:rect");return r.setAttribute("x",s/2),r.setAttribute("y",s/2),r.setAttribute("width",e-s),r.setAttribute("height",i-s),r.setAttribute("stroke-width",s||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),n.append(r),this.container.append(n),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Yr}addHighlightArea(){this.container.classList.add("highlightArea")}}class ms extends Zn{#Jr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,r=this.#Jr=this.svgFactory.createElement("svg:ellipse");return r.setAttribute("cx",e/2),r.setAttribute("cy",i/2),r.setAttribute("rx",e/2-s/2),r.setAttribute("ry",i/2-s/2),r.setAttribute("stroke-width",s||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),n.append(r),this.container.append(n),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Jr}addHighlightArea(){this.container.classList.add("highlightArea")}}class fs extends Zn{#Qr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:i,popupRef:n},width:s,height:r}=this;if(!e)return this.container;const a=this.svgFactory.create(s,r,!0);let o=[];for(let i=0,n=e.length;i<n;i+=2){const n=e[i]-t[0],s=t[3]-e[i+1];o.push(`${n},${s}`)}o=o.join(" ");const l=this.#Qr=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",o),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),a.append(l),this.container.append(a),!n&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Qr}addHighlightArea(){this.container.classList.add("highlightArea")}}class bs extends fs{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class vs extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class ys extends Zn{#Zr=null;#ta=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?F.HIGHLIGHT:F.INK}#ea(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:i,borderStyle:n,popupRef:s}}=this,{transform:r,width:a,height:o}=this.#ea(e,t),l=this.svgFactory.create(a,o,!0),h=this.#Zr=this.svgFactory.createElement("svg:g");l.append(h),h.setAttribute("stroke-width",n.width||1),h.setAttribute("stroke-linecap","round"),h.setAttribute("stroke-linejoin","round"),h.setAttribute("stroke-miterlimit",10),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),h.setAttribute("transform",r);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#ta.push(e),e.setAttribute("points",i[t].join(",")),h.append(e)}return!s&&this.hasPopupData&&this._createPopup(),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:n}=t,s=this.#Zr;if(e>=0&&s.setAttribute("stroke-width",e||1),i)for(let t=0,e=this.#ta.length;t<e;t++)this.#ta[t].setAttribute("points",i[t].join(","));if(n){const{transform:t,width:e,height:i}=this.#ea(this.data.rotation,n);s.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`),s.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#ta}addHighlightArea(){this.container.classList.add("highlightArea")}}class ws extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=F.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){const e=document.createElement("mark");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class xs extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),t){const e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class As extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),t){const e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class _s extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),t){const e=document.createElement("s");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class Ss extends Zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=F.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Cs extends Zn{#ia=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let i;e.hasAppearance||0===e.fillAlpha?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)),i.addEventListener("dblclick",this.#na.bind(this)),this.#ia=i;const{isMac:n}=_t.platform;return t.addEventListener("keydown",t=>{"Enter"===t.key&&(n?t.metaKey:t.ctrlKey)&&this.#na()}),!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#ia}addHighlightArea(){this.container.classList.add("highlightArea")}#na(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Es{#sa=null;#ra=null;#F=null;#aa=new Map;#oa=null;#la=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:n,page:s,viewport:r,structTreeLayer:a,commentManager:o,linkService:l,annotationStorage:h}){this.div=t,this.#sa=e,this.#ra=i,this.#oa=a||null,this.#la=l||null,this.#F=h||new Se,this.page=s,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=n,this._commentManager=o||null}hasEditableAnnotations(){return this.#aa.size>0}async#ha(t,e,i){const n=t.firstChild||t,s=n.id=`${Dt}${e}`,r=await(this.#oa?.getAriaAttributes(s));if(r)for(const[t,e]of r)n.setAttribute(t,e);i?i.at(-1).container.after(t):(this.div.append(t),this.#sa?.moveElementInDOM(this.div,t,n,!1))}async render(t){const{annotations:e}=t,i=this.div;Kt(i,this.viewport);const n=new Map,s={data:null,layer:i,linkService:this.#la,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new Kn,annotationStorage:this.#F,enableComment:!0===t.enableComment,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===V.POPUP;if(e){const e=n.get(t.id);if(!e)continue;s.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;s.data=t;const i=Qn.create(s);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=n.get(t.popupRef);e?e.push(i):n.set(t.popupRef,[i])}const r=i.render();t.hidden&&(r.style.visibility="hidden"),await this.#ha(r,t.id,s.elements),i.extraPopupElement?.popup?.renderCommentButton(),i._isEditable&&(this.#aa.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}this.#ca()}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#la,svgFactory:new Kn,parent:this};for(const i of t){i.borderStyle||=Es._defaultBorderStyle,e.data=i;const t=Qn.create(e);if(!t.isRenderable)continue;const n=t.render();await this.#ha(n,i.id,null)}}update({viewport:t}){const e=this.div;this.viewport=t,Kt(e,{rotation:t.rotation}),this.#ca(),e.hidden=!1}#ca(){if(!this.#ra)return;const t=this.div;for(const[e,i]of this.#ra){const n=t.querySelector(`[data-annotation-id="${e}"]`);if(!n)continue;i.className="annotationContent";const{firstChild:s}=n;s?"CANVAS"===s.nodeName?s.replaceWith(i):s.classList.contains("annotationContent")?s.after(i):s.before(i):n.append(i);const r=this.#aa.get(e);r&&(r._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(e,n.id,i),r._hasNoCanvas=!1):r.canvas=i)}this.#ra.clear()}getEditableAnnotations(){return Array.from(this.#aa.values())}getEditableAnnotation(t){return this.#aa.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:i,rotation:n}=t,s=new ts({data:{id:i,rect:t.getPDFRect(),rotation:n},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#la,annotationStorage:this.#F}),r=s.render();return e.append(r),this.#sa?.moveElementInDOM(e,r,r,!1),s.createOrUpdatePopup(),s}static get _defaultBorderStyle(){return pt(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:G,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const Ts=/\r\n?|\n/g;class ks extends be{#da="";#ua=`${this.id}-editor`;#pa=null;#Vr;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=ks.prototype,e=t=>t.isEmpty(),i=pe.TRANSLATE_SMALL,n=pe.TRANSLATE_BIG;return pt(this,"_keyboardManager",new de([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,n],checker:e}]]))}static _type="freetext";static _editorType=F.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.color=t.color||ks._defaultColor||be._defaultLineColor,this.#Vr=t.fontSize||ks._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert")}static initialize(t,e){be.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case O.FREETEXT_SIZE:ks._defaultFontSize=e;break;case O.FREETEXT_COLOR:ks._defaultColor=e}}updateParams(t,e){switch(t){case O.FREETEXT_SIZE:this.#ga(e);break;case O.FREETEXT_COLOR:this.#Hr(e)}}static get defaultPropertiesToUpdate(){return[[O.FREETEXT_SIZE,ks._defaultFontSize],[O.FREETEXT_COLOR,ks._defaultColor||be._defaultLineColor]]}get propertiesToUpdate(){return[[O.FREETEXT_SIZE,this.#Vr],[O.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new Wn(this),[["colorPicker",this._colorPicker]]}get colorType(){return O.FREETEXT_COLOR}#ga(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#Vr)*this.parentScale),this.#Vr=t,this.#ma()},i=this.#Vr;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:O.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#Hr(t){const e=t=>{this.color=t,this.onUpdatedColor()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:O.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-ks._internalPadding*t,-(ks._internalPadding+this.#Vr)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#pa=new AbortController;const t=this._uiManager.combinedSignal(this.#pa);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return!!super.disableEditMode()&&(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#ua),this._isDraggable=!0,this.#pa?.abort(),this.#pa=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0)}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#fa(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(ks.#ba(i)),e=i);return t.join("\n")}#ma(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,n=e.style.display,s=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=n,e.classList.toggle("hidden",s)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#da,e=this.#da=this.#fa().trimEnd();if(t===e)return;const i=t=>{this.#da=t,t?(this.#va(),this._uiManager.rebuild(this),this.#ma()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#ma()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){ks._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(this._isCopy||this.annotationElementId)&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#ua),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#Vr}px * var(--total-scale-factor))`,i.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:s}=this._initialData;let[r,a]=this.getInitialTranslation();[r,a]=this.pageTranslationToScreen(r,a);const[o,l]=this.pageDimensions,[h,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(s[0]-h)/o,u=e+this.height-(s[1]-c)/l;break;case 90:d=t+(s[0]-h)/o,u=e-(s[1]-c)/l,[r,a]=[a,-r];break;case 180:d=t-this.width+(s[0]-h)/o,u=e-(s[1]-c)/l,[r,a]=[-r,-a];break;case 270:d=t+(s[0]-h-this.height*l)/o,u=e+(s[1]-c-this.width*o)/l,[r,a]=[-a,r]}this.setAt(d*i,u*n,r,a)}else this._moveAfterPaste(t,e);this.#va(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#ba(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Ts,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const n=ks.#ya(e.getData("text")||"").replaceAll(Ts,"\n");if(!n)return;const s=window.getSelection();if(!s.rangeCount)return;this.editorDiv.normalize(),s.deleteFromDocument();const r=s.getRangeAt(0);if(!n.includes("\n"))return r.insertNode(document.createTextNode(n)),this.editorDiv.normalize(),void s.collapseToStart();const{startContainer:a,startOffset:o}=r,l=[],h=[];if(a.nodeType===Node.TEXT_NODE){const t=a.parentElement;if(h.push(a.nodeValue.slice(o).replaceAll(Ts,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(ks.#ba(i)):e=h}l.push(a.nodeValue.slice(0,o).replaceAll(Ts,""))}else if(a===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(ks.#ba(i))}this.#da=`${l.join("\n")}${n}${h.join("\n")}`,this.#va();const c=new Range;let d=Math.sumPrecise(l.map(t=>t.length));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(d<=e){c.setStart(t,d),c.setEnd(t,d);break}d-=e}s.removeAllRanges(),s.addRange(c)}#va(){if(this.editorDiv.replaceChildren(),this.#da)for(const t of this.#da.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#wa(){return this.#da.replaceAll(" "," ")}static#ya(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=ks._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,i){let n=null;if(t instanceof us){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:s,rotation:r,id:a,popupRef:o,richText:l,contentsObj:h,creationDate:c,modificationDate:d},textContent:u,textPosition:p,parent:{page:{pageNumber:g}}}=t;if(!u||0===u.length)return null;n=t={annotationType:F.FREETEXT,color:Array.from(i),fontSize:e,value:u.join("\n"),position:p,pageIndex:g-1,rect:s.slice(0),rotation:r,annotationElementId:a,id:a,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:c,modificationDate:d}}const s=await super.deserialize(t,e,i);return s.#Vr=t.fontSize,s.color=Ct.makeHexColor(...t.color),s.#da=ks.#ya(t.value),s._initialData=n,t.comment&&s.setCommentData(t),s}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=be._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:e,fontSize:this.#Vr,value:this.#wa()});return this.addComment(i),t?(i.isCopy=!0,i):this.annotationElementId&&!this.#xa(i)?null:(i.id=this.annotationElementId,i)}#xa(t){const{value:e,fontSize:i,color:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==n[e])||t.pageIndex!==s}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:i}=e;i.fontSize=`calc(${this.#Vr}px * var(--total-scale-factor))`,i.color=this.color,e.replaceChildren();for(const t of this.#da.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#da}}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class Ds{static PRECISION=1e-4;toSVGPath(){ht("Abstract method `toSVGPath` must be implemented.")}get box(){ht("Abstract getter `box` must be implemented.")}serialize(t,e){ht("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,n,s,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a]*n,r[a+1]=i+t[a+1]*s;return r}static _rescaleAndSwap(t,e,i,n,s,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)r[a]=e+t[a+1]*n,r[a+1]=i+t[a]*s;return r}static _translate(t,e,i,n){n||=new Float32Array(t.length);for(let s=0,r=t.length;s<r;s+=2)n[s]=e+t[s],n[s+1]=i+t[s+1];return n}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,n,s){switch(s){case 90:return[1-e/i,t/n];case 180:return[1-t/i,1-e/n];case 270:return[e/i,1-t/n];default:return[t/i,e/n]}}static _normalizePagePoint(t,e,i){switch(i){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,i,n,s,r){return[(t+5*i)/6,(e+5*n)/6,(5*i+s)/6,(5*n+r)/6,(i+s)/2,(n+r)/2]}}class Ms{#Aa;#_a=[];#Sa;#Ca;#Ea=[];#Ta=new Float32Array(18);#ka;#Da;#Ma;#Pa;#Ia;#Ra;#La=[];static#Ba=8;static#Fa=2;static#Oa=Ms.#Ba+Ms.#Fa;constructor({x:t,y:e},i,n,s,r,a=0){this.#Aa=i,this.#Ra=s*n,this.#Ca=r,this.#Ta.set([NaN,NaN,NaN,NaN,t,e],6),this.#Sa=a,this.#Pa=Ms.#Ba*n,this.#Ma=Ms.#Oa*n,this.#Ia=n,this.#La.push(t,e)}isEmpty(){return isNaN(this.#Ta[8])}#Na(){const t=this.#Ta.subarray(4,6),e=this.#Ta.subarray(16,18),[i,n,s,r]=this.#Aa;return[(this.#ka+(t[0]-e[0])/2-i)/s,(this.#Da+(t[1]-e[1])/2-n)/r,(this.#ka+(e[0]-t[0])/2-i)/s,(this.#Da+(e[1]-t[1])/2-n)/r]}add({x:t,y:e}){this.#ka=t,this.#Da=e;const[i,n,s,r]=this.#Aa;let[a,o,l,h]=this.#Ta.subarray(8,12);const c=t-l,d=e-h,u=Math.hypot(c,d);if(u<this.#Ma)return!1;const p=u-this.#Pa,g=p/u,m=g*c,f=g*d;let b=a,v=o;a=l,o=h,l+=m,h+=f,this.#La?.push(t,e);const y=m/p,w=-f/p*this.#Ra,x=y*this.#Ra;if(this.#Ta.set(this.#Ta.subarray(2,8),0),this.#Ta.set([l+w,h+x],4),this.#Ta.set(this.#Ta.subarray(14,18),12),this.#Ta.set([l-w,h-x],16),isNaN(this.#Ta[6]))return 0===this.#Ea.length&&(this.#Ta.set([a+w,o+x],2),this.#Ea.push(NaN,NaN,NaN,NaN,(a+w-i)/s,(o+x-n)/r),this.#Ta.set([a-w,o-x],14),this.#_a.push(NaN,NaN,NaN,NaN,(a-w-i)/s,(o-x-n)/r)),this.#Ta.set([b,v,a,o,l,h],6),!this.isEmpty();this.#Ta.set([b,v,a,o,l,h],6);return Math.abs(Math.atan2(v-o,b-a)-Math.atan2(f,m))<Math.PI/2?([a,o,l,h]=this.#Ta.subarray(2,6),this.#Ea.push(NaN,NaN,NaN,NaN,((a+l)/2-i)/s,((o+h)/2-n)/r),[a,o,b,v]=this.#Ta.subarray(14,18),this.#_a.push(NaN,NaN,NaN,NaN,((b+a)/2-i)/s,((v+o)/2-n)/r),!0):([b,v,a,o,l,h]=this.#Ta.subarray(0,6),this.#Ea.push(((b+5*a)/6-i)/s,((v+5*o)/6-n)/r,((5*a+l)/6-i)/s,((5*o+h)/6-n)/r,((a+l)/2-i)/s,((o+h)/2-n)/r),[l,h,a,o,b,v]=this.#Ta.subarray(12,18),this.#_a.push(((b+5*a)/6-i)/s,((v+5*o)/6-n)/r,((5*a+l)/6-i)/s,((5*o+h)/6-n)/r,((a+l)/2-i)/s,((o+h)/2-n)/r),!0)}toSVGPath(){if(this.isEmpty())return"";const t=this.#Ea,e=this.#_a;if(isNaN(this.#Ta[6])&&!this.isEmpty())return this.#Ua();const i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#ja(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return this.#za(i),i.join(" ")}#Ua(){const[t,e,i,n]=this.#Aa,[s,r,a,o]=this.#Na();return`M${(this.#Ta[2]-t)/i} ${(this.#Ta[3]-e)/n} L${(this.#Ta[4]-t)/i} ${(this.#Ta[5]-e)/n} L${s} ${r} L${a} ${o} L${(this.#Ta[16]-t)/i} ${(this.#Ta[17]-e)/n} L${(this.#Ta[14]-t)/i} ${(this.#Ta[15]-e)/n} Z`}#za(t){const e=this.#_a;t.push(`L${e[4]} ${e[5]} Z`)}#ja(t){const[e,i,n,s]=this.#Aa,r=this.#Ta.subarray(4,6),a=this.#Ta.subarray(16,18),[o,l,h,c]=this.#Na();t.push(`L${(r[0]-e)/n} ${(r[1]-i)/s} L${o} ${l} L${h} ${c} L${(a[0]-e)/n} ${(a[1]-i)/s}`)}newFreeDrawOutline(t,e,i,n,s,r){return new Ps(t,e,i,n,s,r)}getOutlines(){const t=this.#Ea,e=this.#_a,i=this.#Ta,[n,s,r,a]=this.#Aa,o=new Float32Array((this.#La?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2)o[t]=(this.#La[t]-n)/r,o[t+1]=(this.#La[t+1]-s)/a;if(o[o.length-2]=(this.#ka-n)/r,o[o.length-1]=(this.#Da-s)/a,isNaN(i[6])&&!this.isEmpty())return this.#Ha(o);const l=new Float32Array(this.#Ea.length+24+this.#_a.length);let h=t.length;for(let e=0;e<h;e+=2)isNaN(t[e])?l[e]=l[e+1]=NaN:(l[e]=t[e],l[e+1]=t[e+1]);h=this.#$a(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(l[h]=l[h+1]=NaN,h+=2):(l[h]=e[t+i],l[h+1]=e[t+i+1],h+=2);return this.#Wa(l,h),this.newFreeDrawOutline(l,o,this.#Aa,this.#Ia,this.#Sa,this.#Ca)}#Ha(t){const e=this.#Ta,[i,n,s,r]=this.#Aa,[a,o,l,h]=this.#Na(),c=new Float32Array(36);return c.set([NaN,NaN,NaN,NaN,(e[2]-i)/s,(e[3]-n)/r,NaN,NaN,NaN,NaN,(e[4]-i)/s,(e[5]-n)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/s,(e[17]-n)/r,NaN,NaN,NaN,NaN,(e[14]-i)/s,(e[15]-n)/r],0),this.newFreeDrawOutline(c,t,this.#Aa,this.#Ia,this.#Sa,this.#Ca)}#Wa(t,e){const i=this.#_a;return t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e),e+6}#$a(t,e){const i=this.#Ta.subarray(4,6),n=this.#Ta.subarray(16,18),[s,r,a,o]=this.#Aa,[l,h,c,d]=this.#Na();return t.set([NaN,NaN,NaN,NaN,(i[0]-s)/a,(i[1]-r)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(n[0]-s)/a,(n[1]-r)/o],e),e+24}}class Ps extends Ds{#Aa;#Va=new Float32Array(4);#Sa;#Ca;#La;#Ia;#Ga;constructor(t,e,i,n,s,r){super(),this.#Ga=t,this.#La=e,this.#Aa=i,this.#Ia=n,this.#Sa=s,this.#Ca=r,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#qa(r);const[a,o,l,h]=this.#Va;for(let e=0,i=t.length;e<i;e+=2)t[e]=(t[e]-a)/l,t[e+1]=(t[e+1]-o)/h;for(let t=0,i=e.length;t<i;t+=2)e[t]=(e[t]-a)/l,e[t+1]=(e[t+1]-o)/h}toSVGPath(){const t=[`M${this.#Ga[4]} ${this.#Ga[5]}`];for(let e=6,i=this.#Ga.length;e<i;e+=6)isNaN(this.#Ga[e])?t.push(`L${this.#Ga[e+4]} ${this.#Ga[e+5]}`):t.push(`C${this.#Ga[e]} ${this.#Ga[e+1]} ${this.#Ga[e+2]} ${this.#Ga[e+3]} ${this.#Ga[e+4]} ${this.#Ga[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,i,n],s){const r=i-t,a=n-e;let o,l;switch(s){case 0:o=Ds._rescale(this.#Ga,t,n,r,-a),l=Ds._rescale(this.#La,t,n,r,-a);break;case 90:o=Ds._rescaleAndSwap(this.#Ga,t,e,r,a),l=Ds._rescaleAndSwap(this.#La,t,e,r,a);break;case 180:o=Ds._rescale(this.#Ga,i,e,-r,a),l=Ds._rescale(this.#La,i,e,-r,a);break;case 270:o=Ds._rescaleAndSwap(this.#Ga,i,n,-r,-a),l=Ds._rescaleAndSwap(this.#La,i,n,-r,-a)}return{outline:Array.from(o),points:[Array.from(l)]}}#qa(t){const e=this.#Ga;let i=e[4],n=e[5];const s=[i,n,i,n];let r=i,a=n,o=i,l=n;const h=t?Math.max:Math.min,c=new Float32Array(4);for(let t=6,d=e.length;t<d;t+=6){const d=e[t+4],u=e[t+5];isNaN(e[t])?(Ct.pointBoundingBox(d,u,s),a>u?(r=d,a=u):a===u&&(r=h(r,d)),l<u?(o=d,l=u):l===u&&(o=h(o,d))):(c[0]=c[1]=1/0,c[2]=c[3]=-1/0,Ct.bezierBoundingBox(i,n,...e.slice(t,t+6),c),Ct.rectBoundingBox(c[0],c[1],c[2],c[3],s),a>c[1]?(r=c[0],a=c[1]):a===c[1]&&(r=h(r,c[0])),l<c[3]?(o=c[2],l=c[3]):l===c[3]&&(o=h(o,c[2]))),i=d,n=u}const d=this.#Va;d[0]=s[0]-this.#Sa,d[1]=s[1]-this.#Sa,d[2]=s[2]-s[0]+2*this.#Sa,d[3]=s[3]-s[1]+2*this.#Sa,this.firstPoint=[r,a],this.lastPoint=[o,l]}get box(){return this.#Va}newOutliner(t,e,i,n,s,r=0){return new Ms(t,e,i,n,s,r)}getNewOutline(t,e){const[i,n,s,r]=this.#Va,[a,o,l,h]=this.#Aa,c=s*l,d=r*h,u=i*l+a,p=n*h+o,g=this.newOutliner({x:this.#La[0]*c+u,y:this.#La[1]*d+p},this.#Aa,this.#Ia,t,this.#Ca,e??this.#Sa);for(let t=2;t<this.#La.length;t+=2)g.add({x:this.#La[t]*c+u,y:this.#La[t+1]*d+p});return g.getOutlines()}}class Is{#Aa;#Xa;#Ka;#Ya=[];#Ja=[];constructor(t,e=0,i=0,n=!0){const s=[1/0,1/0,-1/0,-1/0],r=10**-4;for(const{x:i,y:n,width:a,height:o}of t){const t=Math.floor((i-e)/r)*r,l=Math.ceil((i+a+e)/r)*r,h=Math.floor((n-e)/r)*r,c=Math.ceil((n+o+e)/r)*r,d=[t,h,c,!0],u=[l,h,c,!1];this.#Ya.push(d,u),Ct.rectBoundingBox(t,h,l,c,s)}const a=s[2]-s[0]+2*i,o=s[3]-s[1]+2*i,l=s[0]-i,h=s[1]-i;let c=n?-1/0:1/0,d=1/0;const u=this.#Ya.at(n?-1:-2),p=[u[0],u[2]];for(const t of this.#Ya){const[e,i,s,r]=t;!r&&n?i<d?(d=i,c=e):i===d&&(c=Math.max(c,e)):r&&!n&&(i<d?(d=i,c=e):i===d&&(c=Math.min(c,e))),t[0]=(e-l)/a,t[1]=(i-h)/o,t[2]=(s-h)/o}this.#Aa=new Float32Array([l,h,a,o]),this.#Xa=[c,d],this.#Ka=p}getOutlines(){this.#Ya.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#Ya)e[3]?(t.push(...this.#Qa(e)),this.#Za(e)):(this.#to(e),t.push(...this.#Qa(e)));return this.#eo(t)}#eo(t){const e=[],i=new Set;for(const i of t){const[t,n,s]=i;e.push([t,n,i],[t,s,i])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,n=e.length;t<n;t+=2){const n=e[t][2],s=e[t+1][2];n.push(s),s.push(n),i.add(n),i.add(s)}const n=[];let s;for(;i.size>0;){const t=i.values().next().value;let[e,r,a,o,l]=t;i.delete(t);let h=e,c=r;for(s=[e,a],n.push(s);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,r,a,o,l]=t,h!==e&&(s.push(h,c,e,c===r?r:a),h=e),c=c===r?a:r}s.push(h,c)}return new Rs(n,this.#Aa,this.#Xa,this.#Ka)}#io(t){const e=this.#Ja;let i=0,n=e.length-1;for(;i<=n;){const s=i+n>>1,r=e[s][0];if(r===t)return s;r<t?i=s+1:n=s-1}return n+1}#Za([,t,e]){const i=this.#io(t);this.#Ja.splice(i,0,[t,e])}#to([,t,e]){const i=this.#io(t);for(let n=i;n<this.#Ja.length;n++){const[i,s]=this.#Ja[n];if(i!==t)break;if(i===t&&s===e)return void this.#Ja.splice(n,1)}for(let n=i-1;n>=0;n--){const[i,s]=this.#Ja[n];if(i!==t)break;if(i===t&&s===e)return void this.#Ja.splice(n,1)}}#Qa(t){const[e,i,n]=t,s=[[e,i,n]],r=this.#io(n);for(let t=0;t<r;t++){const[i,n]=this.#Ja[t];for(let t=0,r=s.length;t<r;t++){const[,a,o]=s[t];if(!(n<=a||o<=i))if(a>=i)if(o>n)s[t][1]=n;else{if(1===r)return[];s.splice(t,1),t--,r--}else s[t][2]=i,o>n&&s.push([e,n,o])}}return s}}class Rs extends Ds{#Aa;#no;constructor(t,e,i,n){super(),this.#no=t,this.#Aa=e,this.firstPoint=i,this.lastPoint=n}toSVGPath(){const t=[];for(const e of this.#no){let[i,n]=e;t.push(`M${i} ${n}`);for(let s=2;s<e.length;s+=2){const r=e[s],a=e[s+1];r===i?(t.push(`V${a}`),n=a):a===n&&(t.push(`H${r}`),i=r)}t.push("Z")}return t.join(" ")}serialize([t,e,i,n],s){const r=[],a=i-t,o=n-e;for(const e of this.#no){const i=new Array(e.length);for(let s=0;s<e.length;s+=2)i[s]=t+e[s]*a,i[s+1]=n-e[s+1]*o;r.push(i)}return r}get box(){return this.#Aa}get classNamesForOutlining(){return["highlightOutline"]}}class Ls extends Ms{newFreeDrawOutline(t,e,i,n,s,r){return new Bs(t,e,i,n,s,r)}}class Bs extends Ps{newOutliner(t,e,i,n,s,r=0){return new Ls(t,e,i,n,s,r)}}class Fs extends be{#so=null;#ro=0;#ao;#oo=null;#s=null;#lo=null;#ho=null;#co=0;#do=null;#uo=null;#x=null;#po=!1;#Xa=null;#Ka=null;#go=null;#ce="";#Ra;#mo="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=F.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=Fs.prototype;return pt(this,"_keyboardManager",new de([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||Fs._defaultColor,this.#Ra=t.thickness||Fs._defaultThickness,this.opacity=t.opacity||Fs._defaultOpacity,this.#ao=t.boxes||null,this.#mo=t.methodOfCreation||"",this.#ce=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#po=!0,this.#fo(t),this.#bo()):this.#ao&&(this.#so=t.anchorNode,this.#ro=t.anchorOffset,this.#ho=t.focusNode,this.#co=t.focusOffset,this.#vo(),this.#bo(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}get telemetryInitialData(){return{action:"added",type:this.#po?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#Ra,methodOfCreation:this.#mo}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#vo(){const t=new Is(this.#ao,.001);this.#uo=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#uo.box;const e=new Is(this.#ao,.0025,.001,"ltr"===this._uiManager.direction);this.#lo=e.getOutlines();const{firstPoint:i}=this.#uo;this.#Xa=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];const{lastPoint:n}=this.#lo;this.#Ka=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height]}#fo({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#uo=t;if(this.#lo=t.getNewOutline(this.#Ra/2+1.5,.0025),e>=0)this.#x=e,this.#oo=i,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#go=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#lo.box,path:{d:this.#lo.toSVGPath()}},!0);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#x,{bbox:Fs.#yo(this.#uo.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#go,{bbox:Fs.#yo(this.#lo.box,e),path:{d:this.#lo.toSVGPath()}})}const[n,s,r,a]=t.box;switch(this.rotation){case 0:this.x=n,this.y=s,this.width=r,this.height=a;break;case 90:{const[t,e]=this.parentDimensions;this.x=s,this.y=1-n,this.width=r*e/t,this.height=a*t/e;break}case 180:this.x=1-n,this.y=1-s,this.width=r,this.height=a;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-s,this.y=n,this.width=r*e/t,this.height=a*t/e;break}}const{firstPoint:o}=t;this.#Xa=[(o[0]-n)/r,(o[1]-s)/a];const{lastPoint:l}=this.#lo;this.#Ka=[(l[0]-n)/r,(l[1]-s)/a]}static initialize(t,e){be.initialize(t,e),Fs._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case O.HIGHLIGHT_COLOR:Fs._defaultColor=e;break;case O.HIGHLIGHT_THICKNESS:Fs._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Ka}get commentButtonPosition(){return this.#Xa}updateParams(t,e){switch(t){case O.HIGHLIGHT_COLOR:this.#Hr(e);break;case O.HIGHLIGHT_THICKNESS:this.#wo(e)}}static get defaultPropertiesToUpdate(){return[[O.HIGHLIGHT_COLOR,Fs._defaultColor],[O.HIGHLIGHT_THICKNESS,Fs._defaultThickness]]}get propertiesToUpdate(){return[[O.HIGHLIGHT_COLOR,this.color||Fs._defaultColor],[O.HIGHLIGHT_THICKNESS,this.#Ra||Fs._defaultThickness],[O.HIGHLIGHT_FREE,this.#po]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#x,{root:{fill:this.color,"fill-opacity":this.opacity}}),this.#s?.updateColor(this.color),super.onUpdatedColor()}#Hr(t){const e=(t,e)=>{this.color=t,this.opacity=e,this.onUpdatedColor()},i=this.color,n=this.opacity;this.addCommands({cmd:e.bind(this,t,Fs._defaultOpacity),undo:e.bind(this,i,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:O.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#wo(t){const e=this.#Ra,i=t=>{this.#Ra=t,this.#xo(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:O.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){if(this._uiManager.highlightColors){return[["colorPicker",this.#s=new $n({editor:this})]]}return super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#Ao())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Ao())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#_o(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#bo(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#_o():t&&(this.#bo(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#xo(t){this.#po&&(this.#fo({highlightOutlines:this.#uo.getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims(this.width,this.height))}#_o(){null!==this.#x&&this.parent&&(this.parent.drawLayer.remove(this.#x),this.#x=null,this.parent.drawLayer.remove(this.#go),this.#go=null)}#bo(t=this.parent){null===this.#x&&(({id:this.#x,clipPathId:this.#oo}=t.drawLayer.draw({bbox:this.#uo.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#po},path:{d:this.#uo.toSVGPath()}},!1,!0)),this.#go=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#po},bbox:this.#lo.box,path:{d:this.#lo.toSVGPath()}},this.#po),this.#do&&(this.#do.style.clipPath=this.#oo))}static#yo([t,e,i,n],s){switch(s){case 90:return[1-e-n,t,n,i];case 180:return[1-t-i,1-e-n,i,n];case 270:return[e,1-t-i,n,i]}return[t,e,i,n]}rotate(t){const{drawLayer:e}=this.parent;let i;this.#po?(t=(t-this.rotation+360)%360,i=Fs.#yo(this.#uo.box,t)):i=Fs.#yo([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#x,{bbox:i,root:{"data-main-rotation":t}}),e.updateProperties(this.#go,{bbox:Fs.#yo(this.#lo.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#ce&&(t.setAttribute("aria-label",this.#ce),t.setAttribute("role","mark")),this.#po?t.classList.add("free"):this.div.addEventListener("keydown",this.#So.bind(this),{signal:this._uiManager._signal});const e=this.#do=document.createElement("div");return t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#oo,this.setDims(this.width,this.height),oe(this,this.#do,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{hovered:!1}})}#So(t){Fs._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#Co(!0);break;case 1:case 3:this.#Co(!1)}}#Co(t){if(!this.#so)return;const e=window.getSelection();t?e.setPosition(this.#so,this.#ro):e.setPosition(this.#ho,this.#co)}select(){super.select(),this.#go&&this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#go&&(this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{selected:!1}}),this.#po||this.#Co(!1))}get _mustFixPosition(){return!this.#po}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#x,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#go,{rootClass:{hidden:!t}}))}#Ao(){return this.#po?this.rotation:0}#Eo(){if(this.#po)return null;const[t,e]=this.pageDimensions,[i,n]=this.pageTranslation,s=this.#ao,r=new Float32Array(8*s.length);let a=0;for(const{x:o,y:l,width:h,height:c}of s){const s=o*t+i,d=(1-l)*e+n;r[a]=r[a+4]=s,r[a+1]=r[a+3]=d,r[a+2]=r[a+6]=s+h*t,r[a+5]=r[a+7]=d-c*e,a+=8}return r}#To(t){return this.#uo.serialize(t,this.#Ao())}static startHighlighting(t,e,{target:i,x:n,y:s}){const{x:r,y:a,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,c=t.combinedSignal(h),d=e=>{h.abort(),this.#ko(t,e)};window.addEventListener("blur",d,{signal:c}),window.addEventListener("pointerup",d,{signal:c}),window.addEventListener("pointerdown",Wt,{capture:!0,passive:!1,signal:c}),window.addEventListener("contextmenu",$t,{signal:c}),i.addEventListener("pointermove",this.#Do.bind(this,t),{signal:c}),this._freeHighlight=new Ls({x:n,y:s},[r,a,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#Do(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#ko(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let n=null;if(t instanceof ws){const{data:{quadPoints:e,rect:i,rotation:s,id:r,color:a,opacity:o,popupRef:l,richText:h,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;n=t={annotationType:F.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:c?.str||null,creationDate:d,modificationDate:u}}else if(t instanceof ys){const{data:{inkLists:e,rect:i,rotation:s,id:r,color:a,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;n=t={annotationType:F.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:c?.str||null,creationDate:d,modificationDate:u}}const{color:s,quadPoints:r,inkLists:a,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Ct.makeHexColor(...s),l.opacity=o||1,a&&(l.#Ra=t.thickness),l._initialData=n,t.comment&&l.setCommentData(t);const[h,c]=l.pageDimensions,[d,u]=l.pageTranslation;if(r){const t=l.#ao=[];for(let e=0;e<r.length;e+=8)t.push({x:(r[e]-d)/h,y:1-(r[e+1]-u)/c,width:(r[e+2]-r[e])/h,height:(r[e+1]-r[e+5])/c});l.#vo(),l.#bo(),l.rotate(l.rotation)}else if(a){l.#po=!0;const t=a[0],i={x:t[0]-d,y:c-(t[1]-u)},n=new Ls(i,[0,0,h,c],1,l.#Ra/2,!0,.001);for(let e=0,s=t.length;e<s;e+=2)i.x=t[e]-d,i.y=c-(t[e+1]-u),n.add(i);const{id:s,clipPathId:r}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:n.toSVGPath()}},!0,!0);l.#fo({highlightOutlines:n.getOutlines(),highlightId:s,clipPathId:r}),l.#bo(),l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=be._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);return Object.assign(i,{color:e,opacity:this.opacity,thickness:this.#Ra,quadPoints:this.#Eo(),outlines:this.#To(i.rect)}),this.addComment(i),this.annotationElementId&&!this.#xa(i)?null:(i.id=this.annotationElementId,i)}#xa(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,i)=>t!==e[i])}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}}class Os{#Mo=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#Mo[t]=e}toSVGProperties(){const t=this.#Mo;return this.#Mo=Object.create(null),{root:t}}reset(){this.#Mo=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){ht("Not implemented")}}class Ns extends be{#Po=null;#Io;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#Ro=null;static#Lo=null;static#Bo=null;static#Fo=NaN;static#Oo=null;static#No=null;static#Uo=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#Io=t.mustBeCommitted||!1,this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}_addOutlines(t){t.drawOutlines&&(this.#jo(t),this.#bo())}#jo({drawOutlines:t,drawId:e,drawingOptions:i}){this.#Po=t,this._drawingOptions||=i,this.annotationElementId||this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`),e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#zo(t,this.parent),this.#Ho(t.box)}#zo(t,e){const{id:i}=e.drawLayer.draw(Ns._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[n,s]of Object.entries(e))i.has(n)?Object.assign(t[n],s):t[n]=s;return t}static getDefaultDrawingOptions(t){ht("Not implemented")}static get typesMap(){ht("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e),this._currentParent&&(Ns.#Ro.updateProperty(i,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,n]of this.typesMap)t.push([i,e[n]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,n]of this.constructor.typesMap)t.push([i,e[n]]);return t}_updateProperty(t,e,i){const n=this._drawingOptions,s=n[e],r=i=>{n.updateProperty(e,i);const s=this.#Po.updateProperty(e,i);s&&this.#Ho(s),this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties()),t===this.colorType&&this.onUpdatedColor()};this.addCommands({cmd:r.bind(this,i),undo:r.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,Ns._mergeSVGProperties(this.#Po.getPathResizingSVGProperties(this.#$o()),{bbox:this.#Wo()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,Ns._mergeSVGProperties(this.#Po.getPathResizedSVGProperties(this.#$o()),{bbox:this.#Wo()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Wo()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,Ns._mergeSVGProperties(this.#Po.getPathTranslatedSVGProperties(this.#$o(),this.parentDimensions),{bbox:this.#Wo()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#Io&&(this.#Io=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#_o(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#bo(),this.#Ho(this.#Po.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#_o()):t&&(this._uiManager.addShouldRescale(this),this.#bo(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#_o(){null!==this._drawId&&this.parent&&(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#bo(t=this.parent){null!==this._drawId&&this.parent===t||(null===this._drawId?(this._drawingOptions.updateAll(),this._drawId=this.#zo(this.#Po,t)):this.parent.drawLayer.updateParent(this._drawId,t.drawLayer))}#Vo([t,e,i,n]){const{parentDimensions:[s,r],rotation:a}=this;switch(a){case 90:return[e,1-t,i*(r/s),n*(s/r)];case 180:return[1-t,1-e,i,n];case 270:return[1-e,t,i*(r/s),n*(s/r)];default:return[t,e,i,n]}}#$o(){const{x:t,y:e,width:i,height:n,parentDimensions:[s,r],rotation:a}=this;switch(a){case 90:return[1-e,t,i*(s/r),n*(r/s)];case 180:return[1-t,1-e,i,n];case 270:return[e,1-t,i*(s/r),n*(r/s)];default:return[t,e,i,n]}}#Ho(t){[this.x,this.y,this.width,this.height]=this.#Vo(t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#Wo(){const{x:t,y:e,width:i,height:n,rotation:s,parentRotation:r,parentDimensions:[a,o]}=this;switch((4*s+r)/90){case 1:return[1-e-n,t,n,i];case 2:return[1-t-i,1-e-n,i,n];case 3:return[e,1-t-i,n,i];case 4:return[t,e-i*(a/o),n*(o/a),i*(a/o)];case 5:return[1-e,t,i*(a/o),n*(o/a)];case 6:return[1-t-n*(o/a),1-e,n*(o/a),i*(a/o)];case 7:return[e-i*(a/o),1-t-n*(o/a),i*(a/o),n*(o/a)];case 8:return[t-i,e-n,i,n];case 9:return[1-e,t-i,n,i];case 10:return[1-t,1-e,i,n];case 11:return[e-n,1-t,n,i];case 12:return[t-n*(o/a),e,n*(o/a),i*(a/o)];case 13:return[1-e-i*(a/o),t-n*(o/a),i*(a/o),n*(o/a)];case 14:return[1-t,1-e-i*(a/o),n*(o/a),i*(a/o)];case 15:return[e,1-t,i*(a/o),n*(o/a)];default:return[t,e,i,n]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,Ns._mergeSVGProperties({bbox:this.#Wo()},this.#Po.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Ho(this.#Po.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const i=super.render();i.classList.add("draw");const n=document.createElement("div");return i.append(n),n.setAttribute("aria-hidden","true"),n.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),i}static createDrawerInstance(t,e,i,n,s){ht("Not implemented")}static startDrawing(t,e,i,n){const{target:s,offsetX:r,offsetY:a,pointerId:o,pointerType:l}=n;if(Ns.#Oo&&Ns.#Oo!==l)return;const{viewport:{rotation:h}}=t,{width:c,height:d}=s.getBoundingClientRect(),u=Ns.#Lo=new AbortController,p=t.combinedSignal(u);Ns.#Fo||=o,Ns.#Oo??=l,window.addEventListener("pointerup",t=>{Ns.#Fo===t.pointerId?this._endDraw(t):Ns.#No?.delete(t.pointerId)},{signal:p}),window.addEventListener("pointercancel",t=>{Ns.#Fo===t.pointerId?this._currentParent.endDrawingSession():Ns.#No?.delete(t.pointerId)},{signal:p}),window.addEventListener("pointerdown",t=>{Ns.#Oo===t.pointerType&&((Ns.#No||=new Set).add(t.pointerId),Ns.#Ro.isCancellable()&&(Ns.#Ro.removeLastElement(),Ns.#Ro.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",$t,{signal:p}),s.addEventListener("pointermove",this._drawMove.bind(this),{signal:p}),s.addEventListener("touchmove",t=>{t.timeStamp===Ns.#Uo&&Wt(t)},{signal:p}),t.toggleDrawing(),e._editorUndoBar?.hide(),Ns.#Ro?t.drawLayer.updateProperties(this._currentDrawId,Ns.#Ro.startNew(r,a,c,d,h)):(e.updateUIForDefaultProperties(this),Ns.#Ro=this.createDrawerInstance(r,a,c,d,h),Ns.#Bo=this.getDefaultDrawingOptions(),this._currentParent=t,({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(Ns.#Bo.toSVGProperties(),Ns.#Ro.defaultSVGProperties),!0,!1)))}static _drawMove(t){if(Ns.#Uo=-1,!Ns.#Ro)return;const{offsetX:e,offsetY:i,pointerId:n}=t;Ns.#Fo===n&&(Ns.#No?.size>=1?this._endDraw(t):(this._currentParent.drawLayer.updateProperties(this._currentDrawId,Ns.#Ro.add(e,i)),Ns.#Uo=t.timeStamp,Wt(t)))}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,Ns.#Ro=null,Ns.#Bo=null,Ns.#Oo=null,Ns.#Uo=NaN),Ns.#Lo&&(Ns.#Lo.abort(),Ns.#Lo=null,Ns.#Fo=NaN,Ns.#No=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,Ns.#Ro.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const t=Ns.#Ro,i=this._currentDrawId,n=t.getLastElement();return void e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:O.DRAW_STEP})}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(O.DRAW_STEP),!Ns.#Ro.isEmpty()){const{pageDimensions:[i,n],scale:s}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:Ns.#Ro.getOutlines(i*s,n*s,s,this._INNER_MARGIN),drawingOptions:Ns.#Bo,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,i,n,s,r){ht("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:n,pageHeight:s,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,n,s,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);return l.createDrawingOptions(t),l.#jo({drawOutlines:o}),l.#bo(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,i]=this.pageTranslation,[n,s]=this.pageDimensions;return this.#Po.serialize([e,i,n,s],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class Us{#Ta=new Float64Array(6);#Kr;#Go;#ns;#Ra;#La;#qo="";#Xo=0;#no=new js;#Ko;#Yo;constructor(t,e,i,n,s,r){this.#Ko=i,this.#Yo=n,this.#ns=s,this.#Ra=r,[t,e]=this.#Jo(t,e);const a=this.#Kr=[NaN,NaN,NaN,NaN,t,e];this.#La=[t,e],this.#Go=[{line:a,points:this.#La}],this.#Ta.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#Ra=e)}#Jo(t,e){return Ds._normalizePoint(t,e,this.#Ko,this.#Yo,this.#ns)}isEmpty(){return!this.#Go||0===this.#Go.length}isCancellable(){return this.#La.length<=10}add(t,e){[t,e]=this.#Jo(t,e);const[i,n,s,r]=this.#Ta.subarray(2,6),a=t-s,o=e-r;return Math.hypot(this.#Ko*a,this.#Yo*o)<=2?null:(this.#La.push(t,e),isNaN(i)?(this.#Ta.set([s,r,t,e],2),this.#Kr.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#Ta[0])&&this.#Kr.splice(6,6),this.#Ta.set([i,n,s,r,t,e],0),this.#Kr.push(...Ds.createBezierPoints(i,n,s,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const i=this.add(t,e);return i||(2===this.#La.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,n,s){this.#Ko=i,this.#Yo=n,this.#ns=s,[t,e]=this.#Jo(t,e);const r=this.#Kr=[NaN,NaN,NaN,NaN,t,e];this.#La=[t,e];const a=this.#Go.at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),this.#Go.push({line:r,points:this.#La}),this.#Ta.set(r,0),this.#Xo=0,this.toSVGPath(),null}getLastElement(){return this.#Go.at(-1)}setLastElement(t){return this.#Go?(this.#Go.push(t),this.#Kr=t.line,this.#La=t.points,this.#Xo=0,{path:{d:this.toSVGPath()}}):this.#no.setLastElement(t)}removeLastElement(){if(!this.#Go)return this.#no.removeLastElement();this.#Go.pop(),this.#qo="";for(let t=0,e=this.#Go.length;t<e;t++){const{line:e,points:i}=this.#Go[t];this.#Kr=e,this.#La=i,this.#Xo=0,this.toSVGPath()}return{path:{d:this.#qo}}}toSVGPath(){const t=Ds.svgRound(this.#Kr[4]),e=Ds.svgRound(this.#Kr[5]);if(2===this.#La.length)return this.#qo=`${this.#qo} M ${t} ${e} Z`,this.#qo;if(this.#La.length<=6){const i=this.#qo.lastIndexOf("M");this.#qo=`${this.#qo.slice(0,i)} M ${t} ${e}`,this.#Xo=6}if(4===this.#La.length){const t=Ds.svgRound(this.#Kr[10]),e=Ds.svgRound(this.#Kr[11]);return this.#qo=`${this.#qo} L ${t} ${e}`,this.#Xo=12,this.#qo}const i=[];0===this.#Xo&&(i.push(`M ${t} ${e}`),this.#Xo=6);for(let t=this.#Xo,e=this.#Kr.length;t<e;t+=6){const[e,n,s,r,a,o]=this.#Kr.slice(t,t+6).map(Ds.svgRound);i.push(`C${e} ${n} ${s} ${r} ${a} ${o}`)}return this.#qo+=i.join(" "),this.#Xo=this.#Kr.length,this.#qo}getOutlines(t,e,i,n){const s=this.#Go.at(-1);return s.line=new Float32Array(s.line),s.points=new Float32Array(s.points),this.#no.build(this.#Go,t,e,i,this.#ns,this.#Ra,n),this.#Ta=null,this.#Kr=null,this.#Go=null,this.#qo=null,this.#no}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class js extends Ds{#Va;#Qo=0;#Sa;#Go;#Ko;#Yo;#Zo;#ns;#Ra;build(t,e,i,n,s,r,a){this.#Ko=e,this.#Yo=i,this.#Zo=n,this.#ns=s,this.#Ra=r,this.#Sa=a??0,this.#Go=t,this.#tl()}get thickness(){return this.#Ra}setLastElement(t){return this.#Go.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#Go.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#Go)if(t.push(`M${Ds.svgRound(e[4])} ${Ds.svgRound(e[5])}`),6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Ds.svgRound(e[10])} ${Ds.svgRound(e[11])}`);else for(let i=6,n=e.length;i<n;i+=6){const[n,s,r,a,o,l]=e.subarray(i,i+6).map(Ds.svgRound);t.push(`C${n} ${s} ${r} ${a} ${o} ${l}`)}else t.push("Z");return t.join("")}serialize([t,e,i,n],s){const r=[],a=[],[o,l,h,c]=this.#el();let d,u,p,g,m,f,b,v,y;switch(this.#ns){case 0:y=Ds._rescale,d=t,u=e+n,p=i,g=-n,m=t+o*i,f=e+(1-l-c)*n,b=t+(o+h)*i,v=e+(1-l)*n;break;case 90:y=Ds._rescaleAndSwap,d=t,u=e,p=i,g=n,m=t+l*i,f=e+o*n,b=t+(l+c)*i,v=e+(o+h)*n;break;case 180:y=Ds._rescale,d=t+i,u=e,p=-i,g=n,m=t+(1-o-h)*i,f=e+l*n,b=t+(1-o)*i,v=e+(l+c)*n;break;case 270:y=Ds._rescaleAndSwap,d=t+i,u=e+n,p=-i,g=-n,m=t+(1-l-c)*i,f=e+(1-o-h)*n,b=t+(1-l)*i,v=e+(1-o)*n}for(const{line:t,points:e}of this.#Go)r.push(y(t,d,u,p,g,s?new Array(t.length):null)),a.push(y(e,d,u,p,g,s?new Array(e.length):null));return{lines:r,points:a,rect:[m,f,b,v]}}static deserialize(t,e,i,n,s,{paths:{lines:r,points:a},rotation:o,thickness:l}){const h=[];let c,d,u,p,g;switch(o){case 0:g=Ds._rescale,c=-t/i,d=e/n+1,u=1/i,p=-1/n;break;case 90:g=Ds._rescaleAndSwap,c=-e/n,d=-t/i,u=1/n,p=1/i;break;case 180:g=Ds._rescale,c=t/i+1,d=-e/n,u=-1/i,p=1/n;break;case 270:g=Ds._rescaleAndSwap,c=e/n+1,d=t/i+1,u=-1/n,p=-1/i}if(!r){r=[];for(const t of a){const e=t.length;if(2===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const i=new Float32Array(3*(e-2));r.push(i);let[n,s,a,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,n,s],0);for(let r=4;r<e;r+=2){const e=t[r],l=t[r+1];i.set(Ds.createBezierPoints(n,s,a,o,e,l),3*(r-2)),[n,s,a,o]=[a,o,e,l]}}}for(let t=0,e=r.length;t<e;t++)h.push({line:g(r[t].map(t=>t??NaN),c,d,u,p),points:g(a[t].map(t=>t??NaN),c,d,u,p)});const m=new this.prototype.constructor;return m.build(h,i,n,1,o,l,s),m}#il(t=this.#Ra){const e=this.#Sa+t/2*this.#Zo;return this.#ns%180==0?[e/this.#Ko,e/this.#Yo]:[e/this.#Yo,e/this.#Ko]}#el(){const[t,e,i,n]=this.#Va,[s,r]=this.#il(0);return[t+s,e+r,i-2*s,n-2*r]}#tl(){const t=this.#Va=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Go){if(e.length<=12){for(let i=4,n=e.length;i<n;i+=6)Ct.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],n=e[5];for(let s=6,r=e.length;s<r;s+=6){const[r,a,o,l,h,c]=e.subarray(s,s+6);Ct.bezierBoundingBox(i,n,r,a,o,l,h,c,t),i=h,n=c}}const[e,i]=this.#il();t[0]=Mt(t[0]-e,0,1),t[1]=Mt(t[1]-i,0,1),t[2]=Mt(t[2]+e,0,1),t[3]=Mt(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#Va}updateProperty(t,e){return"stroke-width"===t?this.#wo(e):null}#wo(t){const[e,i]=this.#il();this.#Ra=t;const[n,s]=this.#il(),[r,a]=[n-e,s-i],o=this.#Va;return o[0]-=r,o[1]-=a,o[2]+=2*r,o[3]+=2*a,o}updateParentDimensions([t,e],i){const[n,s]=this.#il();this.#Ko=t,this.#Yo=e,this.#Zo=i;const[r,a]=this.#il(),o=r-n,l=a-s,h=this.#Va;return h[0]-=o,h[1]-=l,h[2]+=2*o,h[3]+=2*l,h}updateRotation(t){return this.#Qo=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#Va.map(Ds.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#Va;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Ds.svgRound(t)} ${Ds.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#Va;let i=0,n=0,s=0,r=0,a=0,o=0;switch(this.#Qo){case 90:n=e/t,s=-t/e,a=t;break;case 180:i=-1,r=-1,a=t,o=e;break;case 270:n=-e/t,s=t/e,o=e;break;default:return""}return`matrix(${i} ${n} ${s} ${r} ${Ds.svgRound(a)} ${Ds.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,n]){const[s,r]=this.#il(),[a,o,l,h]=this.#Va;if(Math.abs(l-s)<=Ds.PRECISION||Math.abs(h-r)<=Ds.PRECISION){const s=t+i/2-(a+l/2),r=e+n/2-(o+h/2);return{path:{"transform-origin":`${Ds.svgRound(t)} ${Ds.svgRound(e)}`,transform:`${this.rotationTransform} translate(${s} ${r})`}}}const c=(i-2*s)/(l-2*s),d=(n-2*r)/(h-2*r),u=l/i,p=h/n;return{path:{"transform-origin":`${Ds.svgRound(a)} ${Ds.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Ds.svgRound(s)} ${Ds.svgRound(r)}) scale(${c} ${d}) translate(${Ds.svgRound(-s)} ${Ds.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,i,n]){const[s,r]=this.#il(),a=this.#Va,[o,l,h,c]=a;if(a[0]=t,a[1]=e,a[2]=i,a[3]=n,Math.abs(h-s)<=Ds.PRECISION||Math.abs(c-r)<=Ds.PRECISION){const s=t+i/2-(o+h/2),r=e+n/2-(l+c/2);for(const{line:t,points:e}of this.#Go)Ds._translate(t,s,r,t),Ds._translate(e,s,r,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Ds.svgRound(t)} ${Ds.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(i-2*s)/(h-2*s),u=(n-2*r)/(c-2*r),p=-d*(o+s)+t+s,g=-u*(l+r)+e+r;if(1!==d||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#Go)Ds._rescale(t,p,g,d,u,t),Ds._rescale(e,p,g,d,u,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Ds.svgRound(t)} ${Ds.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[n,s]=i,r=this.#Va,a=t-r[0],o=e-r[1];if(this.#Ko===n&&this.#Yo===s)for(const{line:t,points:e}of this.#Go)Ds._translate(t,a,o,t),Ds._translate(e,a,o,e);else{const t=this.#Ko/n,e=this.#Yo/s;this.#Ko=n,this.#Yo=s;for(const{line:i,points:n}of this.#Go)Ds._rescale(i,a,o,t,e,i),Ds._rescale(n,a,o,t,e,n);r[2]*=t,r[3]*=e}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Ds.svgRound(t)} ${Ds.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#Va;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Ds.svgRound(t[0])} ${Ds.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class zs extends Os{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:be._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){"stroke-width"===t&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new zs(this._viewParameters);return t.updateAll(this),t}}class Hs extends Ns{static _type="ink";static _editorType=F.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){be.initialize(t,e),this._defaultDrawingOptions=new zs(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return pt(this,"typesMap",new Map([[O.INK_THICKNESS,"stroke-width"],[O.INK_COLOR,"stroke"],[O.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,n,s){return new Us(t,e,i,n,s,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,n,s,r){return js.deserialize(t,e,i,n,s,r)}static async deserialize(t,e,i){let n=null;if(t instanceof ys){const{data:{inkLists:e,rect:i,rotation:s,id:r,color:a,opacity:o,borderStyle:{rawWidth:l},popupRef:h,richText:c,contentsObj:d,creationDate:u,modificationDate:p},parent:{page:{pageNumber:g}}}=t;n=t={annotationType:F.INK,color:Array.from(a),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:h,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const s=await super.deserialize(t,e,i);return s._initialData=n,t.comment&&s.setCommentData(t),s}get toolbarButtons(){return this._colorPicker||=new Wn(this),[["colorPicker",this._colorPicker]]}get colorType(){return O.INK_COLOR}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:i}){this._drawingOptions=Hs.getDefaultDrawingOptions({stroke:Ct.makeHexColor(...t),"stroke-width":e,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":s,"stroke-width":r}}=this,a=Object.assign(super.serialize(t),{color:be._colorManager.convert(n),opacity:s,thickness:r,paths:{lines:e,points:i}});return this.addComment(a),t?(a.isCopy=!0,a):this.annotationElementId&&!this.#xa(a)?null:(a.id=this.annotationElementId,a)}#xa(t){const{color:e,thickness:i,opacity:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((t,i)=>t!==e[i])||t.thickness!==i||t.opacity!==n||t.pageIndex!==s}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:e,rect:i}=this.serializeDraw(!1);return t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment}),null}}class $s extends js{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}class Ws{static#nl={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#sl(t,e,i,n){return n-=e,0===(i-=t)?n>0?0:4:1===i?n+6:2-n}static#rl=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#al(t,e,i,n,s,r,a){const o=this.#sl(i,n,s,r);for(let s=0;s<8;s++){const r=(-s+o-a+16)%8;if(0!==t[(i+this.#rl[2*r])*e+(n+this.#rl[2*r+1])])return r}return-1}static#ol(t,e,i,n,s,r,a){const o=this.#sl(i,n,s,r);for(let s=0;s<8;s++){const r=(s+o+a+16)%8;if(0!==t[(i+this.#rl[2*r])*e+(n+this.#rl[2*r+1])])return r}return-1}static#ll(t,e,i,n){const s=t.length,r=new Int32Array(s);for(let e=0;e<s;e++)r[e]=t[e]<=n?1:0;for(let t=1;t<i-1;t++)r[t*e]=r[t*e+e-1]=0;for(let t=0;t<e;t++)r[t]=r[e*i-1-t]=0;let a,o=1;const l=[];for(let t=1;t<i-1;t++){a=1;for(let i=1;i<e-1;i++){const n=t*e+i,s=r[n];if(0===s)continue;let h=t,c=i;if(1===s&&0===r[n-1])o+=1,c-=1;else{if(!(s>=1&&0===r[n+1])){1!==s&&(a=Math.abs(s));continue}o+=1,c+=1,s>1&&(a=s)}const d=[i,t],u=c===i+1,p={isHole:u,points:d,id:o,parent:0};let g;l.push(p);for(const t of l)if(t.id===a){g=t;break}g?g.isHole?p.parent=u?g.parent:a:p.parent=u?a:g.parent:p.parent=u?a:0;const m=this.#al(r,e,t,i,h,c,0);if(-1===m){r[n]=-o,1!==r[n]&&(a=Math.abs(r[n]));continue}let f=this.#rl[2*m],b=this.#rl[2*m+1];const v=t+f,y=i+b;h=v,c=y;let w=t,x=i;for(;;){const s=this.#ol(r,e,w,x,h,c,1);f=this.#rl[2*s],b=this.#rl[2*s+1];const l=w+f,u=x+b;d.push(u,l);const p=w*e+x;if(0===r[p+1]?r[p]=-o:1===r[p]&&(r[p]=o),l===t&&u===i&&w===v&&x===y){1!==r[n]&&(a=Math.abs(r[n]));break}h=w,c=x,w=l,x=u}}}return l}static#hl(t,e,i,n){if(i-e<=4){for(let s=e;s<i-2;s+=2)n.push(t[s],t[s+1]);return}const s=t[e],r=t[e+1],a=t[i-4]-s,o=t[i-3]-r,l=Math.hypot(a,o),h=a/l,c=o/l,d=h*r-c*s,u=o/a,p=1/l,g=Math.atan(u),m=Math.cos(g),f=Math.sin(g),b=p*(Math.abs(m)+Math.abs(f)),v=p*(1-b+b**2),y=Math.max(Math.atan(Math.abs(f+m)*v),Math.atan(Math.abs(f-m)*v));let w=0,x=e;for(let n=e+2;n<i-2;n+=2){const e=Math.abs(d-h*t[n+1]+c*t[n]);e>w&&(x=n,w=e)}w>(l*y)**2?(this.#hl(t,e,x+2,n),this.#hl(t,x,i,n)):n.push(s,r)}static#cl(t){const e=[],i=t.length;return this.#hl(t,0,i,e),e.push(t[i-2],t[i-1]),e.length<=4?null:e}static#dl(t,e,i,n,s,r){const a=new Float32Array(r**2),o=-2*n**2,l=r>>1;for(let t=0;t<r;t++){const e=(t-l)**2;for(let i=0;i<r;i++)a[t*r+i]=Math.exp((e+(i-l)**2)/o)}const h=new Float32Array(256),c=-2*s**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/c);const d=t.length,u=new Uint8Array(d),p=new Uint32Array(256);for(let n=0;n<i;n++)for(let s=0;s<e;s++){const o=n*e+s,c=t[o];let d=0,g=0;for(let o=0;o<r;o++){const u=n+o-l;if(!(u<0||u>=i))for(let i=0;i<r;i++){const n=s+i-l;if(n<0||n>=e)continue;const p=t[u*e+n],m=a[o*r+i]*h[Math.abs(p-c)];d+=p*m,g+=m}}p[u[o]=Math.round(d/g)]++}return[u,p]}static#ul(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#pl(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let n=-1/0,s=1/0;for(let e=0,r=i.length;e<r;e++){const r=i[e]=t[e<<2];n=Math.max(n,r),s=Math.min(s,r)}const r=255/(n-s);for(let t=0,e=i.length;t<e;t++)i[t]=(i[t]-s)*r;return i}static#gl(t){let e,i=-1/0,n=-1/0;const s=t.findIndex(t=>0!==t);let r=s,a=s;for(e=s;e<256;e++){const s=t[e];s>i&&(e-r>n&&(n=e-r,a=e-1),i=s,r=e)}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#ml(t){const e=t,{width:i,height:n}=t,{maxDim:s}=this.#nl;let r=i,a=n;if(i>s||n>s){let o=i,l=n,h=Math.log2(Math.max(i,n)/s);const c=Math.floor(h);h=h===c?c-1:c;for(let i=0;i<h;i++){r=Math.ceil(o/2),a=Math.ceil(l/2);const i=new OffscreenCanvas(r,a);i.getContext("2d").drawImage(t,0,0,o,l,0,0,r,a),o=r,l=a,t!==e&&t.close(),t=i.transferToImageBitmap()}const d=Math.min(s/r,s/a);r=Math.round(r*d),a=Math.round(a*d)}const o=new OffscreenCanvas(r,a).getContext("2d",{willReadFrequently:!0});o.fillStyle="white",o.fillRect(0,0,r,a),o.filter="grayscale(1)",o.drawImage(t,0,0,t.width,t.height,0,0,r,a);const l=o.getImageData(0,0,r,a).data;return[this.#pl(l),r,a]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:n},s,r,a,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1});const c=h.font=`${i} ${n} 200px ${e}`,{actualBoundingBoxLeft:d,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=h.measureText(t),v=1.5,y=Math.ceil(Math.max(Math.abs(d)+Math.abs(u)||0,b)*v),w=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*v);l=new OffscreenCanvas(y,w),h=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),h.font=c,h.filter="grayscale(1)",h.fillStyle="white",h.fillRect(0,0,y,w),h.fillStyle="black",h.fillText(t,.5*y/2,1.5*w/2);const x=this.#pl(h.getImageData(0,0,y,w).data),A=this.#ul(x),_=this.#gl(A),S=this.#ll(x,y,w,_);return this.processDrawnLines({lines:{curves:S,width:y,height:w},pageWidth:s,pageHeight:r,rotation:a,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,n,s){const[r,a,o]=this.#ml(t),[l,h]=this.#dl(r,a,o,Math.hypot(a,o)*this.#nl.sigmaSFactor,this.#nl.sigmaR,this.#nl.kernelSize),c=this.#gl(h),d=this.#ll(l,a,o,c);return this.processDrawnLines({lines:{curves:d,width:a,height:o},pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:r,areContours:a}){n%180!=0&&([e,i]=[i,e]);const{curves:o,width:l,height:h}=t,c=t.thickness??0,d=[],u=Math.min(e/l,i/h),p=u/e,g=u/i,m=[];for(const{points:t}of o){const e=r?this.#cl(t):t;if(!e)continue;m.push(e);const i=e.length,n=new Float32Array(i),s=new Float32Array(3*(2===i?2:i-2));if(d.push({line:s,points:n}),2===i){n[0]=e[0]*p,n[1]=e[1]*g,s.set([NaN,NaN,NaN,NaN,n[0],n[1]],0);continue}let[a,o,l,h]=e;a*=p,o*=g,l*=p,h*=g,n.set([a,o,l,h],0),s.set([NaN,NaN,NaN,NaN,a,o],0);for(let t=4;t<i;t+=2){const i=n[t]=e[t]*p,r=n[t+1]=e[t+1]*g;s.set(Ds.createBezierPoints(a,o,l,h,i,r),3*(t-2)),[a,o,l,h]=[l,h,i,r]}}if(0===d.length)return null;const f=a?new $s:new js;return f.build(d,e,i,1,n,a?0:c,s),{outline:f,newCurves:m,areContours:a,thickness:c,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:n,height:s}){let r,a=1/0,o=-1/0,l=0;for(const e of t){l+=e.length;for(let t=2,i=e.length;t<i;t++){const i=e[t]-e[t-2];a=Math.min(a,i),o=Math.max(o,i)}}r=a>=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,c=8+3*h,d=new Uint32Array(c);let u=0;d[u++]=c*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*r.BYTES_PER_ELEMENT,d[u++]=0,d[u++]=n,d[u++]=s,d[u++]=e?0:1,d[u++]=Math.max(0,Math.floor(i??0)),d[u++]=h,d[u++]=r.BYTES_PER_ELEMENT;for(const e of t)d[u++]=e.length-2,d[u++]=e[0],d[u++]=e[1];const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(d);const m=r.prototype.constructor;for(const e of t){const t=new m(e.length-2);for(let i=2,n=e.length;i<n;i++)t[i-2]=e[i]-e[i-2];g.write(t)}g.close();const f=await new Response(p.readable).arrayBuffer();return Pt(new Uint8Array(f))}static async decompressSignature(t){try{const i=(e=t,Uint8Array.fromBase64?Uint8Array.fromBase64(e):At(atob(e))),{readable:n,writable:s}=new DecompressionStream("deflate-raw"),r=s.getWriter();await r.ready,r.write(i).then(async()=>{await r.ready,await r.close()}).catch(()=>{});let a=null,o=0;for await(const t of n)a||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),a.set(t,o),o+=t.length;const l=new Uint32Array(a.buffer,0,a.length>>2),h=l[1];if(0!==h)throw new Error(`Invalid version: ${h}`);const c=l[2],d=l[3],u=0===l[4],p=l[5],g=l[6],m=l[7],f=[],b=(8+3*g)*Uint32Array.BYTES_PER_ELEMENT;let v;switch(m){case Int8Array.BYTES_PER_ELEMENT:v=new Int8Array(a.buffer,b);break;case Int16Array.BYTES_PER_ELEMENT:v=new Int16Array(a.buffer,b);break;case Int32Array.BYTES_PER_ELEMENT:v=new Int32Array(a.buffer,b)}o=0;for(let t=0;t<g;t++){const e=l[3*t+8],i=new Float32Array(e+2);f.push(i);for(let e=0;e<2;e++)i[e]=l[3*t+8+e+1];for(let t=0;t<e;t++)i[t+2]=i[t]+v[o++]}return{areContours:u,thickness:p,outlines:f,width:c,height:d}}catch(t){return lt(`decompressSignature: ${t}`),null}var e}}class Vs extends Os{constructor(){super(),super.updateProperties({fill:be._defaultLineColor,"stroke-width":0})}clone(){const t=new Vs;return t.updateAll(this),t}}class Gs extends zs{constructor(t){super(t),super.updateProperties({stroke:be._defaultLineColor,"stroke-width":1})}clone(){const t=new Gs(this._viewParameters);return t.updateAll(this),t}}class qs extends Ns{#fl=!1;#bl=null;#vl=null;#yl=null;static _type="signature";static _editorType=F.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#vl=t.signatureData||null,this.#bl=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){be.initialize(t,e),this._defaultDrawingOptions=new Vs,this._defaultDrawnSignatureOptions=new Gs(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return pt(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#bl}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:i}=this;if(i&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),null===this._drawId)if(this.#vl){const{lines:t,mustSmooth:e,areContours:i,description:n,uuid:s,heightInPage:r}=this.#vl,{rawDims:{pageWidth:a,pageHeight:o},rotation:l}=this.parent.viewport,h=Ws.processDrawnLines({lines:t,pageWidth:a,pageHeight:o,rotation:l,innerMargin:qs._INNER_MARGIN,mustSmooth:e,areContours:i});this.addSignature(h,r,n,s)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#bl||""}));return i&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#yl=t,this.addEditToolbar()}getUuid(){return this.#yl}get description(){return this.#bl}set description(t){this.#bl=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:i,width:n,height:s}=this.#vl,r=Math.max(n,s);return{areContours:e,outline:Ws.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:n,height:s},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,i,n){const{x:s,y:r}=this,{outline:a}=this.#vl=t;let o;this.#fl=a instanceof $s,this.description=i,this.#fl?o=qs.getDefaultDrawingOptions():(o=qs._defaultDrawnSignatureOptions.clone(),o.updateProperties({"stroke-width":a.thickness})),this._addOutlines({drawOutlines:a,drawingOptions:o});const[,l]=this.pageDimensions;let h=e/l;h=h>=1?.5:h,this.width*=h/this.height,this.width>=1&&(h*=.9/this.width,this.width=.9),this.height=h,this.setDims(),this.x=s,this.y=r,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(n),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!n,hasDescription:!!i}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return Ws.process(t,e,i,n,qs._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:n},rotation:s}=this.parent.viewport;return Ws.extractContoursFromText(t,e,i,n,s,qs._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return Ws.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:qs._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=qs.getDefaultDrawingOptions():(this._drawingOptions=qs._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":n}}=this,s=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#fl,color:[0,0,0],thickness:this.#fl?0:n});return this.addComment(s),t?(s.paths={lines:e,points:i},s.uuid=this.#yl,s.isCopy=!0):s.lines=e,this.#bl&&(s.accessibilityData={type:"Figure",alt:this.#bl}),s}static deserializeDraw(t,e,i,n,s,r){return r.areContours?$s.deserialize(t,e,i,n,s,r):js.deserialize(t,e,i,n,s,r)}static async deserialize(t,e,i){const n=await super.deserialize(t,e,i);return n.#fl=t.areContours,n.description=t.accessibilityData?.alt||"",n.#yl=t.uuid,n}}class Xs extends be{#wl=null;#xl=null;#Al=null;#_l=null;#Sl=null;#Cl="";#El=null;#Tl=!1;#kl=null;#Dl=!1;#Ml=!1;static _type="stamp";static _editorType=F.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#_l=t.bitmapUrl,this.#Sl=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){be.initialize(t,e)}static isHandlingMimeForPasting(t){return Jt.includes(t)}static paste(t,e){e.pasteEditor({mode:F.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#Pl(t,e=!1){t?(this.#wl=t.bitmap,e||(this.#xl=t.id,this.#Dl=t.isSvg),t.file&&(this.#Cl=t.file.name),this.#Il()):this.remove()}#Rl(){if(this.#Al=null,this._uiManager.enableWaiting(!1),this.#El)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#wl)this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#wl){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:n,width:s,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await i.guess({name:"altText",request:{data:n,width:s,height:r,channels:n.length/(s*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const o=a.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#Ll(){if(this.#xl)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#xl).then(t=>this.#Pl(t,!0)).finally(()=>this.#Rl());if(this.#_l){const t=this.#_l;return this.#_l=null,this._uiManager.enableWaiting(!0),void(this.#Al=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#Pl(t)).finally(()=>this.#Rl()))}if(this.#Sl){const t=this.#Sl;return this.#Sl=null,this._uiManager.enableWaiting(!0),void(this.#Al=this._uiManager.imageManager.getFromFile(t).then(t=>this.#Pl(t)).finally(()=>this.#Rl()))}const t=document.createElement("input");t.type="file",t.accept=Jt.join(",");const e=this._uiManager._signal;this.#Al=new Promise(i=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#Pl(e)}else this.remove();i()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:e})}).finally(()=>this.#Rl()),t.click()}remove(){this.#xl&&(this.#wl=null,this._uiManager.imageManager.deleteId(this.#xl),this.#El?.remove(),this.#El=null,this.#kl&&(clearTimeout(this.#kl),this.#kl=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#xl&&null===this.#El&&this.#Ll(),this.isAttachedToDOM||this.parent.add(this))):this.#xl&&this.#Ll()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#Al||this.#wl||this.#_l||this.#Sl||this.#xl||this.#Tl)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#Tl||(this.#wl?this.#Il():this.#Ll()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:i,bitmap:n}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(this.#xl=i,n&&(this.#wl=n),this.#Tl=!1,this.#Il())}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#kl&&clearTimeout(this.#kl);this.#kl=setTimeout(()=>{this.#kl=null,this.#Bl()},200)}#Il(){const{div:t}=this;let{width:e,height:i}=this.#wl;const[n,s]=this.pageDimensions,r=.75;if(this.width)e=this.width*n,i=this.height*s;else if(e>r*n||i>r*s){const t=Math.min(r*n/e,r*s/i);e*=t,i*=t}this._uiManager.enableWaiting(!1);const a=this.#El=document.createElement("canvas");a.setAttribute("role","img"),this.addContainer(a),this.width=e/n,this.height=i/s,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Bl(),this.#Ml||(this.parent.addUndoableEditor(this),this.#Ml=!0),this._reportTelemetry({action:"inserted_image"}),this.#Cl&&this.div.setAttribute("aria-description",this.#Cl),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")}copyCanvas(t,e,i=!1){t||(t=224);const{width:n,height:s}=this.#wl,r=new Yt;let a=this.#wl,o=n,l=s,h=null;if(e){if(n>e||s>e){const t=Math.min(e/n,e/s);o=Math.floor(n*t),l=Math.floor(s*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*r.sx),i=h.height=Math.ceil(l*r.sy);this.#Dl||(a=this.#Fl(t,i));const c=h.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":Qt.isDarkMode&&(d="#8f8f9d",u="#42414d");const p=15,g=p*r.sx,m=p*r.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=d,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),c.fillStyle=c.createPattern(f,"repeat"),c.fillRect(0,0,t,i),c.drawImage(a,0,0,a.width,a.height,0,0,t,i)}let c=null;if(i){let e,i;if(r.symmetric&&a.width<t&&a.height<t)e=a.width,i=a.height;else if(a=this.#wl,n>t||s>t){const r=Math.min(t/n,t/s);e=Math.floor(n*r),i=Math.floor(s*r),this.#Dl||(a=this.#Fl(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(a,0,0,a.width,a.height,0,0,e,i),c={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:c}}#Fl(t,e){const{width:i,height:n}=this.#wl;let s=i,r=n,a=this.#wl;for(;s>2*t||r>2*e;){const i=s,n=r;s>2*t&&(s=s>=16384?Math.floor(s/2)-1:Math.ceil(s/2)),r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const o=new OffscreenCanvas(s,r);o.getContext("2d").drawImage(a,0,0,i,n,0,0,s,r),a=o.transferToImageBitmap()}return a}#Bl(){const[t,e]=this.parentDimensions,{width:i,height:n}=this,s=new Yt,r=Math.ceil(i*t*s.sx),a=Math.ceil(n*e*s.sy),o=this.#El;if(!o||o.width===r&&o.height===a)return;o.width=r,o.height=a;const l=this.#Dl?this.#wl:this.#Fl(r,a),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter,h.drawImage(l,0,0,l.width,l.height,0,0,r,a)}#Ol(t){if(t){if(this.#Dl){const t=this._uiManager.imageManager.getSvgUrl(this.#xl);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#wl);return t.getContext("2d").drawImage(this.#wl,0,0),t.toDataURL()}if(this.#Dl){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*Bt.PDF_TO_CSS_UNITS),n=Math.round(this.height*e*Bt.PDF_TO_CSS_UNITS),s=new OffscreenCanvas(i,n);return s.getContext("2d").drawImage(this.#wl,0,0,this.#wl.width,this.#wl.height,0,0,i,n),s.transferToImageBitmap()}return structuredClone(this.#wl)}static async deserialize(t,e,i){let n=null,s=!1;if(t instanceof Ss){const{data:{rect:r,rotation:a,id:o,structParent:l,popupRef:h,richText:c,contentsObj:d,creationDate:u,modificationDate:p},container:g,parent:{page:{pageNumber:m}},canvas:f}=t;let b,v;f?(delete t.canvas,({id:b,bitmap:v}=i.imageManager.getFromCanvas(g.id,f)),f.remove()):(s=!0,t._hasNoCanvas=!0);const y=(await e._structTree.getAriaAttributes(`${Dt}${o}`))?.get("aria-label")||"";n=t={annotationType:F.STAMP,bitmapId:b,bitmap:v,pageIndex:m-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:y},isSvg:!1,structParent:l,popupRef:h,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const r=await super.deserialize(t,e,i),{rect:a,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:c,accessibilityData:d}=t;s?(i.addMissingCanvas(t.id,r),r.#Tl=!0):h&&i.imageManager.isValidId(h)?(r.#xl=h,o&&(r.#wl=o)):r.#_l=l,r.#Dl=c;const[u,p]=r.pageDimensions;return r.width=(a[2]-a[0])/u,r.height=(a[3]-a[1])/p,d&&(r.altTextData=d),r._initialData=n,t.comment&&r.setCommentData(t),r.#Ml=!!n,r}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:this.#xl,isSvg:this.#Dl});if(this.addComment(i),t)return i.bitmapUrl=this.#Ol(!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;const{decorative:n,altText:s}=this.serializeAltText(!1);if(!n&&s&&(i.accessibilityData={type:"Figure",alt:s}),this.annotationElementId){const t=this.#xa(i);return t.isSame?null:(t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1,i.id=this.annotationElementId,delete i.bitmapId,i)}if(null===e)return i;e.stamps||=new Map;const r=this.#Dl?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#xl)){if(this.#Dl){const t=e.stamps.get(this.#xl);r>t.area&&(t.area=r,t.serialized.bitmap.close(),t.serialized.bitmap=this.#Ol(!1))}}else e.stamps.set(this.#xl,{area:r,serialized:i}),i.bitmap=this.#Ol(!1);return i}#xa(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,n=t.pageIndex===e,s=(t.accessibilityData?.alt||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&n&&s,isSameAltText:s}}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}class Ks{#sa;#Nl=!1;#Ul=null;#jl=null;#zl=null;#Hl=new Map;#$l=!1;#Wl=!1;#Vl=!1;#Gl=null;#ql=null;#Xl=null;#Kl=null;#Yl=null;#Jl=-1;#b;static _initialized=!1;static#V=new Map([ks,Hs,Xs,Fs,qs].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:n,accessibilityManager:s,annotationLayer:r,drawLayer:a,textLayer:o,viewport:l,l10n:h}){const c=[...Ks.#V.values()];if(!Ks._initialized){Ks._initialized=!0;for(const e of c)e.initialize(h,t)}t.registerEditorTypes(c),this.#b=t,this.pageIndex=e,this.div=i,this.#sa=s,this.#Ul=r,this.viewport=l,this.#Xl=o,this.drawLayer=a,this._structTree=n,this.#b.addLayer(this)}get isEmpty(){return 0===this.#Hl.size}get isInvisible(){return this.isEmpty&&this.#b.getMode()===F.NONE}updateToolbar(t){this.#b.updateToolbar(t)}updateMode(t=this.#b.getMode()){switch(this.#Ql(),t){case F.NONE:return this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case F.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case F.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;if(e.toggle("nonEditing",!1),t===F.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const i of Ks.#V.values())e.toggle(`${i._type}Editing`,t===i._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#Xl?.div}setEditingState(t){this.#b.setEditingState(t)}addCommands(t){this.#b.addCommands(t)}cleanUndoStack(t){this.#b.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Ul?.div.classList.toggle("disabled",!t)}get#Zl(){return 0!==this.#Hl.size?this.#Hl.values():this.#b.getEditors(this.pageIndex)}async enable(){this.#Vl=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),this.#Yl?.abort(),this.#Yl=null;const t=new Set;for(const e of this.#Zl)e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#b.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));const e=this.#Ul;if(e)for(const i of e.getEditableAnnotations()){if(i.hide(),this.#b.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}this.#Vl=!1,this.#b._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#Wl=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),this.#Xl&&!this.#Yl){this.#Yl=new AbortController;const t=this.#b.combinedSignal(this.#Yl);this.#Xl.div.addEventListener("pointerdown",t=>{const{clientX:e,clientY:i,timeStamp:n}=t;if(n-this.#Jl>500)return void(this.#Jl=n);this.#Jl=-1;const{classList:s}=this.div;s.toggle("getElements",!0);const r=document.elementsFromPoint(e,i);if(s.toggle("getElements",!1),!this.div.contains(r[0]))return;let a;const o=new RegExp(`^${B}[0-9]+$`);for(const t of r)if(o.test(t.id)){a=t.id;break}if(!a)return;const l=this.#Hl.get(a);null===l?.annotationElementId&&(t.stopPropagation(),t.preventDefault(),l.dblclick(t))},{signal:t,capture:!0})}const t=this.#Ul;if(t){const e=new Map,i=new Map;for(const n of this.#Zl)n.disableEditing(),n.annotationElementId?null===n.serialize()?(i.set(n.annotationElementId,n),this.getEditableAnnotation(n.annotationElementId)?.show(),n.remove()):e.set(n.annotationElementId,n):n.updateFakeAnnotationElement(t);const n=t.getEditableAnnotations();for(const t of n){const{id:n}=t.data;if(this.#b.isDeletedAnnotationElement(n)){t.updateEdited({deleted:!0});continue}let s=i.get(n);s?(s.resetAnnotationElement(t),s.show(!1),t.show()):(s=e.get(n),s&&(this.#b.addChangedExistingAnnotation(s),s.renderAnnotationElement(t)&&s.show(!1)),t.show())}}this.#Ql(),this.isEmpty&&(this.div.hidden=!0);const{classList:e}=this.div;for(const t of Ks.#V.values())e.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#Wl=!1}getEditableAnnotation(t){return this.#Ul?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#b.getActive()!==t&&this.#b.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#Xl?.div&&!this.#Kl){this.#Kl=new AbortController;const t=this.#b.combinedSignal(this.#Kl);this.#Xl.div.addEventListener("pointerdown",this.#th.bind(this),{signal:t}),this.#Xl.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#Xl?.div&&this.#Kl&&(this.#Kl.abort(),this.#Kl=null,this.#Xl.div.classList.remove("highlighting"))}#th(t){this.#b.unselectAll();const{target:e}=t;if(e===this.#Xl.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Xl.div.contains(e)){const{isMac:e}=_t.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#b.showAllEditors("highlight",!0,!0),this.#Xl.div.classList.add("free"),this.toggleDrawing(),Fs.startHighlighting(this,"ltr"===this.#b.direction,{target:this.#Xl.div,x:t.x,y:t.y}),this.#Xl.div.addEventListener("pointerup",()=>{this.#Xl.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#b._signal}),t.preventDefault()}}enableClick(){if(this.#jl)return;this.#jl=new AbortController;const t=this.#b.combinedSignal(this.#jl);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#jl?.abort(),this.#jl=null}attach(t){this.#Hl.set(t.id,t);const{annotationElementId:e}=t;e&&this.#b.isDeletedAnnotationElement(e)&&this.#b.removeDeletedAnnotationElement(t)}detach(t){this.#Hl.delete(t.id),this.#sa?.removePointerInTextLayer(t.contentDiv),!this.#Wl&&t.annotationElementId&&this.#b.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#b.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#b.addDeletedAnnotationElement(t.annotationElementId),be.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(t.parent!==this||!t.isAttachedToDOM){if(this.changeParent(t),this.#b.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#Vl),this.#b.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#zl&&(t._focusEventsAllowed=!1,this.#zl=setTimeout(()=>{this.#zl=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#b._signal}),e.focus())},0)),t._structTreeParentId=this.#sa?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getEditorByUID(t){for(const e of this.#Hl.values())if(e.uid===t)return e;return null}getNextId(){return this.#b.getId()}get#eh(){return Ks.#V.get(this.#b.getMode())}combinedSignal(t){return this.#b.combinedSignal(t)}#ih(t){const e=this.#eh;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#eh?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t),await this.#b.updateMode(t.mode);const{offsetX:i,offsetY:n}=this.#nh(),s=this.getNextId(),r=this.#ih({parent:this,id:s,x:i,y:n,uiManager:this.#b,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await(Ks.#V.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#b))||null}createAndAddNewEditor(t,e,i={}){const n=this.getNextId(),s=this.#ih({parent:this,id:n,x:t.offsetX,y:t.offsetY,uiManager:this.#b,isCentered:e,...i});return s&&this.add(s),s}get boundingClientRect(){return this.div.getBoundingClientRect()}#nh(){const{x:t,y:e,width:i,height:n}=this.boundingClientRect,s=Math.max(0,t),r=Math.max(0,e),a=(s+Math.min(window.innerWidth,t+i))/2-t,o=(r+Math.min(window.innerHeight,e+n))/2-e,[l,h]=this.viewport.rotation%180==0?[a,o]:[o,a];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#nh(),!0,t)}setSelected(t){this.#b.setSelected(t)}toggleSelected(t){this.#b.toggleSelected(t)}unselect(t){this.#b.unselect(t)}pointerup(t){const{isMac:e}=_t.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#$l)return;if(this.#$l=!1,this.#eh?.isDrawer&&this.#eh.supportMultipleDrawings)return;if(!this.#Nl)return void(this.#Nl=!0);const i=this.#b.getMode();i!==F.STAMP&&i!==F.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#b.unselectAll()}pointerdown(t){if(this.#b.getMode()===F.HIGHLIGHT&&this.enableTextSelection(),this.#$l)return void(this.#$l=!1);const{isMac:e}=_t.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(this.#$l=!0,this.#eh?.isDrawer)return void this.startDrawingSession(t);const i=this.#b.getActive();this.#Nl=!i||i.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#Gl)return void this.#eh.startDrawing(this,this.#b,!1,t);this.#b.setCurrentDrawingSession(this),this.#Gl=new AbortController;const e=this.#b.combinedSignal(this.#Gl);this.div.addEventListener("blur",({relatedTarget:t})=>{t&&!this.div.contains(t)&&(this.#ql=null,this.commitOrRemove())},{signal:e}),this.#eh.startDrawing(this,this.#b,!1,t)}pause(t){if(t){const{activeElement:t}=document;return void(this.div.contains(t)&&(this.#ql=t))}this.#ql&&setTimeout(()=>{this.#ql?.focus(),this.#ql=null},0)}endDrawingSession(t=!1){return this.#Gl?(this.#b.setCurrentDrawingSession(null),this.#Gl.abort(),this.#Gl=null,this.#ql=null,this.#eh.endDrawing(t)):null}findNewParent(t,e,i){const n=this.#b.findParent(e,i);return null!==n&&n!==this&&(n.changeParent(t),!0)}commitOrRemove(){return!!this.#Gl&&(this.endDrawingSession(),!0)}onScaleChanging(){this.#Gl&&this.#eh.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#b.getActive()?.parent===this&&(this.#b.commitOrRemove(),this.#b.setActiveEditor(null)),this.#zl&&(clearTimeout(this.#zl),this.#zl=null);for(const t of this.#Hl.values())this.#sa?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Hl.clear(),this.#b.removeLayer(this)}#Ql(){for(const t of this.#Hl.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,Kt(this.div,t);for(const t of this.#b.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#b.commitOrRemove(),this.#Ql();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,Kt(this.div,{rotation:i}),e!==i)for(const t of this.#Hl.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#b.viewParameters.realScale}}class Ys{#kr=null;#sh=new Map;#rh=new Map;static#x=0;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#kr){if(this.#kr!==t){if(this.#sh.size>0)for(const e of this.#sh.values())e.remove(),t.append(e);this.#kr=t}}else this.#kr=t}static get _svgFactory(){return pt(this,"_svgFactory",new Kn)}static#ah(t,[e,i,n,s]){const{style:r}=t;r.top=100*i+"%",r.left=100*e+"%",r.width=100*n+"%",r.height=100*s+"%"}#oh(){const t=Ys._svgFactory.create(1,1,!0);return this.#kr.append(t),t.setAttribute("aria-hidden",!0),t}#lh(t,e){const i=Ys._svgFactory.createElement("clipPath");t.append(i);const n=`clip_${e}`;i.setAttribute("id",n),i.setAttribute("clipPathUnits","objectBoundingBox");const s=Ys._svgFactory.createElement("use");return i.append(s),s.setAttribute("href",`#${e}`),s.classList.add("clip"),n}#hh(t,e){for(const[i,n]of Object.entries(e))null===n?t.removeAttribute(i):t.setAttribute(i,n)}draw(t,e=!1,i=!1){const n=Ys.#x++,s=this.#oh(),r=Ys._svgFactory.createElement("defs");s.append(r);const a=Ys._svgFactory.createElement("path");r.append(a);const o=`path_p${this.pageIndex}_${n}`;a.setAttribute("id",o),a.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#rh.set(n,a);const l=i?this.#lh(r,o):null,h=Ys._svgFactory.createElement("use");return s.append(h),h.setAttribute("href",`#${o}`),this.updateProperties(s,t),this.#sh.set(n,s),{id:n,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=Ys.#x++,n=this.#oh(),s=Ys._svgFactory.createElement("defs");n.append(s);const r=Ys._svgFactory.createElement("path");s.append(r);const a=`path_p${this.pageIndex}_${i}`;let o;if(r.setAttribute("id",a),r.setAttribute("vector-effect","non-scaling-stroke"),e){const t=Ys._svgFactory.createElement("mask");s.append(t),o=`mask_p${this.pageIndex}_${i}`,t.setAttribute("id",o),t.setAttribute("maskUnits","objectBoundingBox");const e=Ys._svgFactory.createElement("rect");t.append(e),e.setAttribute("width","1"),e.setAttribute("height","1"),e.setAttribute("fill","white");const n=Ys._svgFactory.createElement("use");t.append(n),n.setAttribute("href",`#${a}`),n.setAttribute("stroke","none"),n.setAttribute("fill","black"),n.setAttribute("fill-rule","nonzero"),n.classList.add("mask")}const l=Ys._svgFactory.createElement("use");n.append(l),l.setAttribute("href",`#${a}`),o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();return n.append(h),l.classList.add("mainOutline"),h.classList.add("secondaryOutline"),this.updateProperties(n,t),this.#sh.set(i,n),i}finalizeDraw(t,e){this.#rh.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:n,rootClass:s,path:r}=e,a="number"==typeof t?this.#sh.get(t):t;if(a){if(i&&this.#hh(a,i),n&&Ys.#ah(a,n),s){const{classList:t}=a;for(const[e,i]of Object.entries(s))t.toggle(e,i)}if(r){const t=a.firstChild.firstChild;this.#hh(t,r)}}}updateParent(t,e){if(e===this)return;const i=this.#sh.get(t);i&&(e.#kr.append(i),this.#sh.delete(t),e.#sh.set(t,i))}remove(t){this.#rh.delete(t),null!==this.#kr&&(this.#sh.get(t).remove(),this.#sh.delete(t))}destroy(){this.#kr=null;for(const t of this.#sh.values())t.remove();this.#sh.clear(),this.#rh.clear()}}globalThis._pdfjsTestingUtils={HighlightOutliner:Is},globalThis.pdfjsLib={AbortException:wt,AnnotationEditorLayer:Ks,AnnotationEditorParamsType:O,AnnotationEditorType:F,AnnotationEditorUIManager:pe,AnnotationLayer:Es,AnnotationMode:L,AnnotationType:V,applyOpacity:function(t,e,i,n){const s=255*(1-(n=Math.min(Math.max(n??1,0),1)));return[t=Math.round(t*n+s),e=Math.round(e*n+s),i=Math.round(i*n+s)]},build:"f56dc8601",ColorPicker:$n,createValidAbsoluteUrl:dt,CSSConstants:class{static get commentForegroundColor(){const t=document.createElement("span");t.classList.add("comment","sidebar");const{style:e}=t;e.width=e.height="0",e.display="none",e.color="var(--comment-fg-color)",document.body.append(t);const{color:i}=window.getComputedStyle(t);return t.remove(),pt(this,"commentForegroundColor",Gt(i))}},DOMSVGFactory:Kn,DrawLayer:Ys,FeatureTest:_t,fetchData:Ft,findContrastColor:function(t,e){const i=t[0]+256*t[1]+65536*t[2]+16777216*e[0]+4294967296*e[1]+1099511627776*e[2];let n=ne.get(i);if(n)return n;const s=new Float32Array(9),r=s.subarray(0,3),a=s.subarray(3,6);Zt(t,a);const o=s.subarray(6,9);Zt(e,o);const l=o[2]<.5,h=l?12:4.5;if(a[2]=l?Math.sqrt(a[2]):1-Math.sqrt(1-a[2]),ie(a,o,r)<h){let t,e;l?(t=a[2],e=1):(t=0,e=a[2]);const i=.005;for(;e-t>i;){const i=a[2]=(t+e)/2;l===ie(a,o,r)<h?t=i:e=i}a[2]=l?e:t}return te(a,r),n=Ct.makeHexColor(Math.round(255*r[0]),Math.round(255*r[1]),Math.round(255*r[2])),ne.set(i,n),n},getDocument:Ln,getFilenameFromUrl:function(t){return[t]=t.split(/[#?]/,1),t.substring(t.lastIndexOf("/")+1)},getPdfFilenameFromUrl:function(t,e="document.pdf"){if("string"!=typeof t)return e;if(Ut(t))return lt('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;const i=(t=>{try{return new URL(t)}catch{try{return new URL(decodeURIComponent(t))}catch{try{return new URL(t,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(t),"https://foo.bar")}catch{return null}}}}})(t);if(!i)return e;const n=t=>{try{let e=decodeURIComponent(t);return e.includes("/")?(e=e.split("/").at(-1),e.test(/^\.pdf$/i)?e:t):e}catch{return t}},s=/\.pdf$/i,r=i.pathname.split("/").at(-1);if(s.test(r))return n(r);if(i.searchParams.size>0){const t=Array.from(i.searchParams.values()).reverse();for(const e of t)if(s.test(e))return n(e);const e=Array.from(i.searchParams.keys()).reverse();for(const t of e)if(s.test(t))return n(t)}if(i.hash){const t=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(i.hash);if(t)return n(t[0])}return e},getRGB:Gt,getUuid:kt,getXfaPageViewport:function(t,{scale:e=1,rotation:i=0}){const{width:n,height:s}=t.attributes.style,r=[0,0,parseInt(n),parseInt(s)];return new Ot({viewBox:r,userUnit:1,scale:e,rotation:i})},GlobalWorkerOptions:sn,ImageKind:W,InvalidPDFException:bt,isDataScheme:Ut,isPdfFile:jt,isValidExplicitDest:Me,MathClamp:Mt,noContextMenu:$t,normalizeUnicode:function(t){return Et||(Et=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,Tt=new Map([["ſt","ſt"]])),t.replaceAll(Et,(t,e,i)=>e?e.normalize("NFKC"):Tt.get(i))},OPS:Q,OutputScale:Yt,PasswordResponses:nt,PDFDataRangeTransport:Fn,PDFDateString:Vt,PDFWorker:Un,PermissionFlag:{PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},PixelsPerInch:Bt,RenderingCancelledException:Nt,renderRichText:se,ResponseException:vt,setLayerDimensions:Kt,shadow:pt,SignatureExtractor:Ws,stopEvent:Wt,SupportedImageMimeTypes:Jt,TextLayer:Rn,TouchManager:fe,updateUrlHash:ut,Util:Ct,VerbosityLevel:J,version:"5.4.296",XfaLayer:Rt};var Js="Invariant failed";function Qs(t,e){if(!t)throw new Error(Js)}d();const Zs=(0,g.createContext)(null);class tr{constructor(){this.externalLinkEnabled=!0,this.externalLinkRel=void 0,this.externalLinkTarget=void 0,this.isInPresentationMode=!1,this.pdfDocument=void 0,this.pdfViewer=void 0}setDocument(t){this.pdfDocument=t}setViewer(t){this.pdfViewer=t}setExternalLinkRel(t){this.externalLinkRel=t}setExternalLinkTarget(t){this.externalLinkTarget=t}setHash(){}setHistory(){}get pagesCount(){return this.pdfDocument?this.pdfDocument.numPages:0}get page(){return Qs(this.pdfViewer),this.pdfViewer.currentPageNumber||0}set page(t){Qs(this.pdfViewer),this.pdfViewer.currentPageNumber=t}get rotation(){return 0}set rotation(t){}addLinkAttributes(t,e,i){t.href=e,t.rel=this.externalLinkRel||"noopener noreferrer nofollow",t.target=i?"_blank":this.externalLinkTarget||""}goToDestination(t){return new Promise(e=>{Qs(this.pdfDocument),Qs(t),"string"==typeof t?this.pdfDocument.getDestination(t).then(e):Array.isArray(t)?e(t):t.then(e)}).then(t=>{Qs(Array.isArray(t));const e=t[0];new Promise(t=>{Qs(this.pdfDocument),e instanceof Object?this.pdfDocument.getPageIndex(e).then(e=>{t(e)}).catch(()=>{Qs(!1)}):"number"==typeof e?t(e):Qs(!1)}).then(e=>{const i=e+1;Qs(this.pdfViewer),Qs(i>=1&&i<=this.pagesCount),this.pdfViewer.scrollPageIntoView({dest:t,pageIndex:e,pageNumber:i})})})}goToPage(t){const e=t-1;Qs(this.pdfViewer),Qs(t>=1&&t<=this.pagesCount),this.pdfViewer.scrollPageIntoView({pageIndex:e,pageNumber:t})}goToXY(){}cachePageRef(){}getDestinationHash(){return"#"}getAnchorUrl(){return"#"}executeNamedAction(){}executeSetOCGState(){}isPageVisible(){return!0}isPageCached(){return!0}navigateTo(t){this.goToDestination(t)}}function er({children:t,type:e}){return(0,p.jsx)("div",{className:`react-pdf__message react-pdf__message--${e}`,children:t})}const ir={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};function nr(t,e){switch(e.type){case"RESOLVE":return{value:e.value,error:void 0};case"REJECT":return{value:!1,error:e.error};case"RESET":return{value:void 0,error:void 0};default:return t}}function sr(){return(0,g.useReducer)(nr,{value:void 0,error:void 0})}const rr="undefined"!=typeof window,ar=rr&&"file:"===window.location.protocol;function or(t){return void 0!==t}function lr(t){return or(t)&&null!==t}function hr(t){return function(t){return"string"==typeof t}(t)&&/^data:/.test(t)}function cr(t){Qs(hr(t));const[e="",i=""]=t.split(",");return-1!==e.split(";").indexOf("base64")?atob(i):unescape(i)}function dr(){return rr&&window.devicePixelRatio||1}const ur="On Chromium based browsers, you can use --allow-file-access-from-files flag for debugging purposes.";function pr(){d()(!ar,`Loading PDF as base64 strings/URLs may not work on protocols other than HTTP/HTTPS. ${ur}`)}function gr(t){(null==t?void 0:t.cancel)&&t.cancel()}function mr(t,e){return Object.defineProperty(t,"width",{get(){return this.getViewport({scale:e}).width},configurable:!0}),Object.defineProperty(t,"height",{get(){return this.getViewport({scale:e}).height},configurable:!0}),Object.defineProperty(t,"originalWidth",{get(){return this.getViewport({scale:1}).width},configurable:!0}),Object.defineProperty(t,"originalHeight",{get(){return this.getViewport({scale:1}).height},configurable:!0}),t}function fr(t){return"AbortException"===t.name||"RenderingCancelledException"===t.name}const{Tm:br}=u,vr=(t,e)=>{switch(e){case ir.NEED_PASSWORD:t(prompt("Enter the password to open this PDF file."));break;case ir.INCORRECT_PASSWORD:t(prompt("Invalid password. Please try again."));break}};function yr(t){return"object"==typeof t&&null!==t&&("data"in t||"range"in t||"url"in t)}const wr=(0,g.forwardRef)(function({children:t,className:e,error:i="Failed to load PDF file.",externalLinkRel:n,externalLinkTarget:s,file:r,inputRef:a,imageResourcesPath:o,loading:l="Loading PDF…",noData:h="No PDF file specified.",onItemClick:c,onLoadError:u,onLoadProgress:m,onLoadSuccess:b,onPassword:v=vr,onSourceError:x,onSourceSuccess:_,options:S,renderMode:C,rotate:E,scale:T,...k},D){const[M,P]=sr(),{value:I,error:R}=M,[L,B]=sr(),{value:F,error:O}=L,N=(0,g.useRef)(new tr),U=(0,g.useRef)([]),j=(0,g.useRef)(void 0),z=(0,g.useRef)(void 0);r&&r!==j.current&&yr(r)&&(d()(!y(r,j.current),'File prop passed to <Document /> changed, but it\'s equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "file" prop.'),j.current=r),S&&S!==z.current&&(d()(!y(S,z.current),'Options prop passed to <Document /> changed, but it\'s equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "options" prop.'),z.current=S);const H=(0,g.useRef)({scrollPageIntoView:t=>{const{dest:e,pageNumber:i,pageIndex:n=i-1}=t;if(c)return void c({dest:e,pageIndex:n,pageNumber:i});const s=U.current[n];s?s.scrollIntoView():d()(!1,`An internal link leading to page ${i} was clicked, but neither <Document> was provided with onItemClick nor it was able to find the page within itself. Either provide onItemClick to <Document> and handle navigating by yourself or ensure that all pages are rendered within <Document>.`)}});(0,g.useImperativeHandle)(D,()=>({linkService:N,pages:U,viewer:H}),[]),(0,g.useEffect)(function(){P({type:"RESET"})},[r,P]);const $=(0,g.useCallback)(async()=>{if(!r)return null;if("string"==typeof r){if(hr(r)){return{data:cr(r)}}return pr(),{url:r}}if(r instanceof br)return{range:r};if(r instanceof ArrayBuffer)return{data:r};if(rr&&function(t){return Qs(rr),t instanceof Blob}(r)){const t=await function(t){return new Promise((e,i)=>{const n=new FileReader;n.onload=()=>{if(!n.result)return i(new Error("Error while reading a file."));e(n.result)},n.onerror=t=>{if(!t.target)return i(new Error("Error while reading a file."));const{error:e}=t.target;if(!e)return i(new Error("Error while reading a file."));switch(e.code){case e.NOT_FOUND_ERR:return i(new Error("Error while reading a file: File not found."));case e.SECURITY_ERR:return i(new Error("Error while reading a file: Security error."));case e.ABORT_ERR:return i(new Error("Error while reading a file: Aborted."));default:return i(new Error("Error while reading a file."))}},n.readAsArrayBuffer(t)})}(r);return{data:t}}if(Qs("object"==typeof r),Qs(yr(r)),"url"in r&&"string"==typeof r.url){if(hr(r.url)){const{url:t,...e}=r;return{data:cr(t),...e}}pr()}return r},[r]);(0,g.useEffect)(()=>{const t=w($());return t.promise.then(t=>{P({type:"RESOLVE",value:t})}).catch(t=>{P({type:"REJECT",error:t})}),()=>{gr(t)}},[$,P]),(0,g.useEffect)(()=>{void 0!==I&&(!1!==I?_&&_():R&&(d()(!1,R.toString()),x&&x(R)))},[I]),(0,g.useEffect)(function(){B({type:"RESET"})},[B,I]),(0,g.useEffect)(function(){if(!I)return;const t=Ln(S?{...I,...S}:I);m&&(t.onProgress=m),v&&(t.onPassword=v);const e=t;return e.promise.then(t=>{e.destroyed||B({type:"RESOLVE",value:t})}).catch(t=>{e.destroyed||B({type:"REJECT",error:t})}),()=>{e.destroy(),B({type:"RESET"})}},[S,B,I]),(0,g.useEffect)(()=>{void 0!==F&&(!1!==F?F&&(b&&b(F),U.current=new Array(F.numPages),N.current.setDocument(F)):O&&(d()(!1,O.toString()),u&&u(O)))},[F]),(0,g.useEffect)(function(){N.current.setViewer(H.current),N.current.setExternalLinkRel(n),N.current.setExternalLinkTarget(s)},[n,s]);const W=(0,g.useCallback)((t,e)=>{U.current[t]=e},[]),V=(0,g.useCallback)(t=>{delete U.current[t]},[]),G=(0,g.useMemo)(()=>({imageResourcesPath:o,linkService:N.current,onItemClick:c,pdf:F,registerPage:W,renderMode:C,rotate:E,scale:T,unregisterPage:V}),[o,c,F,W,C,E,T,V]),q=(0,g.useMemo)(()=>A(k,()=>F),[k,F]);return(0,p.jsx)("div",{className:f("react-pdf__Document",e),ref:a,...q,children:r?null==F?(0,p.jsx)(er,{type:"loading",children:"function"==typeof l?l():l}):!1===F?(0,p.jsx)(er,{type:"error",children:"function"==typeof i?i():i}):function(){if(e=G,!Boolean(null==e?void 0:e.pdf))throw new Error("pdf is undefined");var e;const i="function"==typeof t?t(G):t;return(0,p.jsx)(Zs.Provider,{value:G,children:i})}():(0,p.jsx)(er,{type:"no-data",children:"function"==typeof h?h():h})})}),xr=n.p+"pdfjs/build/pdf.worker.min.mjs";function Ar(){return Ar.c||(Ar.c=n.n(r()))}function _r(){return _r.c||(_r.c=n.n(h()))}function Sr(){return Sr.c||(Sr.c=n.n(a()))}function Cr(){return Cr.c||(Cr.c=n.n(l()))}function Er(){return Er.c||(Er.c=n.n(o()))}function Tr(){return Tr.c||(Tr.c=n.n(c()))}r(),h(),a(),l(),o(),c();var kr=n(808),Dr={};Dr.styleTagTransform=Tr()(),Dr.setAttributes=Cr()(),Dr.insert=Sr()().bind(null,"head"),Dr.domAPI=_r()(),Dr.insertStyleElement=Er()();Ar()()(kr.A,Dr);kr.A&&kr.A.locals&&kr.A.locals;var Mr=n(810),Pr={};Pr.styleTagTransform=Tr()(),Pr.setAttributes=Cr()(),Pr.insert=Sr()().bind(null,"head"),Pr.domAPI=_r()(),Pr.insertStyleElement=Er()();Ar()()(Mr.A,Pr);Mr.A&&Mr.A.locals&&Mr.A.locals;var Ir=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const Rr=new URL("../",xr).toString(),Lr=t=>t.endsWith("/")?t:`${t}/`,Br=(t,e)=>{if(Object.is(t,e))return!0;if(!t||!e||"object"!=typeof t||"object"!=typeof e)return!1;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((t,i)=>Br(t,e[i]));const i=t,n=e,s=Object.keys(i);return s.length===Object.keys(n).length&&s.every(t=>Object.prototype.hasOwnProperty.call(n,t)&&Br(i[t],n[t]))},Fr=t=>{const e=(0,g.useRef)(t);return Br(e.current,t)||(e.current=t),e.current},Or=t=>`${Lr((null==t?void 0:t.trim())||Rr)}web/images/`,Nr=(t,e)=>{const i=e instanceof Error?e:new Error(String(e));return{stage:t,name:i.name,message:i.message}};let Ur=0;const jr=(t,e)=>(Ur=Math.max(Date.now(),Ur+1),{pageIndex:t,pageNumber:e,timestamp:Ur}),zr=t=>({pageNumber:t.pageNumber,width:t.width,height:t.height,originalWidth:t.originalWidth,originalHeight:t.originalHeight}),Hr=t=>{var{children:e,id:i,className:n,style:s,loading_state:r,containerRef:a,onScroll:o,setProps:l}=t,h=Ir(t,["children","id","className","style","loading_state","containerRef","onScroll","setProps"]);const c=(t=>{var e;const i=window.dash_component_api;return i?i.useDashContext().useLoading():null!==(e=null==t?void 0:t.is_loading)&&void 0!==e&&e})(r);return(0,p.jsx)("div",Object.assign({ref:a,onScroll:o},h,{id:i,className:n,style:s,"data-dash-is-loading":c||void 0,children:e}))},$r=(0,g.createContext)(null);var Wr=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const Vr=t=>{var{children:e,file:i=null,options:n={},assetBaseUrl:s,workerSrc:r,imageResourcesPath:a,externalLinkRel:o,externalLinkTarget:l,renderMode:h="canvas",rotate:c,scale:d=1,password:u,numPages:m,loadData:f,documentData:b,loadProgress:v,sourceLoaded:y,errorData:w,passwordData:x,itemClickData:A,error:_,noData:S,setProps:C,navigate:E}=t,T=Wr(t,["children","file","options","assetBaseUrl","workerSrc","imageResourcesPath","externalLinkRel","externalLinkTarget","renderMode","rotate","scale","password","numPages","loadData","documentData","loadProgress","sourceLoaded","errorData","passwordData","itemClickData","error","noData","setProps","navigate"]);const k=Fr(i),D=Fr(n),M=(0,g.useMemo)(()=>((t={},e,i)=>{const n=Lr((null==e?void 0:e.trim())||Rr);return sn.workerSrc=(null==i?void 0:i.trim())||(e?`${n}build/pdf.worker.min.mjs`:xr),Object.assign({cMapUrl:`${n}cmaps/`,cMapPacked:!0,standardFontDataUrl:`${n}standard_fonts/`,wasmUrl:`${n}wasm/`,iccUrl:`${n}iccs/`,isEvalSupported:!1},t)})(D,s,r),[D,s,r]),P=(0,g.useRef)(null),I=(0,g.useRef)(new Map),R=(0,g.useCallback)((t,e)=>(I.current.set(t,e),()=>{I.current.delete(t)}),[]),L=(0,g.useMemo)(()=>({registerPage:R}),[R]);(0,g.useEffect)(()=>{u&&P.current&&(P.current(u),P.current=null)},[u]),(0,g.useEffect)(()=>{null==C||C({numPages:null,loadData:null,documentData:null,loadProgress:null,sourceLoaded:!1,errorData:null,passwordData:null})},[k,D,s,r]);return(0,p.jsx)($r.Provider,{value:L,children:(0,p.jsx)(Hr,Object.assign({},T,{setProps:C,children:(0,p.jsx)(wr,{file:k,options:M,imageResourcesPath:a||Or(s),externalLinkRel:o,externalLinkTarget:l,renderMode:h,rotate:c,scale:d,loading:null,error:_,noData:S,onItemClick:({pageIndex:t,pageNumber:e})=>{const i=[...I.current.values()],n=i.find(t=>t.pageNumber===e);E?E(e):n?n.scrollIntoView():1===i.length&&i[0].setPageNumber(e),null==C||C({itemClickData:jr(t,e)})},onLoadProgress:t=>null==C?void 0:C({loadProgress:t}),onLoadSuccess:t=>{null==C||C({numPages:t.numPages,loadData:{numPages:t.numPages,fingerprints:[...t.fingerprints]},documentData:{numPages:t.numPages,fingerprints:[...t.fingerprints]},errorData:null,passwordData:null})},onLoadError:t=>null==C?void 0:C({numPages:null,errorData:Nr("document",t)}),onSourceSuccess:()=>null==C?void 0:C({sourceLoaded:!0}),onSourceError:t=>null==C?void 0:C({sourceLoaded:!1,errorData:Nr("source",t)}),onPassword:(t,e)=>{P.current=t,u&&e===nt.NEED_PASSWORD?(t(u),P.current=null):null==C||C({passwordData:{reason:e===nt.INCORRECT_PASSWORD?"incorrect-password":"need-password"}})},children:e})}))})},Gr=t=>(0,p.jsx)(Vr,Object.assign({},t)),qr=(0,g.createContext)(null);class Xr{constructor({num:t,gen:e}){this.num=t,this.gen=e}toString(){let t=`${this.num}R`;return 0!==this.gen&&(t+=this.gen),t}}function Kr(t){const e=(0,g.useRef)(void 0),i=e.current;return or(i)?()=>i:()=>{const i=t();return e.current=i,i}}function Yr(){return(0,g.useContext)(Zs)}function Jr(t){const e=Yr(),i=(0,g.useContext)(qr);Qs(i);const n={...e,...i,...t},{item:s,linkService:r,onItemClick:a,pdf:o,...l}=n;Qs(o);const h=Kr(()=>"string"==typeof s.dest?o.getDestination(s.dest):s.dest),c=Kr(async()=>{const t=await h();if(!t)throw new Error("Destination not found.");const[e]=t;return o.getPageIndex(new Xr(e))}),d=Kr(async()=>await c()+1);return(0,p.jsxs)("li",{children:[(0,p.jsx)("a",{href:"#",onClick:function(t){t.preventDefault(),Qs(a||r),a?Promise.all([h(),c(),d()]).then(([t,e,i])=>{a({dest:t,pageIndex:e,pageNumber:i})}):r&&r.goToDestination(s.dest)},children:s.title}),function(){var t;if(!(null===(t=s.items)||void 0===t?void 0:t.length))return null;const{items:e}=s;return(0,p.jsx)("ul",{children:e.map((t,e)=>(0,p.jsx)(Jr,{item:t,pdf:o,...l},"string"==typeof t.dest?t.dest:e))})}()]})}function Qr(t){const e={...Yr(),...t},{className:i,inputRef:n,onItemClick:s,onLoadError:r,onLoadSuccess:a,pdf:o,...l}=e;Qs(o);const[h,c]=sr(),{value:u,error:m}=h;(0,g.useEffect)(function(){c({type:"RESET"})},[c,o]),(0,g.useEffect)(function(){const t=w(o.getOutline()),e=t;return t.promise.then(t=>{c({type:"RESOLVE",value:t})}).catch(t=>{c({type:"REJECT",error:t})}),()=>gr(e)},[c,o]),(0,g.useEffect)(()=>{void 0!==u&&(!1!==u?void 0!==u&&!1!==u&&a&&a(u):m&&(d()(!1,m.toString()),r&&r(m)))},[u]);const b=(0,g.useMemo)(()=>({onItemClick:s}),[s]),v=(0,g.useMemo)(()=>A(l,()=>u),[l,u]);if(!u)return null;return(0,p.jsx)("div",{className:f("react-pdf__Outline",i),ref:n,...v,children:(0,p.jsx)(qr.Provider,{value:b,children:u?(0,p.jsx)("ul",{children:u.map((t,e)=>(0,p.jsx)(Jr,{item:t,pdf:o},"string"==typeof t.dest?t.dest:e))}):null})})}var Zr=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const ta=t=>Array.isArray(t)?t.map(t=>{const e=t;return{title:"string"==typeof e.title?e.title:"",bold:!0===e.bold,italic:!0===e.italic,url:"string"==typeof e.url?e.url:null,items:ta(e.items)||[]}}):null,ea=t=>{var{outlineData:e,itemClickData:i,errorData:n,setProps:s}=t,r=Zr(t,["outlineData","itemClickData","errorData","setProps"]);return(0,p.jsx)(Hr,Object.assign({},r,{setProps:s,children:(0,p.jsx)(Qr,{onItemClick:({pageIndex:t,pageNumber:e})=>null==s?void 0:s({itemClickData:jr(t,e)}),onLoadSuccess:t=>null==s?void 0:s({outlineData:ta(t),errorData:null}),onLoadError:t=>null==s?void 0:s({errorData:Nr("outline-load",t)})})}))},ia=t=>(0,p.jsx)(ea,Object.assign({},t)),na=(t,e,i)=>"all"===t?Array.from({length:i},(t,e)=>e+1):t?[...new Set(t)].filter(t=>Number.isInteger(t)&&t>=1&&t<=i):[e];function sa(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var i=t.filter(Boolean);return i.length<=1?i[0]||null:function(t){for(var e=0,n=i;e<n.length;e++){var s=n[e];"function"==typeof s?s(t):s&&(s.current=t)}}}const ra=(0,g.createContext)(null);function aa(){return(0,g.useContext)(ra)}function oa(){const t=Yr(),e=aa();Qs(e);const i={...t,...e},{filterAnnotations:n,imageResourcesPath:s,linkService:r,onGetAnnotationsError:a,onGetAnnotationsSuccess:o,onRenderAnnotationLayerError:l,onRenderAnnotationLayerSuccess:h,page:c,pdf:u,renderForms:m,rotate:b,scale:v=1}=i;Qs(u),Qs(c),Qs(r);const[y,x]=sr(),{value:A,error:_}=y,S=(0,g.useRef)(null);d()(1===Number.parseInt(window.getComputedStyle(document.body).getPropertyValue("--react-pdf-annotation-layer"),10),"AnnotationLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-annotations"),(0,g.useEffect)(function(){x({type:"RESET"})},[x,c]),(0,g.useEffect)(function(){if(!c)return;const t=w(c.getAnnotations()),e=t;return t.promise.then(t=>{x({type:"RESOLVE",value:t})}).catch(t=>{x({type:"REJECT",error:t})}),()=>{gr(e)}},[x,c]),(0,g.useEffect)(()=>{void 0!==A&&(!1!==A?A&&o&&o(A):_&&(d()(!1,_.toString()),a&&a(_)))},[A]);const C=(0,g.useMemo)(()=>c.getViewport({scale:v,rotation:b}),[c,b,v]);return(0,g.useEffect)(function(){if(!(u&&c&&r&&A))return;const{current:t}=S;if(!t)return;const e=C.clone({dontFlip:!0}),i={accessibilityManager:null,annotationCanvasMap:null,annotationEditorUIManager:null,annotationStorage:u.annotationStorage,commentManager:null,div:t,l10n:null,linkService:r,page:c,structTreeLayer:null,viewport:e},a={annotations:n?n({annotations:A}):A,annotationStorage:u.annotationStorage,div:t,imageResourcesPath:s,linkService:r,page:c,renderForms:m,viewport:e};t.innerHTML="";try{new Es(i).render(a),h&&h()}catch(t){!function(t){d()(!1,`${t}`),l&&l(t)}(t)}return()=>{}},[A,n,s,r,c,u,m,C]),(0,p.jsx)("div",{className:f("react-pdf__Page__annotations","annotationLayer"),ref:S})}const la={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},ha=/^H(\d+)$/;function ca(t){return"children"in t}function da(t){return!!ca(t)&&(1===t.children.length&&0 in t.children&&"id"in t.children[0])}function ua(t){const e={};if(ca(t)){const{role:i}=t,n=i.match(ha);if(n)e.role="heading",e["aria-level"]=Number(n[1]);else if(function(t){return t in la}(i)){const t=la[i];t&&(e.role=t)}}return e}function pa(t){const e={};if(ca(t)){if(void 0!==t.alt&&(e["aria-label"]=t.alt),void 0!==t.lang&&(e.lang=t.lang),da(t)){const[i]=t.children;if(i){const t=pa(i);return{...e,...t}}}}else"id"in t&&(e["aria-owns"]=t.id);return e}function ga({className:t,node:e}){const i=(0,g.useMemo)(()=>function(t){return t?{...ua(t),...pa(t)}:null}(e),[e]),n=(0,g.useMemo)(()=>ca(e)?da(e)?null:e.children.map((t,e)=>(0,p.jsx)(ga,{node:t},e)):null,[e]);return(0,p.jsx)("span",{className:t,...i,children:n})}function ma(){const t=aa();Qs(t);const{onGetStructTreeError:e,onGetStructTreeSuccess:i}=t,[n,s]=sr(),{value:r,error:a}=n,{customTextRenderer:o,page:l}=t;return(0,g.useEffect)(function(){s({type:"RESET"})},[s,l]),(0,g.useEffect)(function(){if(o)return;if(!l)return;const t=w(l.getStructTree()),e=t;return t.promise.then(t=>{s({type:"RESOLVE",value:t})}).catch(t=>{s({type:"REJECT",error:t})}),()=>gr(e)},[o,l,s]),(0,g.useEffect)(()=>{void 0!==r&&(!1!==r?r&&i&&i(r):a&&(d()(!1,a.toString()),e&&e(a)))},[r]),r?(0,p.jsx)(ga,{className:"react-pdf__Page__structTree structTree",node:r}):null}const fa=L;function ba(t){const e=aa();Qs(e);const i={...e,...t},{_className:n,canvasBackground:s,devicePixelRatio:r=dr(),onRenderError:a,onRenderSuccess:o,page:l,renderForms:h,renderTextLayer:c,pageColors:u,rotate:m,scale:f}=i,{canvasRef:b}=t;Qs(l);const v=(0,g.useRef)(null);function y(t){fr(t)||(d()(!1,t.toString()),a&&a(t))}const w=(0,g.useMemo)(()=>l.getViewport({scale:f*r,rotation:m}),[r,l,m,f]),x=(0,g.useMemo)(()=>l.getViewport({scale:f,rotation:m}),[l,m,f]);(0,g.useEffect)(function(){if(!l)return;l.cleanup();const{current:t}=v;if(!t)return;t.width=w.width,t.height=w.height,t.style.width=`${Math.floor(x.width)}px`,t.style.height=`${Math.floor(x.height)}px`,t.style.visibility="hidden";const e={annotationMode:h?fa.ENABLE_FORMS:fa.ENABLE,canvas:t,canvasContext:t.getContext("2d",{alpha:!1}),pageColors:u,viewport:w};s&&(e.background=s);const i=l.render(e),n=i;return i.promise.then(()=>{t.style.visibility="",l&&o&&o(mr(l,f))}).catch(y),()=>gr(n)},[s,l,u,h,w,x]);const A=(0,g.useCallback)(()=>{const{current:t}=v;t&&(t.width=0,t.height=0)},[]);return(0,g.useEffect)(()=>A,[A]),(0,p.jsx)("canvas",{className:`${n}__canvas`,dir:"ltr",ref:sa(b,v),style:{display:"block",userSelect:"none"},children:c?(0,p.jsx)(ma,{}):null})}const va=new Set(["base","embed","iframe","link","meta","object","script","style","template"]),ya=new Set(["action","formaction","href","poster","src","xlink:href"]);function wa(t){return function(t){return t.nodeType===Node.ELEMENT_NODE}(t)&&t instanceof HTMLElement}function xa(t){var e;return wa(t)&&!function(t){return wa(t)&&va.has(t.tagName.toLowerCase())}(t)?function(t){const e=document.createElement(t.tagName.toLowerCase());return Array.from(t.attributes).forEach(t=>{const i=t.name.toLowerCase();i.startsWith("on")||"srcdoc"===i||ya.has(i)&&function(t){let e="";for(const i of t){const t=i.charCodeAt(0);t<=32||127===t||(e+=i.toLowerCase())}return e.startsWith("data:")||e.startsWith("javascript:")||e.startsWith("vbscript:")}(t.value)||e.setAttribute(t.name,t.value)}),Array.from(t.childNodes).forEach(t=>{e.append(xa(t))}),e}(t):document.createTextNode(null!==(e=t.textContent)&&void 0!==e?e:"")}function Aa(){const t=aa();Qs(t);const{customTextRenderer:e,onGetTextError:i,onGetTextSuccess:n,onRenderTextLayerError:s,onRenderTextLayerSuccess:r,page:a,pageIndex:o,pageNumber:l,rotate:h,scale:c}=t;Qs(a);const[u,m]=sr(),{value:b,error:v}=u,y=(0,g.useRef)(null);d()(1===Number.parseInt(window.getComputedStyle(document.body).getPropertyValue("--react-pdf-text-layer"),10),"TextLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-text-layer"),(0,g.useEffect)(function(){m({type:"RESET"})},[a,m]),(0,g.useEffect)(function(){if(!a)return;const t=w(a.getTextContent()),e=t;return t.promise.then(t=>{m({type:"RESOLVE",value:t})}).catch(t=>{m({type:"REJECT",error:t})}),()=>gr(e)},[a,m]),(0,g.useEffect)(()=>{void 0!==b&&(!1!==b?b&&n&&n(b):v&&(d()(!1,v.toString()),i&&i(v)))},[b]);const x=(0,g.useCallback)(()=>{r&&r()},[r]),A=(0,g.useCallback)(t=>{fr(t)||(d()(!1,t.toString()),s&&s(t))},[s]);const _=(0,g.useMemo)(()=>a.getViewport({scale:c,rotation:h}),[a,h,c]);return(0,g.useLayoutEffect)(function(){if(!a||!b)return;const{current:t}=y;if(!t)return;t.innerHTML="";const i=a.streamTextContent({includeMarkedContent:!0}),n=new Rn({container:t,textContentSource:i,viewport:_}),s=n;return n.render().then(()=>{const i=document.createElement("div");i.className="endOfContent",t.append(i);const n=t.querySelectorAll('[role="presentation"]');if(e){let t=0;b.items.forEach((i,s)=>{if(!function(t){return"str"in t}(i))return;const r=n[t];if(!r)return;!function(t,e){const i=document.createElement("template");i.innerHTML=e;const n=document.createDocumentFragment();Array.from(i.content.childNodes).forEach(t=>{n.append(xa(t))}),t.replaceChildren(n)}(r,e({pageIndex:o,pageNumber:l,itemIndex:s,...i})),t+=i.str&&i.hasEOL?2:1})}x()}).catch(A),()=>gr(s)},[e,A,x,a,o,l,b,_]),(0,p.jsx)("div",{className:f("react-pdf__Page__textContent","textLayer"),onMouseUp:function(){const t=y.current;t&&t.classList.remove("selecting")},onMouseDown:function(){const t=y.current;t&&t.classList.add("selecting")},ref:y})}const _a=1;function Sa(t){const e={...Yr(),...t},{_className:i="react-pdf__Page",_enableRegisterUnregisterPage:n=!0,canvasBackground:s,canvasRef:r,children:a,className:o,customRenderer:l,customTextRenderer:h,devicePixelRatio:c,error:u="Failed to load the page.",filterAnnotations:m,height:b,inputRef:v,loading:y="Loading page…",noData:x="No page specified.",onGetAnnotationsError:_,onGetAnnotationsSuccess:S,onGetStructTreeError:C,onGetStructTreeSuccess:E,onGetTextError:T,onGetTextSuccess:k,onLoadError:D,onLoadSuccess:M,onRenderAnnotationLayerError:P,onRenderAnnotationLayerSuccess:I,onRenderError:R,onRenderSuccess:L,onRenderTextLayerError:B,onRenderTextLayerSuccess:F,pageColors:O,pageIndex:N,pageNumber:U,pdf:j,registerPage:z,renderAnnotationLayer:H=!0,renderForms:$=!1,renderMode:W="canvas",renderTextLayer:V=!0,rotate:G,scale:q=_a,unregisterPage:X,width:K,...Y}=e,[J,Q]=sr(),{value:Z,error:tt}=J,et=(0,g.useRef)(null);Qs(j);const it=lr(U)?U-1:null!=N?N:null,nt=null!=U?U:lr(N)?N+1:null,st=null!=G?G:Z?Z.rotate:null,rt=(0,g.useMemo)(()=>{if(!Z)return null;let t=1;const e=null!=q?q:_a;if(K||b){const e=Z.getViewport({scale:1,rotation:st});K?t=K/e.width:b&&(t=b/e.height)}return e*t},[b,Z,st,q,K]);(0,g.useEffect)(function(){return()=>{lr(it)&&n&&X&&X(it)}},[n,j,it,X]),(0,g.useEffect)(function(){Q({type:"RESET"})},[Q,j,it]),(0,g.useEffect)(function(){if(!j||!nt)return;const t=w(j.getPage(nt)),e=t;return t.promise.then(t=>{Q({type:"RESOLVE",value:t})}).catch(t=>{Q({type:"REJECT",error:t})}),()=>gr(e)},[Q,j,nt]),(0,g.useEffect)(()=>{void 0!==Z&&(!1!==Z?function(){if(M){if(!Z||!rt)return;M(mr(Z,rt))}if(n&&z){if(!lr(it)||!et.current)return;z(it,et.current)}}():tt&&(d()(!1,tt.toString()),D&&D(tt)))},[Z,rt]);const at=(0,g.useMemo)(()=>lr(it)&&nt&&lr(st)&&lr(rt)?{_className:i,canvasBackground:s,customTextRenderer:h,devicePixelRatio:c,filterAnnotations:m,onGetAnnotationsError:_,onGetAnnotationsSuccess:S,onGetStructTreeError:C,onGetStructTreeSuccess:E,onGetTextError:T,onGetTextSuccess:k,onRenderAnnotationLayerError:P,onRenderAnnotationLayerSuccess:I,onRenderError:R,onRenderSuccess:L,onRenderTextLayerError:B,onRenderTextLayerSuccess:F,page:Z,pageColors:O,pageIndex:it,pageNumber:nt,renderForms:$,renderTextLayer:V,rotate:st,scale:rt}:null,[i,s,h,c,m,_,S,C,E,T,k,P,I,R,L,B,F,Z,O,it,nt,$,V,st,rt]),ot=(0,g.useMemo)(()=>A(Y,()=>Z?rt?mr(Z,rt):void 0:Z),[Y,Z,rt]),lt=`${it}@${rt}/${st}`;function ht(){switch(W){case"custom":return Qs(l),(0,p.jsx)(l,{},`${lt}_custom`);case"none":return null;default:return(0,p.jsx)(ba,{canvasRef:r},`${lt}_canvas`)}}return(0,p.jsx)("div",{className:f(i,o),"data-page-number":nt,ref:sa(v,et),style:{"--scale-round-x":"1px","--scale-round-y":"1px","--scale-factor":"1","--user-unit":`${rt}`,"--total-scale-factor":"calc(var(--scale-factor) * var(--user-unit))",backgroundColor:s||"white",position:"relative",minWidth:"min-content",minHeight:"min-content"},...ot,children:nt?null===j||null==Z?(0,p.jsx)(er,{type:"loading",children:"function"==typeof y?y():y}):!1===j||!1===Z?(0,p.jsx)(er,{type:"error",children:"function"==typeof u?u():u}):function(){if(t=at,!Boolean(null==t?void 0:t.page))throw new Error("page is undefined");var t;const e="function"==typeof a?a(at):a;return(0,p.jsxs)(ra.Provider,{value:at,children:[ht(),V?(0,p.jsx)(Aa,{},`${lt}_text`):null,H?(0,p.jsx)(oa,{},`${lt}_annotations`):null,e]})}():(0,p.jsx)(er,{type:"no-data",children:"function"==typeof x?x():x})})}var Ca=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const Ea=t=>{var e,i,n,s,{children:r,canvasBackground:a,devicePixelRatio:o,height:l,imageResourcesPath:h,error:c,noData:d,pageColors:u,pageIndex:m,pageNumber:f,renderAnnotationLayer:b=!0,renderForms:v=!1,renderMode:y="canvas",renderTextLayer:w=!0,rotate:x,scale:A=1,width:_,loadData:S,pageData:C,renderData:E,errorData:T,annotationsData:k,textData:D,setProps:M,fit:P,fitSize:I}=t,R=Ca(t,["children","canvasBackground","devicePixelRatio","height","imageResourcesPath","error","noData","pageColors","pageIndex","pageNumber","renderAnnotationLayer","renderForms","renderMode","renderTextLayer","rotate","scale","width","loadData","pageData","renderData","errorData","annotationsData","textData","setProps","fit","fitSize"]);const[L,B]=(0,g.useState)(null),F=null==L?void 0:L.getViewport({scale:1,rotation:null!=x?x:L.rotate}),O=((t,e,i,n,s)=>{if(t&&!(e<=0))return"page"===t&&i>0&&n>0&&s>0?Math.min(e,i*n/s):e})(P,null!==(e=null==I?void 0:I.width)&&void 0!==e?e:0,null!==(i=null==I?void 0:I.height)&&void 0!==i?i:0,null!==(n=null==F?void 0:F.width)&&void 0!==n?n:0,null!==(s=null==F?void 0:F.height)&&void 0!==s?s:0),N=(0,g.useContext)($r),U=(0,g.useRef)(null),j=(0,g.useRef)(Symbol("pdf-page")),z=null!=f?f:(null!=m?m:0)+1;return(0,g.useEffect)(()=>{if(N)return N.registerPage(j.current,{pageNumber:z,setPageNumber:t=>null==M?void 0:M({pageNumber:t}),scrollIntoView:()=>{var t;return null===(t=U.current)||void 0===t?void 0:t.scrollIntoView()}})},[z,N,M]),(0,p.jsx)(Hr,Object.assign({},R,{setProps:M,children:(0,p.jsx)(Sa,{inputRef:U,canvasBackground:a,devicePixelRatio:o,height:P?void 0:l,imageResourcesPath:h,loading:null,error:c,noData:d,pageColors:u,pageIndex:m,pageNumber:f,renderAnnotationLayer:b,renderForms:v,renderMode:y,renderTextLayer:w,rotate:x,scale:A,width:P?O:_,onLoadSuccess:t=>{B(t),null==M||M({loadData:zr(t),pageData:zr(t),errorData:null})},onLoadError:t=>null==M?void 0:M({errorData:Nr("page-load",t)}),onRenderSuccess:t=>null==M?void 0:M({renderData:zr(t),errorData:null}),onRenderError:t=>null==M?void 0:M({errorData:Nr("page-render",t)}),onGetAnnotationsSuccess:t=>null==M?void 0:M({annotationsData:{pageNumber:z,layer:"annotations",count:t.length}}),onGetAnnotationsError:t=>null==M?void 0:M({errorData:Nr("annotations-load",t)}),onRenderAnnotationLayerError:t=>null==M?void 0:M({errorData:Nr("annotations-render",t)}),onGetTextSuccess:t=>null==M?void 0:M({textData:{pageNumber:z,layer:"text",count:t.items.length}}),onGetTextError:t=>null==M?void 0:M({errorData:Nr("text-load",t)}),onRenderTextLayerError:t=>null==M?void 0:M({errorData:Nr("text-render",t)}),children:r})}))};var Ta=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const ka=t=>{var{children:e,file:i=null,pageNumber:n=1,pages:s,fit:r,style:a,width:o,height:l,scale:h=1,rotate:c=0,renderTextLayer:d=!0,renderAnnotationLayer:u=!0,renderForms:m=!1,renderMode:f="canvas",canvasBackground:b,devicePixelRatio:v,pageColors:y,options:w={},assetBaseUrl:x,workerSrc:A,imageResourcesPath:_,externalLinkRel:S,externalLinkTarget:C,password:E,numPages:T,documentData:k,loadProgress:D,sourceLoaded:M,errorData:P,passwordData:I,itemClickData:R,pageData:L,renderData:B,annotationsData:F,textData:O,error:N,noData:U,loading_state:j,setProps:z}=t,H=Ta(t,["children","file","pageNumber","pages","fit","style","width","height","scale","rotate","renderTextLayer","renderAnnotationLayer","renderForms","renderMode","canvasBackground","devicePixelRatio","pageColors","options","assetBaseUrl","workerSrc","imageResourcesPath","externalLinkRel","externalLinkTarget","password","numPages","documentData","loadProgress","sourceLoaded","errorData","passwordData","itemClickData","pageData","renderData","annotationsData","textData","error","noData","loading_state","setProps"]);const $=Fr(i),W=Fr(null!=s?s:"all"===n?"all":void 0),[V,G]=(0,g.useState)("number"==typeof n?n:1),[q,X]=(0,g.useState)(0),K=(0,g.useRef)(null),Y=(0,g.useRef)(null),J=(0,g.useRef)(null),Q=(0,g.useRef)(new Set),Z=(0,g.useRef)(0),tt=((t,e)=>{const[i,n]=(0,g.useState)({width:0,height:0});return(0,g.useEffect)(()=>{const i=t.current;if(!i||!e)return;const s=()=>{const t=getComputedStyle(i),e=i.clientWidth-parseFloat(t.paddingLeft)-parseFloat(t.paddingRight),s=i.clientHeight-parseFloat(t.paddingTop)-parseFloat(t.paddingBottom);n(t=>t.width===e&&t.height===s?t:{width:e,height:s})};s();const r=new ResizeObserver(s);return r.observe(i),()=>r.disconnect()},[t,e]),i})(K,Boolean(r)),et=na(W,V,q),it=(0,g.useCallback)(t=>{const e=K.current,i=null==e?void 0:e.querySelector(`.react-pdf__Page[data-page-number="${t}"]`);if(!e||!i)return!1;const n=Array.from(e.querySelectorAll(".react-pdf__Page[data-page-number]")),s=n.indexOf(i);return!(s<0||!n.slice(0,s+1).every(t=>Q.current.has(Number(t.dataset.pageNumber))))&&(Z.current=Date.now()+250,e.scrollTop+=i.getBoundingClientRect().top-e.getBoundingClientRect().top-e.clientTop,!0)},[]);(0,g.useEffect)(()=>{"number"==typeof n&&(J.current!==n?(G(n),Y.current=W?n:null,W&&it(n)&&(Y.current=null)):J.current=null)},[n,W,it]),(0,g.useEffect)(()=>{Q.current.clear(),X(0)},[$]),(0,g.useEffect)(()=>{null!==Y.current&&it(Y.current)&&(Y.current=null)},[V,q,W,it]);const nt=(0,g.useCallback)(t=>{"number"!=typeof t||!Number.isInteger(t)||t<1||q>0&&t>q||W&&!na(W,t,q).includes(t)||(Y.current=W&&!it(t)?t:null,G(t),"all"!==n&&(null==z||z({pageNumber:t})))},[z,n,q,W,it]),st=(0,g.useCallback)(t=>{const{loadData:e,itemClickData:i}=t,n=Ta(t,["loadData","itemClickData"]),s=Object.assign({},n);"number"==typeof n.numPages?X(n.numPages):null===n.numPages&&(X(0),Object.assign(s,{pageData:null,renderData:null,annotationsData:null,textData:null})),void 0!==e&&(s.documentData=e),void 0!==i&&(s.itemClickData=i),Object.keys(s).length>0&&(null==z||z(s))},[z]),rt=(0,g.useCallback)(t=>{const{loadData:e,pageNumber:i}=t,n=Ta(t,["loadData","pageNumber"]);n.renderData&&(Q.current.add(n.renderData.pageNumber),null!==Y.current&&it(Y.current)&&(Y.current=null)),void 0!==e&&(n.pageData=e),void 0!==i&&nt(i),Object.keys(n).length>0&&(null==z||z(n))},[z,nt,it]);return(0,p.jsx)(Hr,Object.assign({},H,{loading_state:j,setProps:z,containerRef:K,style:Object.assign({maxWidth:"100%",overflow:"auto"},a),onScroll:()=>{const t=K.current;if(!t||!W||"all"===n||Date.now()<Z.current)return;const e=t.getBoundingClientRect().top+t.clientTop,i=Array.from(t.querySelectorAll(".react-pdf__Page[data-page-number]")).filter(i=>i.getBoundingClientRect().bottom>e&&i.getBoundingClientRect().top<e+t.clientHeight).reduce((t,i)=>!t||Math.abs(i.getBoundingClientRect().top-e)<Math.abs(t.getBoundingClientRect().top-e)?i:t,null),s=Number(null==i?void 0:i.dataset.pageNumber);s&&s!==V&&(J.current=s,G(s),null==z||z({pageNumber:s}))},children:(0,p.jsx)(Vr,{file:$,navigate:nt,options:w,assetBaseUrl:x,workerSrc:A,imageResourcesPath:_,externalLinkRel:S,externalLinkTarget:C,renderMode:f,password:E,error:N,noData:U,loading_state:j,setProps:st,children:et.map(t=>(0,p.jsx)(Ea,{pageNumber:t,width:o,fit:r,fitSize:tt,height:l,scale:h,rotate:c,renderTextLayer:d,renderAnnotationLayer:u,renderForms:m,renderMode:f,canvasBackground:b,devicePixelRatio:v,imageResourcesPath:_,pageColors:y,error:N,noData:U,setProps:rt,children:e},t))})}))},Da=t=>(0,p.jsx)(ka,Object.assign({},t)),Ma=t=>(0,p.jsx)(Ea,Object.assign({},t));function Pa(t){const e={...Yr(),...t},{className:i,linkService:n,onItemClick:s,pageIndex:r,pageNumber:a,pdf:o}=e;Qs(o);const l=lr(a)?a-1:null!=r?r:null,h=null!=a?a:lr(r)?r+1:null;const{className:c,onItemClick:d,...u}=t;return(0,p.jsx)("a",{className:f("react-pdf__Thumbnail",i),href:h?"#":void 0,onClick:function(t){t.preventDefault(),lr(l)&&h&&(Qs(s||n),s?s({pageIndex:l,pageNumber:h}):n&&n.goToPage(h))},children:(0,p.jsx)(Sa,{...u,_className:"react-pdf__Thumbnail__page",_enableRegisterUnregisterPage:!1,renderAnnotationLayer:!1,renderTextLayer:!1})})}var Ia=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const Ra=t=>{var{canvasBackground:e,devicePixelRatio:i,height:n,error:s,noData:r,pageColors:a,pageIndex:o,pageNumber:l,renderMode:h="canvas",rotate:c,scale:d=1,width:u,loadData:g,pageData:m,renderData:f,errorData:b,itemClickData:v,setProps:y}=t,w=Ia(t,["canvasBackground","devicePixelRatio","height","error","noData","pageColors","pageIndex","pageNumber","renderMode","rotate","scale","width","loadData","pageData","renderData","errorData","itemClickData","setProps"]);return(0,p.jsx)(Hr,Object.assign({},w,{setProps:y,children:(0,p.jsx)(Pa,{canvasBackground:e,devicePixelRatio:i,height:n,loading:null,error:s,noData:r,pageColors:a,pageIndex:o,pageNumber:l,renderMode:h,rotate:c,scale:d,width:u,onItemClick:({pageIndex:t,pageNumber:e})=>null==y?void 0:y({itemClickData:jr(t,e)}),onLoadSuccess:t=>null==y?void 0:y({loadData:zr(t),pageData:zr(t),errorData:null}),onLoadError:t=>null==y?void 0:y({errorData:Nr("thumbnail-load",t)}),onRenderSuccess:t=>null==y?void 0:y({renderData:zr(t),errorData:null}),onRenderError:t=>null==y?void 0:y({errorData:Nr("thumbnail-render",t)})})}))},La=t=>(0,p.jsx)(Ra,Object.assign({},t));return s})());
|