@bitcaster/printkit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -0
- package/README.md +8 -2
- package/README.npm.md +9 -0
- package/THIRD_PARTY_NOTICES.md +1973 -0
- package/dist/assets/fonts/C400.ttf +0 -0
- package/dist/assets/fonts/M400.ttf +0 -0
- package/dist/assets/fonts/M600.ttf +0 -0
- package/dist/assets/fonts/M700.ttf +0 -0
- package/dist/assets/fonts/OFL-IBMPlexMono.txt +93 -0
- package/dist/assets/fonts/OFL-LibreCaslonText.txt +93 -0
- package/dist/assets/fonts/OFL-Manrope.txt +93 -0
- package/dist/assets/fonts/P400.ttf +0 -0
- package/dist/assets/fonts/P500.ttf +0 -0
- package/dist/assets/pdf.worker.min.mjs +29 -0
- package/dist/components/index.d.ts +42 -0
- package/dist/components/index.js +1 -0
- package/dist/components/p-6By_vSL9.js +1 -0
- package/dist/components/p-B85ddf5i.js +58 -0
- package/dist/components/p-BEuF_WyR.js +15 -0
- package/dist/components/p-C06-VTon.js +1 -0
- package/dist/components/p-C5up7ejY.js +22 -0
- package/dist/components/p-ChB3W-Ln.js +3 -0
- package/dist/components/p-DpEO5JlK.js +2 -0
- package/dist/components/p-DzTdZECU.js +21 -0
- package/dist/components/pk-editor.d.ts +11 -0
- package/dist/components/pk-editor.js +277 -0
- package/dist/components/pk-help.d.ts +11 -0
- package/dist/components/pk-help.js +1 -0
- package/dist/components/pk-template-editor.d.ts +11 -0
- package/dist/components/pk-template-editor.js +1 -0
- package/dist/types/.stencil/components/pk-editor/pk-editor.d.ts +113 -0
- package/dist/types/.stencil/components/pk-help/help.content.d.ts +1 -0
- package/dist/types/.stencil/components/pk-help/pk-help.d.ts +9 -0
- package/dist/types/.stencil/components/pk-template-editor/pk-template-editor.d.ts +203 -0
- package/dist/types/.stencil/services/background-load.d.ts +20 -0
- package/dist/types/.stencil/services/background.d.ts +70 -0
- package/dist/types/.stencil/services/card-engine.d.ts +123 -0
- package/dist/types/.stencil/services/card-render.d.ts +5 -0
- package/dist/types/.stencil/services/card.config.d.ts +48 -0
- package/dist/types/.stencil/services/cmyk-lut.d.ts +4 -0
- package/dist/types/.stencil/services/collide.d.ts +19 -0
- package/dist/types/.stencil/services/color.d.ts +12 -0
- package/dist/types/.stencil/services/design.d.ts +106 -0
- package/dist/types/.stencil/services/fonts.d.ts +32 -0
- package/dist/types/.stencil/services/layouts.d.ts +15 -0
- package/dist/types/.stencil/services/logo.d.ts +19 -0
- package/dist/types/.stencil/services/palette.d.ts +31 -0
- package/dist/types/.stencil/services/pdf.d.ts +26 -0
- package/dist/types/.stencil/services/qr.d.ts +21 -0
- package/dist/types/.stencil/services/spot.d.ts +49 -0
- package/dist/types/.stencil/services/terms.d.ts +1 -0
- package/dist/types/.stencil/types/card.types.d.ts +403 -0
- package/dist/types/.stencil/types/editor.types.d.ts +48 -0
- package/dist/types/components.d.ts +320 -0
- package/dist/types/stencil-public-runtime.d.ts +1879 -0
- package/package.json +46 -4
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @licstart The following is the entire license notice for the
|
|
3
|
+
* JavaScript code in this page
|
|
4
|
+
*
|
|
5
|
+
* Copyright 2024 Mozilla Foundation
|
|
6
|
+
*
|
|
7
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
* you may not use this file except in compliance with the License.
|
|
9
|
+
* You may obtain a copy of the License at
|
|
10
|
+
*
|
|
11
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
*
|
|
13
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
* See the License for the specific language governing permissions and
|
|
17
|
+
* limitations under the License.
|
|
18
|
+
*
|
|
19
|
+
* @licend The above is the entire license notice for the
|
|
20
|
+
* JavaScript code in this page
|
|
21
|
+
*/
|
|
22
|
+
const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),s=[1/0,1/0,-1/0,-1/0],e=new Float32Array(s),i=[.001,0,0,.001,0,0],n="http://www.w3.org/2000/svg",r={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},o="pdfjs_internal_id_",h="pdfjs_internal_editor_",a={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},l={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},c={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},u={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},d={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,RICHMEDIA:27},f={ERRORS:0,WARNINGS:1,INFOS:5},p={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},g={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let m=f.WARNINGS;function A(t){Number.isInteger(t)&&(m=t)}function w(){return m}function b(t){m>=f.INFOS&&console.info(`Info: ${t}`)}function y(t){m>=f.WARNINGS&&console.warn(`Warning: ${t}`)}function v(t){throw new Error(t)}function x(t,s){t||v(s)}function M(t,s=null,e=null){if(!t)return null;if(e&&"string"==typeof t){if(e.addDefaultProtocol&&t.startsWith("www.")){const s=t.match(/\./g);s?.length>=2&&(t=`http://${t}`)}if(e.tryConvertEncoding)try{t=decodeURIComponent(escape(t))}catch{}}const i=s?URL.parse(t,s):URL.parse(t);return function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(i)?i:null}function k(t,s,e=!1){const i=URL.parse(t);return i?(i.hash=s,i.href):e&&M(t,"http://example.com")?t.split("#",1)[0]+""+(s?`#${s}`:""):""}function C(t){return t.substring(t.lastIndexOf("/")+1)}function S(t,s,e,i=!1){return Object.defineProperty(t,s,{value:e,enumerable:!i,configurable:!0,writable:!1}),e}const T=function(){function t(t,s){this.message=t,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class P extends T{constructor(t,s){super(t,"PasswordException"),this.code=s}}class E extends T{constructor(t,s){super(t,"UnknownErrorException"),this.details=s}}class D extends T{constructor(t){super(t,"InvalidPDFException")}}class N extends T{constructor(t,s,e){super(t,"ResponseException"),this.status=s,this.missing=e}}class I extends T{constructor(t){super(t,"FormatError")}}class F extends T{constructor(t){super(t,"AbortException")}}function _(t){"string"!=typeof t&&v("Invalid argument for stringToBytes");const s=t.length,e=new Uint8Array(s);for(let i=0;i<s;++i)e[i]=255&t.charCodeAt(i);return e}class R{static get isLittleEndian(){const t=new Uint8Array(4);return t[0]=1,S(this,"isLittleEndian",1===new Uint32Array(t.buffer,0,1)[0])}static get isOffscreenCanvasSupported(){return S(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return S(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return S(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return S(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:t,userAgent:s}=navigator;return S(this,"platform",{isAndroid:s.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:s.includes("Firefox")})}static get isCanvasFilterSupported(){let t;return this.isOffscreenCanvasSupported?t=new OffscreenCanvas(1,1).getContext("2d"):"undefined"!=typeof document&&(t=document.createElement("canvas").getContext("2d")),S(this,"isCanvasFilterSupported",void 0!==t?.filter)}static get isAlphaColorInputSupported(){if("undefined"==typeof document)return S(this,"isAlphaColorInputSupported",!1);const t=document.createElement("input");return t.type="color",t.setAttribute("alpha",""),t.value="#ff000080",S(this,"isAlphaColorInputSupported","#ff0000"!==t.value)}static get isBackdropFilterSupported(){return S(this,"isBackdropFilterSupported","undefined"!=typeof CSS&&CSS.supports("backdrop-filter","blur(1px)"))}}class O{static get hexNums(){return S(this,"hexNums",Array.from({length:256},((t,s)=>s.toString(16).padStart(2,"0"))))}static makeHexColor(t,s,e){return`#${this.hexNums[t]}${this.hexNums[s]}${this.hexNums[e]}`}static transform(t,s){return[t[0]*s[0]+t[2]*s[1],t[1]*s[0]+t[3]*s[1],t[0]*s[2]+t[2]*s[3],t[1]*s[2]+t[3]*s[3],t[0]*s[4]+t[2]*s[5]+t[4],t[1]*s[4]+t[3]*s[5]+t[5]]}static multiplyByDOMMatrix(t,s){return[t[0]*s.a+t[2]*s.b,t[1]*s.a+t[3]*s.b,t[0]*s.c+t[2]*s.d,t[1]*s.c+t[3]*s.d,t[0]*s.e+t[2]*s.f+t[4],t[1]*s.e+t[3]*s.f+t[5]]}static applyTransform(t,s,e=0){const i=t[e],n=t[e+1];t[e]=i*s[0]+n*s[2]+s[4],t[e+1]=i*s[1]+n*s[3]+s[5]}static applyTransformToBezier(t,s,e=0){const i=s[0],n=s[1],r=s[2],o=s[3],h=s[4],a=s[5];for(let s=0;s<6;s+=2){const l=t[e+s],c=t[e+s+1];t[e+s]=l*i+c*r+h,t[e+s+1]=l*n+c*o+a}}static applyInverseTransform(t,s){const e=t[0],i=t[1],n=s[0]*s[3]-s[1]*s[2];t[0]=(e*s[3]-i*s[2]+s[2]*s[5]-s[4]*s[3])/n,t[1]=(-e*s[1]+i*s[0]+s[4]*s[1]-s[5]*s[0])/n}static axialAlignedBoundingBox(t,s,e){const i=s[0],n=s[1],r=s[2],o=s[3],h=s[4],a=s[5],l=t[0],c=t[1],u=t[2],d=t[3];let f=i*l+h,p=f,g=i*u+h,m=g,A=o*c+a,w=A,b=o*d+a,y=b;if(0!==n||0!==r){const t=n*l,s=n*u,e=r*c,i=r*d;f+=e,m+=e,g+=i,p+=i,A+=t,y+=t,b+=s,w+=s}e[0]=Math.min(e[0],f,g,p,m),e[1]=Math.min(e[1],A,b,w,y),e[2]=Math.max(e[2],f,g,p,m),e[3]=Math.max(e[3],A,b,w,y)}static inverseTransform(t){const s=t[0]*t[3]-t[1]*t[2];return[t[3]/s,-t[1]/s,-t[2]/s,t[0]/s,(t[2]*t[5]-t[4]*t[3])/s,(t[4]*t[1]-t[5]*t[0])/s]}static singularValueDecompose2dScale(t,s){const e=t[0],i=t[1],n=t[2],r=t[3],o=e**2+i**2,h=n**2+r**2,a=(o+h)/2,l=Math.sqrt(a**2-(o*h-(e*n+i*r)**2));s[0]=Math.sqrt(a+l||1),s[1]=Math.sqrt(a-l||1)}static normalizeRect(t){const s=t.slice(0);return t[0]>t[2]&&(s[0]=t[2],s[2]=t[0]),t[1]>t[3]&&(s[1]=t[3],s[3]=t[1]),s}static intersect(t,s){const e=Math.max(Math.min(t[0],t[2]),Math.min(s[0],s[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(s[0],s[2]));if(e>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(s[1],s[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(s[1],s[3]));return n>r?null:[e,n,i,r]}static pointBoundingBox(t,s,e){e[0]=Math.min(e[0],t),e[1]=Math.min(e[1],s),e[2]=Math.max(e[2],t),e[3]=Math.max(e[3],s)}static rectBoundingBox(t,s,e,i,n){n[0]=Math.min(n[0],t,e),n[1]=Math.min(n[1],s,i),n[2]=Math.max(n[2],t,e),n[3]=Math.max(n[3],s,i)}static#t(t,s,e,i,n,r,o,h,a,l){if(a<=0||a>=1)return;const c=1-a,u=a*a,d=u*a,f=c*(c*(c*t+3*a*s)+3*u*e)+d*i,p=c*(c*(c*n+3*a*r)+3*u*o)+d*h;l[0]=Math.min(l[0],f),l[1]=Math.min(l[1],p),l[2]=Math.max(l[2],f),l[3]=Math.max(l[3],p)}static#s(t,s,e,i,n,r,o,h,a,l,c,u){if(Math.abs(a)<1e-12)return void(Math.abs(l)>=1e-12&&this.#t(t,s,e,i,n,r,o,h,-c/l,u));const d=l**2-4*c*a;if(d<0)return;const f=Math.sqrt(d),p=2*a;this.#t(t,s,e,i,n,r,o,h,(-l+f)/p,u),this.#t(t,s,e,i,n,r,o,h,(-l-f)/p,u)}static bezierBoundingBox(t,s,e,i,n,r,o,h,a){a[0]=Math.min(a[0],t,o),a[1]=Math.min(a[1],s,h),a[2]=Math.max(a[2],t,o),a[3]=Math.max(a[3],s,h),this.#s(t,e,n,o,s,i,r,h,3*(3*(e-n)-t+o),6*(t-2*e+n),3*(e-t),a),this.#s(t,e,n,o,s,i,r,h,3*(3*(i-r)-s+h),6*(s-2*i+r),3*(i-s),a)}}let B=null,$=null;function L(t){return B||(B=/([\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,$=new Map([["ſt","ſt"]])),t.replaceAll(B,((t,s,e)=>s?s.normalize("NFKC"):$.get(e)))}function U(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);return crypto.getRandomValues(t),function(t){"object"==typeof t&&void 0!==t?.length||v("Invalid argument for bytesToString");const s=t.length,e=8192;if(s<e)return String.fromCharCode.apply(null,t);const i=[];for(let n=0;n<s;n+=e){const r=Math.min(n+e,s),o=t.subarray(n,r);i.push(String.fromCharCode.apply(null,o))}return i.join("")}(t)}const j=()=>[],G=()=>new Map,z=()=>Object.create(null),H=()=>new Set;function W(t,s,e){return Math.min(Math.max(t,s),e)}"function"!=typeof Iterator.prototype.join&&(Iterator.prototype.join=function(t){return[...this].join(t)});class V{constructor({viewBox:t,userUnit:s,scale:e,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:o=!1}){this.viewBox=t,this.userUnit=s,this.scale=e,this.rotation=i,this.offsetX=n,this.offsetY=r,e*=s;const h=(t[2]+t[0])/2,a=(t[3]+t[1])/2;let l,c,u,d,f,p,g,m;switch((i%=360)<0&&(i+=360),i){case 180:l=-1,c=0,u=0,d=1;break;case 90:l=0,c=1,u=1,d=0;break;case 270:l=0,c=-1,u=-1,d=0;break;case 0:l=1,c=0,u=0,d=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}o&&(u=-u,d=-d),0===l?(f=Math.abs(a-t[1])*e+n,p=Math.abs(h-t[0])*e+r,g=(t[3]-t[1])*e,m=(t[2]-t[0])*e):(f=Math.abs(h-t[0])*e+n,p=Math.abs(a-t[1])*e+r,g=(t[2]-t[0])*e,m=(t[3]-t[1])*e),this.transform=[l*e,c*e,u*e,d*e,f-l*e*h-u*e*a,p-c*e*h-d*e*a],this.width=g,this.height=m}get rawDims(){const t=this.viewBox;return S(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:s=this.rotation,offsetX:e=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new V({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:s,offsetX:e,offsetY:i,dontFlip:n})}convertToViewportPoint(t,s){const e=[t,s];return O.applyTransform(e,this.transform),e}convertToPdfPoint(t,s){const e=[t,s];return O.applyInverseTransform(e,this.transform),e}}class X{static textContent(t){const s=[],e={items:s,styles:Object.create(null)};return function t(e){if(!e)return;let i=null;const n=e.name;if("#text"===n)i=e.value;else{if(!X.shouldBuildText(n))return;e?.attributes?.textContent?i=e.attributes.textContent:e.value&&(i=e.value)}if(null!==i&&s.push({str:i}),e.children)for(const s of e.children)t(s)}(t),e}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Y=/url\(|image-set\(/i,K=/^on/i;class q{static get _allowedHtmlElements(){return S(this,"_allowedHtmlElements",new Set(["a","b","br","button","div","i","img","input","label","li","ol","option","p","select","span","sub","sup","textarea","ul"]))}static get _allowedSvgElements(){return S(this,"_allowedSvgElements",new Set(["ellipse","line","path","rect","svg"]))}static get _allowedRichTextElements(){return S(this,"_allowedRichTextElements",new Set(["a","b","br","div","i","li","ol","p","span","sub","sup","ul"]))}static get _allowedRichTextAttributes(){return S(this,"_allowedRichTextAttributes",new Set(["class","dir","style"]))}static get _allowedRichTextStyles(){return S(this,"_allowedRichTextStyles",new Set(["color","font","fontFamily","fontSize","fontStretch","fontStyle","fontWeight","kerningMode","letterSpacing","lineHeight","margin","marginBottom","marginLeft","marginRight","marginTop","orphans","paddingLeft","paddingRight","breakAfter","breakBefore","breakInside","tabInterval","tabStop","textAlign","textDecoration","textIndent","transform","verticalAlign","widows"]))}static setupStorage(t,s,e,i,n){const r=i.getValue(s,{value:null});switch(e.name){case"textarea":if(null!==r.value&&(t.textContent=r.value),"print"===n)break;t.addEventListener("input",(t=>{i.setValue(s,{value:t.target.value})}));break;case"input":if("radio"===e.attributes.type||"checkbox"===e.attributes.type){if(r.value===e.attributes.xfaOn?t.setAttribute("checked",!0):r.value===e.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",(t=>{i.setValue(s,{value:t.target.getAttribute(t.target.checked?"xfaOn":"xfaOff")})}))}else{if(null!==r.value&&t.setAttribute("value",r.value),"print"===n)break;t.addEventListener("input",(t=>{i.setValue(s,{value:t.target.value})}))}break;case"select":if(null!==r.value){t.setAttribute("value",r.value);for(const t of e.children)t.attributes.value===r.value?t.attributes.selected=!0:Object.hasOwn(t.attributes,"selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const e=t.target.options;i.setValue(s,{value:-1===e.selectedIndex?"":e[e.selectedIndex].value})}))}}static setAttributes({html:t,element:s,storage:e=null,intent:i,linkService:n}){const{attributes:r}=s,o=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${i}`);for(const[s,e]of Object.entries(r))if(null!=e&&!K.test(s)&&("richText"!==i||this._allowedRichTextAttributes.has(s)))switch(s){case"class":e.length&&t.setAttribute(s,e.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",e);break;case"style":if("richText"===i){const s=this._allowedRichTextStyles;for(const[i,n]of Object.entries(e))s.has(i)&&!Y.test(n)&&(t.style[i]=n)}else Object.assign(t.style,e);break;case"textContent":t.textContent=e;break;default:(!o||"href"!==s&&"newWindow"!==s)&&t.setAttribute(s,e)}o&&n?.addLinkAttributes(t,r.href,r.newWindow),e&&r.dataId&&this.setupStorage(t,r.dataId,s,e)}static#e(t,s,e){return"richText"===e?!s&&this._allowedRichTextElements.has(t)?document.createElement(t):null:s?s===n&&this._allowedSvgElements.has(t)?document.createElementNS(n,t):null:this._allowedHtmlElements.has(t)?document.createElement(t):null}static render(t){const s=t.annotationStorage,e=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=this.#e(i.name,i.attributes?.xmlns,n)??document.createElement("div");i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:e});const o="richText"!==n,h=t.div;if(h.append(r),t.viewport){const s=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=s}o&&h.setAttribute("class","xfaLayer xfaFont");const a=[];if(0===i.children.length){if(i.value){const t=document.createTextNode(i.value);r.append(t),o&&X.shouldBuildText(i.name)&&a.push(t)}return{textDivs:a}}const l=[[i,-1,r]];for(;l.length>0;){const[t,i,r]=l.at(-1);if(i+1===t.children.length){l.pop();continue}const h=t.children[++l.at(-1)[1]];if(null===h)continue;const{name:c}=h;if("#text"===c){const t=document.createTextNode(h.value);a.push(t),r.append(t);continue}const u=this.#e(c,h.attributes?.xmlns,n);if(u)if(r.append(u),h.attributes&&this.setAttributes({html:u,element:h,storage:s,intent:n,linkService:e}),h.children?.length>0)l.push([h,-1,u]);else if(h.value){const t=document.createTextNode(h.value);o&&X.shouldBuildText(c)&&a.push(t),u.append(t)}}for(const t of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:a}}static update(t){const s=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=s,t.div.hidden=!1}static getPageViewport(t,{scale:s=1,rotation:e=0}){const{width:i,height:n}=t.attributes.style;return new V({viewBox:[0,0,parseInt(i,10),parseInt(n,10)],userUnit:1,scale:s,rotation:e})}}class Q{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function J(t,s="text"){if(rt(t,document.baseURI)){const e=await fetch(t);if(!e.ok)throw new Error(e.statusText);switch(s){case"blob":return e.blob();case"bytes":return e.bytes();case"json":return e.json()}return e.text()}return new Promise(((e,i)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType="bytes"===s?"arraybuffer":s,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)i(new Error(n.statusText));else{switch(s){case"bytes":return void e(new Uint8Array(n.response));case"blob":case"json":return void e(n.response)}e(n.responseText)}},n.send(null)}))}class Z extends T{constructor(t,s=0){super(t,"RenderingCancelledException"),this.extraDelay=s}}function tt(t){const s=t.length;let e=0;for(;e<s&&""===t[e].trim();)e++;return"data:"===t.substring(e,e+5).toLowerCase()}function st(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function et(t){return[t]=t.split(/[#?]/,1),C(t)}function it(t,s="document.pdf"){if("string"!=typeof t)return s;if(tt(t))return y('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),s;const e=(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(!e)return s;const i=t=>{try{let s=decodeURIComponent(t);return s.includes("/")&&(s=C(s),4===s.length&&n.test(s))?t:s}catch{return t}},n=/\.pdf$/i,r=C(e.pathname);if(n.test(r))return i(r);if(e.searchParams.size>0){const t=t=>[...t].findLast((t=>n.test(t))),s=t(e.searchParams.values())??t(e.searchParams.keys());if(s)return i(s)}if(e.hash){const{hash:t}=e;let s=-1;for(const{index:e}of t.matchAll(/\.pdf\b/gi))s=e;if(s>0){let e=s;for(;e>0&&!"/?#=".includes(t[e-1]);)e--;if(e<s)return i(t.slice(e,s+4))}}return s}class nt{#i=new Map;times=[];time(t){this.#i.has(t)&&y(`Timer is already running for ${t}`),this.#i.set(t,Date.now())}timeEnd(t){this.#i.has(t)||y(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.#i.get(t),end:Date.now()}),this.#i.delete(t)}toString(){const t=Math.max(...this.times.map((t=>t.name.length)));return this.times.map((s=>`${s.name.padEnd(t)} ${s.end-s.start}ms\n`)).join("")}}function rt(t,s){const e=s?URL.parse(t,s):URL.parse(t);return/https?:/.test(e?.protocol??"")}function ot(t){t.preventDefault()}function ht(t){t.preventDefault(),t.stopPropagation()}class at{static#n;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#n||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?");const s=this.#n.exec(t);if(!s)return null;const e=parseInt(s[1],10);let i=parseInt(s[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(s[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(s[4],10);r=r>=0&&r<=23?r:0;let o=parseInt(s[5],10);o=o>=0&&o<=59?o:0;let h=parseInt(s[6],10);h=h>=0&&h<=59?h:0;const a=s[7]||"Z";let l=parseInt(s[8],10);l=l>=0&&l<=23?l:0;let c=parseInt(s[9],10)||0;return c=c>=0&&c<=59?c:0,"-"===a?(r+=l,o+=c):"+"===a&&(r-=l,o-=c),new Date(Date.UTC(e,i,n,r,o,h))}}function lt(t){if(t.startsWith("#")){const s=t.slice(1);return[parseInt(s.slice(0,2),16),parseInt(s.slice(2,4),16),parseInt(s.slice(4,6),16),s.length>=8?parseInt(s.slice(6,8),16)/255:1]}if(t.startsWith("rgb(")){const[s,e,i]=t.slice(4,-1).split(",").map((t=>parseInt(t,10)));return[s,e,i,1]}if(t.startsWith("rgba(")){const s=t.slice(5,-1).split(",");return[parseInt(s[0],10),parseInt(s[1],10),parseInt(s[2],10),parseFloat(s[3])]}const s=t.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return s?[Math.round(255*parseFloat(s[1])),Math.round(255*parseFloat(s[2])),Math.round(255*parseFloat(s[3])),void 0!==s[4]&&"none"!==s[4]?parseFloat(s[4]):1]:null}function ct(t){const s=lt(t);return s?s.slice(0,3):(y(`Not a valid color format: "${t}"`),[0,0,0])}function ut(t){const{a:s,b:e,c:i,d:n,e:r,f:o}=t.getTransform();return[s,e,i,n,r,o]}function dt(t){const{a:s,b:e,c:i,d:n,e:r,f:o}=t.getTransform().invertSelf();return[s,e,i,n,r,o]}function ft(t,s,e=!1,i=!0){if(s instanceof V){const{pageWidth:i,pageHeight:n}=s.rawDims,{style:r}=t,o=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-x))`,h=`round(down, var(--total-scale-factor) * ${n}px, var(--scale-round-y))`;e&&s.rotation%180!=0?(r.width=h,r.height=o):(r.width=o,r.height=h)}i&&t.setAttribute("data-main-rotation",s.rotation)}class pt{constructor(){const{pixelRatio:t}=pt;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,s,e,i,n=-1){let r=1/0,o=1/0,h=1/0;(e=pt.capPixels(e,n))>0&&(r=Math.sqrt(e/(t*s))),-1!==i&&(o=i/t,h=i/s);const a=Math.min(r,o,h);return(this.sx>a||this.sy>a)&&(this.sx=a,this.sy=a,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,s){if(s>=0){const e=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+s/100));return t>0?Math.min(t,e):e}return t}}const gt=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class mt{static get isDarkMode(){return S(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}class At{static get commentForegroundColor(){const t=document.createElement("span");t.classList.add("comment","sidebar");const{style:s}=t;s.width=s.height="0",s.display="none",s.color="var(--comment-fg-color)",document.body.append(t);const{color:e}=window.getComputedStyle(t);return t.remove(),S(this,"commentForegroundColor",ct(e))}}function wt(t,s){const e=255*(1-(s=W(s??1,0,1)));return t.map((t=>Math.round(t*s+e)))}function bt(t,s){const e=t[0]/255,i=t[1]/255,n=t[2]/255,r=Math.max(e,i,n),o=Math.min(e,i,n),h=(r+o)/2;if(r===o)s[0]=s[1]=0;else{const t=r-o;switch(s[1]=h<.5?t/(r+o):t/(2-r-o),r){case e:s[0]=60*((i-n)/t+(i<n?6:0));break;case i:s[0]=60*((n-e)/t+2);break;case n:s[0]=60*((e-i)/t+4)}}s[2]=h}function yt(t,s){const e=t[0],i=t[1],n=t[2],r=(1-Math.abs(2*n-1))*i,o=r*(1-Math.abs(e/60%2-1)),h=n-r/2;switch(Math.floor(e/60)){case 0:s[0]=r+h,s[1]=o+h,s[2]=h;break;case 1:s[0]=o+h,s[1]=r+h,s[2]=h;break;case 2:s[0]=h,s[1]=r+h,s[2]=o+h;break;case 3:s[0]=h,s[1]=o+h,s[2]=r+h;break;case 4:s[0]=o+h,s[1]=h,s[2]=r+h;break;case 5:case 6:s[0]=r+h,s[1]=h,s[2]=o+h}}function vt(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function xt(t,s,e){yt(t,e),e.map(vt);const i=.2126*e[0]+.7152*e[1]+.0722*e[2];yt(s,e),e.map(vt);const n=.2126*e[0]+.7152*e[1]+.0722*e[2];return i>n?(i+.05)/(n+.05):(n+.05)/(i+.05)}const Mt=new Map;function kt(t,s){const e=t[0]+256*t[1]+65536*t[2]+16777216*s[0]+4294967296*s[1]+1099511627776*s[2];let i=Mt.get(e);if(i)return i;const n=new Float32Array(9),r=n.subarray(0,3),o=n.subarray(3,6);bt(t,o);const h=n.subarray(6,9);bt(s,h);const a=h[2]<.5,l=a?12:4.5;if(o[2]=a?Math.sqrt(o[2]):1-Math.sqrt(1-o[2]),xt(o,h,r)<l){let t,s;a?(t=o[2],s=1):(t=0,s=o[2]);const e=.005;for(;s-t>e;){const e=o[2]=(t+s)/2;a===xt(o,h,r)<l?t=e:s=e}o[2]=a?s:t}return yt(o,r),i=O.makeHexColor(Math.round(255*r[0]),Math.round(255*r[1]),Math.round(255*r[2])),Mt.set(e,i),i}function Ct({html:t,dir:s,className:e},i){const n=document.createDocumentFragment();if("string"==typeof t){const e=document.createElement("p");e.dir=s||"auto";const i=t.split(/\r\n?|\n/);for(let t=0,s=i.length;t<s;++t)e.append(document.createTextNode(i[t])),t<s-1&&e.append(document.createElement("br"));n.append(e)}else q.render({xfaHtml:t,div:n,intent:"richText"});n.firstElementChild.classList.add("richText",e),i.append(n)}function St(t){const s=new Path2D;if(!t)return s;for(let e=0,i=t.length;e<i;)switch(t[e++]){case 0:s.moveTo(t[e++],t[e++]);break;case 1:s.lineTo(t[e++],t[e++]);break;case 2:s.bezierCurveTo(t[e++],t[e++],t[e++],t[e++],t[e++],t[e++]);break;case 3:s.quadraticCurveTo(t[e++],t[e++],t[e++],t[e++]);break;case 4:s.closePath();break;default:y(`Unrecognized drawing path operator: ${t[e-1]}`)}return s}class Tt{#r=null;#o=null;#h;#a=null;#l=null;#c=null;#u=null;#d=null;static#f=null;constructor(t){this.#h=t,Tt.#f||=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.#r=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const s=this.#h._uiManager._signal;s instanceof AbortSignal&&!s.aborted&&(t.addEventListener("contextmenu",ot,{signal:s}),t.addEventListener("pointerdown",Tt.#p,{signal:s}));const e=this.#a=document.createElement("div");e.className="buttons",t.append(e);const i=this.#h.toolbarPosition;if(i){const{style:s}=t,e="ltr"===this.#h._uiManager.direction?1-i[0]:i[0];s.insetInlineEnd=100*e+"%",s.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#r}static#p(t){t.stopPropagation()}#g(t){this.#h._focusEventsAllowed=!1,ht(t)}#m(t){this.#h._focusEventsAllowed=!0,ht(t)}#A(t){const s=this.#h._uiManager._signal;return s instanceof AbortSignal&&!s.aborted&&(t.addEventListener("focusin",this.#g.bind(this),{capture:!0,signal:s}),t.addEventListener("focusout",this.#m.bind(this),{capture:!0,signal:s}),t.addEventListener("contextmenu",ot,{signal:s}),!0)}hide(){this.#r.classList.add("hidden"),this.#o?.hideDropdown()}show(){this.#r.classList.remove("hidden"),this.#l?.shown(),this.#c?.shown()}addDeleteButton(){const{editorType:t,_uiManager:s}=this.#h,e=document.createElement("button");e.classList.add("basic","deleteButton"),e.tabIndex=0,e.setAttribute("data-l10n-id",Tt.#f[t]),this.#A(e)&&e.addEventListener("click",(()=>{s.delete()}),{signal:s._signal}),this.#a.append(e)}get#w(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const s=await t.render();this.#A(s),this.#a.append(s,this.#w),this.#l=t}addComment(t,s=null){if(this.#c)return;const e=t.renderForToolbar();if(!e)return;this.#A(e);const i=this.#u=this.#w;s?(this.#a.insertBefore(e,s),this.#a.insertBefore(i,s)):this.#a.append(e,i),this.#c=t,t.toolbar=this}addColorPicker(t){if(this.#o)return;this.#o=t;const s=t.renderButton();this.#A(s),this.#a.append(s,this.#w)}async addEditSignatureButton(t){const s=this.#d=await t.renderEditButton(this.#h);this.#A(s),this.#a.append(s,this.#w)}removeButton(t){"comment"===t&&(this.#c?.removeToolbarCommentButton(),this.#c=null,this.#u?.remove(),this.#u=null)}async addButton(t,s){switch(t){case"colorPicker":s&&this.addColorPicker(s);break;case"altText":s&&await this.addAltText(s);break;case"editSignature":s&&await this.addEditSignatureButton(s);break;case"delete":this.addDeleteButton();break;case"comment":s&&this.addComment(s)}}async addButtonBefore(t,s,e){if(!s&&"comment"===t)return;const i=this.#a.querySelector(e);i&&"comment"===t&&this.addComment(s,i)}updateEditSignatureButton(t){this.#d&&(this.#d.title=t)}remove(){this.#r.remove(),this.#o?.destroy(),this.#o=null}}class Pt{#a=null;#r=null;#b;constructor(t){this.#b=t}#y(){const t=this.#r=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.dir=this.#b.direction;const s=this.#b._signal;s instanceof AbortSignal&&!s.aborted&&t.addEventListener("contextmenu",ot,{signal:s});const e=this.#a=document.createElement("div");return e.className="buttons",t.append(e),this.#b.hasCommentManager()&&this.#v("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",(()=>{this.#b.commentSelection("floating_button")})),this.#v("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",(()=>{this.#b.highlightSelection("floating_button")})),t}#x(t,s){let e=0,i=0;for(const n of t){const t=n.y+n.height;if(t<e)continue;const r=n.x+(s?n.width:0);t>e?(i=r,e=t):s?r>i&&(i=r):r<i&&(i=r)}return[s?1-i:i,e]}show(t,s,e){const[i,n]=this.#x(s,e),{style:r}=this.#r||=this.#y();t.append(this.#r),r.insetInlineEnd=100*i+"%",r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#r.remove()}#v(t,s,e,i){const n=document.createElement("button");n.classList.add("basic",t),n.tabIndex=0,n.setAttribute("data-l10n-id",s);const r=document.createElement("span");n.append(r),r.className="visuallyHidden",r.setAttribute("data-l10n-id",e);const o=this.#b._signal;o instanceof AbortSignal&&!o.aborted&&(n.addEventListener("contextmenu",ot,{signal:o}),n.addEventListener("click",i,{signal:o})),this.#a.append(n)}}const Et=Object.freeze({internal:"59968104-cc61-4cf9-b570-014b35b3709c"});function Dt(t,s,e){for(const i of e)s.addEventListener(i,t[i].bind(t))}class Nt{static#M=NaN;static#k=null;static#C=NaN;static#S=null;static initializeAndAddPointerId(t){(Nt.#k||=new Set).add(t)}static setPointer(t,s){Nt.#M||=s,Nt.#S??=t}static setTimeStamp(t){Nt.#C=t}static isSamePointerId(t){return Nt.#M===t}static isSamePointerIdOrRemove(t){return Nt.#M===t||(Nt.#k?.delete(t),!1)}static isSamePointerType(t){return Nt.#S===t}static isInitializedAndDifferentPointerType(t){return null!==Nt.#S&&!Nt.isSamePointerType(t)}static isSameTimeStamp(t){return Nt.#C===t}static isUsingMultiplePointers(){return Nt.#k?.size>=1}static clearPointerType(){Nt.#S=null}static clearPointerIds(){Nt.#M=NaN,Nt.#k=null}static clearTimeStamp(){Nt.#C=NaN}}class It{#T=0;get id(){return`${h}${this.#T++}`}}class Ft{#P=U();#T=0;#E=null;static get _isSVGFittingCanvas(){const t=`data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="${n}"><rect width="1" height="1" style="fill:red;"/></svg>`,s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;return e.src=t,S(this,"_isSVGFittingCanvas",e.decode().then((()=>(s.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]))))}async#D(t,s){this.#E||=new Map;let e=this.#E.get(t);if(null===e)return null;if(e?.bitmap)return e.refCounter+=1,e;try{let t;if(e||={bitmap:null,id:`image_${this.#P}_${this.#T++}`,refCounter:0,isSvg:!1},"string"==typeof s?(e.url=s,t=await J(s,"blob")):s instanceof File?t=e.file=s:s instanceof Blob&&(t=s),"image/svg+xml"===t.type){const s=Ft._isSVGFittingCanvas,i=new FileReader,n=new Image,r=new Promise(((t,r)=>{n.onload=()=>{e.bitmap=n,e.isSvg=!0,t()},i.onload=async()=>{const t=e.svgUrl=i.result;n.src=await s?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=i.onerror=r}));i.readAsDataURL(t),await r}else e.bitmap=await createImageBitmap(t);e.refCounter=1}catch(t){y(t),e=null}return this.#E.set(t,e),e&&this.#E.set(e.id,e),e}async getFromFile(t){const{lastModified:s,name:e,size:i,type:n}=t;return this.#D(`${s}_${e}_${i}_${n}`,t)}async getFromUrl(t){return this.#D(t,t)}async getFromBlob(t,s){const e=await s;return this.#D(t,e)}async getFromId(t){this.#E||=new Map;const s=this.#E.get(t);if(!s)return null;if(s.bitmap)return s.refCounter+=1,s;if(s.file)return this.getFromFile(s.file);if(s.blobPromise){const{blobPromise:t}=s;return delete s.blobPromise,this.getFromBlob(s.id,t)}return this.getFromUrl(s.url)}getFromCanvas(t,s){this.#E||=new Map;let e=this.#E.get(t);if(e?.bitmap)return e.refCounter+=1,e;const i=new OffscreenCanvas(s.width,s.height);return i.getContext("2d").drawImage(s,0,0),e={bitmap:i.transferToImageBitmap(),id:`image_${this.#P}_${this.#T++}`,refCounter:1,isSvg:!1},this.#E.set(t,e),this.#E.set(e.id,e),e}getSvgUrl(t){const s=this.#E.get(t);return s?.isSvg?s.svgUrl:null}deleteId(t){this.#E||=new Map;const s=this.#E.get(t);if(!s)return;if(s.refCounter-=1,0!==s.refCounter)return;const{bitmap:e}=s;if(!s.url&&!s.file){const t=new OffscreenCanvas(e.width,e.height);t.getContext("bitmaprenderer").transferFromImageBitmap(e),s.blobPromise=t.convertToBlob()}e.close?.(),s.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#P}_`)}}class _t{#N=[];#I=!1;#F;#_=-1;constructor(t=128){this.#F=t}add({cmd:t,undo:s,post:e,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),this.#I)return;const h={cmd:t,undo:s,post:e,type:n};if(-1===this.#_)return this.#N.length>0&&(this.#N.length=0),this.#_=0,void this.#N.push(h);if(r&&this.#N[this.#_].type===n)return o&&(h.undo=this.#N[this.#_].undo),void(this.#N[this.#_]=h);const a=this.#_+1;a===this.#F?this.#N.splice(0,1):(this.#_=a,a<this.#N.length&&this.#N.splice(a)),this.#N.push(h)}undo(){if(-1===this.#_)return;this.#I=!0;const{undo:t,post:s}=this.#N[this.#_];t(),s?.(),this.#I=!1,this.#_-=1}redo(){if(this.#_<this.#N.length-1){this.#_+=1,this.#I=!0;const{cmd:t,post:s}=this.#N[this.#_];t(),s?.(),this.#I=!1}}hasSomethingToUndo(){return-1!==this.#_}hasSomethingToRedo(){return this.#_<this.#N.length-1}cleanType(t){if(-1!==this.#_){for(let s=this.#_;s>=0;s--)if(this.#N[s].type!==t)return this.#N.splice(s+1,this.#_-s),void(this.#_=s);this.#N.length=0,this.#_=-1}}destroy(){this.#N=null}}class Rt{static ALT=1;static CTRL=2;static META=4;static SHIFT=8;constructor(t){this.callbacks=new Map;const{isMac:s}=R.platform;for(const[e,i,n={}]of t){const t=e.some((t=>t.startsWith("mac+")));for(const r of e){let e=r;if(t){const t=r.startsWith("mac+");if(s!==t)continue;t&&(e=r.slice(4))}const[o,h]=Rt.#R(e);null!==o&&this.callbacks.getOrInsertComputed(o,j).push({callback:i,options:n,modifiers:h})}}}static#R(t){let s=null,e=0;for(let i of t.split("+")){if(i=i.trim(),!i)continue;const n=i.toUpperCase(),r=Rt[n];if(r)e|=r;else{if(null!==s){y(`KeyboardManager: multiple keys in shortcut "${t}"`);break}s="SPACE"===n?" ":i}}return null===s&&y(`KeyboardManager: no key found in shortcut "${t}"`),[s,e]}static#O(t){const s=/^(?:Key([A-Z])|(?:Digit|Numpad)(\d))$/.exec(t);return s?s[1]?.toLowerCase()??s[2]:null}exec(t,s){let e=this.callbacks.get(s.key);if(!e){if(/^[a-z]$/i.test(s.key))return;const t=Rt.#O(s.code);if(null===t||t===s.key)return;if(e=this.callbacks.get(t),!e)return}const i=(s.altKey?Rt.ALT:0)|(s.ctrlKey?Rt.CTRL:0)|(s.metaKey?Rt.META:0)|(s.shiftKey?Rt.SHIFT:0),n=e.find((t=>t.modifiers===i));if(!n)return;const{callback:r,options:{bubbles:o=!1,args:h=[],checker:a=null}}=n;a&&!a(t,s)||(r.bind(t,...h,s)(),o||ht(s))}}class Ot{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 s=document.createElement("span");s.style.visibility="hidden",s.style.colorScheme="only light",document.body.append(s);for(const e of t.keys()){s.style.color=e;const i=window.getComputedStyle(s).color;t.set(e,ct(i))}s.remove()}(t),S(this,"_colors",t)}convert(t){const s=ct(t);if(!window.matchMedia("(forced-colors: active)").matches)return s;for(const[t,e]of this._colors)if(e.every(((t,e)=>t===s[e])))return Ot._colorsMapping.get(t);return s}getHexCode(t){const s=this._colors.get(t);return s?O.makeHexColor(...s):t}}class Bt{#B=new AbortController;#$=null;#L=null;#U=new Map;#j=new Map;#G=null;#z=null;#H=null;#W=null;#V=null;#X=new _t;#Y=null;#K=null;#q=null;#Q=0;#J=new Set;#Z=null;#tt=null;#st=new Set;_editorUndoBar=null;#et=!1;#it=!1;#nt=!1;#rt=null;#ot=null;#ht=null;#at=null;#lt=!1;#ct=null;#ut=new It;#dt=!1;#ft=!1;#pt=!1;#gt=null;#mt=null;#At=null;#wt=null;#bt=null;#yt=a.NONE;#vt=new Set;#xt=null;#Mt=null;#kt=null;#Ct=null;#St=null;#Tt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Pt=[0,0];#Et=null;#Dt=null;#Nt=null;#It=null;#Ft=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Bt.prototype,s=t=>t.#Dt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),e=(t,{target:s})=>{if(s instanceof HTMLInputElement){const{type:t}=s;return"text"!==t&&"number"!==t}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return S(this,"_keyboardManager",new Rt([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:e}],[["ctrl+z","mac+meta+z"],t.undo,{checker:e}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:e}],[["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:e}],[["Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:s})=>!(s instanceof HTMLButtonElement)&&t.#Dt.contains(s)&&!t.isEnterHandled}],[["Space"],t.addNewEditorFromKeyboard,{checker:(t,{target:s})=>!(s instanceof HTMLButtonElement)&&t.#Dt.contains(document.activeElement)}],[["Escape"],t.unselectAll],[["ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:s}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:s}],[["ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:s}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:s}],[["ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:s}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:s}],[["ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:s}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:s}]]))}constructor(t,s,e,i,n,r,o,h,a,l,c,u,d,f,p,g){const m=this._signal=this.#B.signal;this.#Dt=t,this.#Nt=s,this.#It=e,this.#H=i,this.#Y=n,this.#Mt=r,this.#St=h,this._eventBus=o;const A={signal:m,...Et};o.on("editingaction",this.onEditingAction.bind(this),A),o.on("pagechanging",this.onPageChanging.bind(this),A),o.on("scalechanging",this.onScaleChanging.bind(this),A),o.on("rotationchanging",this.onRotationChanging.bind(this),A),o.on("setpreference",this.onSetPreference.bind(this),A),o.on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),A),window.addEventListener("pointerdown",(()=>{this.#ft=!0}),{capture:!0,signal:m}),window.addEventListener("pointerup",(()=>{this.#ft=!1}),{capture:!0,signal:m}),window.addEventListener("beforeunload",this.endCurrentEditing.bind(this),{capture:!0,signal:m}),this.#_t(),this.#Rt(),this.#Ot(),this.#W=h.annotationStorage,this.#rt=h.filterFactory,this.#kt=a,this.#at=l||null,this.#et=c,this.#it=u,this.#nt=d,this.#bt=f||null,this.viewParameters={realScale:Q.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=p||null,this._supportsPinchToZoom=!1!==g,n?.setSidebarUiManager(this)}destroy(){this.#Ft?.resolve(),this.#Ft=null,this.#B?.abort(),this.#B=null,this._signal=null;for(const t of this.#j.values())t.destroy();this.#j.clear(),this.#U.clear(),this.#st.clear(),this.#wt?.clear(),this.#$=null,this.#vt.clear(),this.#X.destroy(),this.#H?.destroy(),this.#Y?.destroy(),this.#Mt?.destroy(),this.#ct?.hide(),this.#ct=null,this.#At?.destroy(),this.#At=null,this.#L=null,this.#ot&&(clearTimeout(this.#ot),this.#ot=null),this.#Et&&(clearTimeout(this.#Et),this.#Et=null),this._editorUndoBar?.destroy(),this.#St=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#bt}get useNewAltTextFlow(){return this.#it}get useNewAltTextWhenAddingImage(){return this.#nt}get hcmFilter(){return S(this,"hcmFilter",this.#kt?this.#rt.addHCMFilter(this.#kt.foreground,this.#kt.background):"none")}get direction(){return S(this,"direction",getComputedStyle(this.#Dt).direction)}get _highlightColors(){return S(this,"_highlightColors",this.#at?new Map(this.#at.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 S(this,"highlightColors",null);const s=new Map,e=!!this.#kt;for(const[i,n]of t){const t=i.endsWith("_HCM");e&&t?s.set(i.replace("_HCM",""),n):e||t||s.set(i,n)}return S(this,"highlightColors",s)}get highlightColorNames(){return S(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const s=this.highlightColorNames.get(t);return this._highlightColors.get(s)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#q=t}setMainHighlightColorPicker(t){this.#At=t}editAltText(t,s=!1){this.#H?.editAltText(this,t,s)}hasCommentManager(){return!!this.#Y}editComment(t,s,e,i){this.#Y?.showDialog(this,t,s,e,i)}selectComment(t,s){const e=this.#j.get(t),i=e?.getEditorByUID(s);i?.toggleComment(!0,!0)}updateComment(t){this.#Y?.updateComment(t.getData())}updatePopupColor(t){this.#Y?.updatePopupColor(t)}removeComment(t){this.#Y?.removeComments([t.uid])}deleteComment(t,s){const e=()=>{t.comment=s};this.addCommands({cmd:()=>{this._editorUndoBar?.show(e,"comment"),this.toggleComment(null),t.comment=null},undo:e,mustExec:!0})}toggleComment(t,s,e){this.#Y?.toggleCommentPopup(t,s,e)}makeCommentColor(t,s){return t&&this.#Y?.makeCommentColor(t,s)||null}getCommentDialogElement(){return this.#Y?.dialogElement||null}async waitForEditorsRendered(t){if(this.#j.has(t-1))return;const{resolve:s,promise:e}=Promise.withResolvers(),i=e=>{e.pageNumber===t&&(this._eventBus.off("editorsrendered",i),s())};this._eventBus.on("editorsrendered",i,Et),await e}getSignature(t){this.#Mt?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#Mt}switchToMode(t,s){this._eventBus.on("annotationeditormodechanged",s,{once:!0,signal:this._signal,...Et}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,s){this._eventBus.dispatch("setpreference",{source:this,name:t,value:s})}onSetPreference({name:t,value:s}){"enableNewAltTextWhenAddingImage"===t&&(this.#nt=s)}onPageChanging({pageNumber:t}){this.#Q=t-1}deletePage(t){for(const s of this.getEditors(t))s.remove();this.#j.delete(t),this.#Q===t&&(this.#Q=0)}focusMainContainer(){this.#Dt.focus()}findParent(t,s){for(const e of this.#j.values()){const{x:i,y:n,width:r,height:o}=e.div.getBoundingClientRect();if(t>=i&&t<=i+r&&s>=n&&s<=n+o)return e}return null}disableUserSelect(t=!1){this.#Nt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#st.add(t)}removeShouldRescale(t){this.#st.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Q.PDF_TO_CSS_UNITS;for(const t of this.#st)t.onScaleChanging();this.#q?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#Bt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#$t(t){const{currentLayer:s}=this;if(s.hasTextLayer(t))return s;for(const s of this.#j.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t="",s=!1){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:o}=e,h=e.toString(),l=this.#Bt(e).closest(".textLayer"),c=this.getSelectionBoxes(l);if(!c)return;e.empty();const u=this.#$t(l),d=this.#yt===a.NONE,f=()=>{const e=u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:c,anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:o,text:h});d&&this.showAllEditors("highlight",!0,!0),s&&e?.editComment()};d?this.switchToMode(a.HIGHLIGHT,f):f()}commentSelection(t=""){this.highlightSelection(t,!0)}endCurrentEditing(){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#Lt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#Bt(t).closest(".textLayer"),e=this.getSelectionBoxes(s);e&&(this.#ct||=new Pt(this),this.#ct.show(s,e,"ltr"===this.direction))}getAndRemoveDataFromAnnotationStorage(t){if(!this.#W)return null;const s=`${h}${t}`,e=this.#W.getRawValue(s);return e&&this.#W.remove(s),e}addToAnnotationStorage(t){t.isEmpty()||!this.#W||this.#W.has(t.id)||this.#W.setValue(t.id,t)}a11yAlert(t,s=null){const e=this.#It;e&&(e.setAttribute("data-l10n-id",t),s?e.setAttribute("data-l10n-args",JSON.stringify(s)):e.removeAttribute("data-l10n-args"))}#Ut(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#xt&&(this.#ct?.hide(),this.#xt=null,this.#jt({hasSelectedText:!1})));const{anchorNode:s}=t;if(s===this.#xt)return;const e=this.#Bt(t).closest(".textLayer");if(e){if(this.#ct?.hide(),this.#xt=s,this.#jt({hasSelectedText:!0}),(this.#yt===a.HIGHLIGHT||this.#yt===a.NONE)&&(this.#yt===a.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#lt=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#yt===a.HIGHLIGHT?this.#$t(e):null;if(t?.toggleDrawing(),this.#ft){const s=new AbortController,e=this.combinedSignal(s),i=e=>{"pointerup"===e.type&&0!==e.button||(s.abort(),t?.toggleDrawing(!0),"pointerup"===e.type&&this.#Gt("main_toolbar"))};window.addEventListener("pointerup",i,{signal:e}),window.addEventListener("blur",i,{signal:e})}else t?.toggleDrawing(!0),this.#Gt("main_toolbar")}}else this.#xt&&(this.#ct?.hide(),this.#xt=null,this.#jt({hasSelectedText:!1}))}#Gt(t=""){this.#yt===a.HIGHLIGHT?this.highlightSelection(t):this.#et&&this.#Lt()}#_t(){document.addEventListener("selectionchange",this.#Ut.bind(this),{signal:this._signal})}#zt(){if(this.#ht)return;this.#ht=new AbortController;const t=this.combinedSignal(this.#ht);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Ht(){this.#ht?.abort(),this.#ht=null}blur(){if(this.isShiftKeyDown=!1,this.#lt&&(this.#lt=!1,this.#Gt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const s of this.#vt)if(s.div.contains(t)){this.#mt=[s,t],s._focusEventsAllowed=!1;break}}focus(){if(!this.#mt)return;const[t,s]=this.#mt;this.#mt=null,s.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal}),s.focus()}#Ot(){if(this.#gt)return;this.#gt=new AbortController;const t=this.combinedSignal(this.#gt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Wt(){this.#gt?.abort(),this.#gt=null}#Vt(){if(this.#K)return;this.#K=new AbortController;const t=this.combinedSignal(this.#K);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})}#Xt(){this.#K?.abort(),this.#K=null}#Rt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Ot(),this.setEditingState(!0)}removeEditListeners(){this.#Wt(),this.setEditingState(!1)}dragOver(t){for(const{type:s}of t.dataTransfer.items)for(const e of this.#tt)if(e.isHandlingMimeForPasting(s))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const s of t.dataTransfer.items)for(const e of this.#tt)if(e.isHandlingMimeForPasting(s.type))return e.paste(s,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#$?.commitOrRemove(),!this.hasSelection)return;const s=[];for(const t of this.#vt){const e=t.serialize(!0);e&&s.push(e)}0!==s.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(s))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:s}=t;for(const t of s.items)for(const s of this.#tt)if(s.isHandlingMimeForPasting(t.type))return void s.paste(t,this.currentLayer);let e=s.getData("application/pdfjs");if(!e)return;try{e=JSON.parse(e)}catch(t){return void y(`paste: "${t.message}".`)}if(!Array.isArray(e))return;this.unselectAll();const i=this.currentLayer;try{const t=[];for(const s of e){const e=await i.deserialize(s);if(!e)return;t.push(e)}this.addCommands({cmd:()=>{for(const s of t)this.#Yt(s);this.#Kt(t)},undo:()=>{for(const s of t)s.remove()},mustExec:!0})}catch(t){y(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#yt===a.NONE||this.isEditorHandlingKeyboard||Bt._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#lt&&(this.#lt=!1,this.#Gt("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")}}updatePageIndex(t,s){for(const e of this.#z.get(t)||[])e.pageIndex=s;const e=this.#G.get(t);e&&(e.pageIndex=s,this.#j.set(s,e),this.#dt?e.enable():e.disable())}startUpdatePages(){this.#G=new Map(this.#j),this.#j.clear();const t=this.#z=new Map,s=s=>{t.getOrInsertComputed(s.pageIndex,j).push(s)};for(const t of this.#U.values())s(t);for(const[t,e]of this.#W)t.startsWith(h)&&!this.#U.has(t)&&Number.isInteger(e?.pageIndex)&&s(e)}endUpdatePages(){this.#G=null,this.#z=null}clonePage(t,s){for(const e of this.getEditors(t)){const t=e.serialize(e.mode!==a.HIGHLIGHT);t&&(t.pageIndex=s,t.id=this.getId(),t.isClone=!0,delete t.popupRef,this.#W.setValue(t.id,t))}}findClonesForPage(t){const s=[],{pageIndex:e}=t;for(const[i,n]of this.#W)n.pageIndex===e&&n.isClone&&(this.#W.remove(i),s.push(t.deserialize(n).then((s=>{s&&(s.isClone=!0,t.addOrRebuild(s))}))));return Promise.all(s)}#jt(t){Object.entries(t).some((([t,s])=>this.#Tt[t]!==s))&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(this.#Tt,t)}),this.#yt===a.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#qt([[l.HIGHLIGHT_FREE,!0]]))}#qt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#zt(),this.#Vt(),this.#jt({isEditing:this.#yt!==a.NONE,isEmpty:this.#Qt(),hasSomethingToUndo:this.#X.hasSomethingToUndo(),hasSomethingToRedo:this.#X.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Ht(),this.#Xt(),this.#jt({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#tt){this.#tt=t;for(const t of this.#tt)this.#qt(t.defaultPropertiesToUpdate)}}getId(){return this.#ut.id}get currentLayer(){return this.#j.get(this.#Q)}getLayer(t){return this.#j.get(t)}get currentPageIndex(){return this.#Q}addLayer(t){this.#j.set(t.pageIndex,t),this.#dt?t.enable():t.disable()}removeLayer(t){this.#j.delete(t.pageIndex)}async updateMode(t,s=null,e=!1,i=!1,n=!1,r=!1){if(this.#yt!==t&&(!this.#Ft||(await this.#Ft.promise,this.#Ft))){if(this.#Ft=Promise.withResolvers(),this.#q?.commitOrRemove(),this.#yt===a.POPUP&&this.#Y?.hideSidebar(),this.#Y?.destroyPopup(),this.#yt=t,t===a.NONE){this.setEditingState(!1),this.#Jt();for(const t of this.#U.values())t.hideStandaloneCommentButton();return this._editorUndoBar?.hide(),this.toggleComment(null),void this.#Ft.resolve()}for(const t of this.#U.values())t.addStandaloneCommentButton();t===a.SIGNATURE&&await(this.#Mt?.loadSignatures()),e&&Nt.clearPointerType(),this.setEditingState(!0),await this.#Zt(),this.unselectAll();for(const s of this.#j.values())s.updateMode(t);if(t===a.POPUP){this.#L||=await this.#St.getAnnotationsByType(new Set(this.#tt.map((t=>t._editorType))));const t=new Set,s=[];for(const e of this.#U.values()){const{annotationElementId:i,hasComment:n,deleted:r}=e;i&&t.add(i),n&&!r&&s.push(e.getData())}for(const e of this.#L){const{id:i,popupRef:n,contentsObj:r}=e;n&&r?.str&&!t.has(i)&&!this.#J.has(i)&&s.push(e)}this.#Y?.showSidebar(s)}if(!s)return i&&this.addNewEditorFromKeyboard(),void this.#Ft.resolve();for(const t of this.#U.values())t.uid===s?(this.setSelected(t),r?t.editComment():n?t.enterInEditMode():t.focus()):t.unselect();this.#Ft.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#yt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,s){if(this.#tt){switch(t){case l.CREATE:return void this.currentLayer.addNewEditor(s);case l.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#Ct||=new Map).set(t,s),this.showAllEditors("highlight",s)}if(this.hasSelection)for(const e of this.#vt)e.updateParams(t,s);else for(const e of this.#tt)e.updateDefaultParams(t,s)}}showAllEditors(t,s,e=!1){for(const e of this.#U.values())e.editorType===t&&e.show(s);(this.#Ct?.get(l.HIGHLIGHT_SHOW_ALL)??!0)!==s&&this.#qt([[l.HIGHLIGHT_SHOW_ALL,s]])}enableWaiting(t=!1){if(this.#pt!==t){this.#pt=t;for(const s of this.#j.values())t?s.disableClick():s.enableClick(),s.div.classList.toggle("waiting",t)}}async#Zt(){if(!this.#dt){this.#dt=!0;const t=[];for(const s of this.#j.values())t.push(s.enable());await Promise.all(t);for(const t of this.#U.values())t.enable()}}#Jt(){if(this.unselectAll(),this.#dt){this.#dt=!1;for(const t of this.#j.values())t.disable();for(const t of this.#U.values())t.disable()}}*getEditors(t){for(const s of this.#U.values())s.pageIndex===t&&(yield s)}getEditor(t){return this.#U.get(t)}addEditor(t){this.#U.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#ot&&clearTimeout(this.#ot),this.#ot=setTimeout((()=>{this.focusMainContainer(),this.#ot=null}),0)),this.#U.delete(t.id),t.annotationElementId&&this.#wt?.delete(t.annotationElementId),this.unselect(t),t.annotationElementId&&this.#J.has(t.annotationElementId)||this.#W?.remove(t.id)}addDeletedAnnotationElement(t){this.#J.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#J.has(t)}removeDeletedAnnotationElement(t){this.#J.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#Yt(t){const s=this.#j.get(t.pageIndex);s?s.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#$!==t&&(this.#$=t,t&&this.#qt(t.propertiesToUpdate))}get#ts(){let t=null;for(t of this.#vt);return t}updateUI(t){this.#ts===t&&this.#qt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#qt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#vt.has(t))return this.#vt.delete(t),t.unselect(),void this.#jt({hasSelectedEditor:this.hasSelection});this.#vt.add(t),t.select(),this.#qt(t.propertiesToUpdate),this.#jt({hasSelectedEditor:!0})}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid}),this.#q?.commitOrRemove();for(const s of this.#vt)s!==t&&s.unselect();this.#Y?.destroyPopup(),this.#vt.clear(),this.#vt.add(t),t.select(),this.#qt(t.propertiesToUpdate),this.#jt({hasSelectedEditor:!0})}get firstSelectedEditor(){return this.#vt.values().next().value}unselect(t){t.unselect(),this.#vt.delete(t),this.#jt({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#vt.size}get isEnterHandled(){return 1===this.#vt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#X.undo(),this.#jt({hasSomethingToUndo:this.#X.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Qt()}),this._editorUndoBar?.hide()}redo(){this.#X.redo(),this.#jt({hasSomethingToUndo:!0,hasSomethingToRedo:this.#X.hasSomethingToRedo(),isEmpty:this.#Qt()})}addCommands(t){this.#X.add(t),this.#jt({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Qt()})}cleanUndoStack(t){this.#X.cleanType(t)}#Qt(){if(0===this.#U.size)return!0;if(1===this.#U.size)for(const t of this.#U.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const s=t?[t]:[...this.#vt],e=()=>{for(const t of s)this.#Yt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(e,1===s.length?s[0].editorType:s.length);for(const t of s)t.remove()},undo:e,mustExec:!0})}commitOrRemove(){this.#$?.commitOrRemove()}hasSomethingToControl(){return this.#$||this.hasSelection}#Kt(t){for(const t of this.#vt)t.unselect();this.#vt.clear();for(const s of t)s.isEmpty()||(this.#vt.add(s),s.select());this.#jt({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#vt)t.commit();this.#Kt(this.#U.values())}unselectAll(){if((!this.#$||(this.#$.commitOrRemove(),this.#yt===a.NONE))&&!this.#q?.commitOrRemove()&&(this.#Y?.destroyPopup(),this.hasSelection)){for(const t of this.#vt)t.unselect();this.#vt.clear(),this.#jt({hasSelectedEditor:!1})}}translateSelectedEditors(t,s,e=!1){if(e||this.commitOrRemove(),!this.hasSelection)return;this.#Pt[0]+=t,this.#Pt[1]+=s;const[i,n]=this.#Pt,r=[...this.#vt];this.#Et&&clearTimeout(this.#Et),this.#Et=setTimeout((()=>{this.#Et=null,this.#Pt[0]=this.#Pt[1]=0,this.addCommands({cmd:()=>{for(const t of r)this.#U.has(t.id)&&(t.translateInPage(i,n),t.translationDone())},undo:()=>{for(const t of r)this.#U.has(t.id)&&(t.translateInPage(-i,-n),t.translationDone())},mustExec:!1})}),1e3);for(const e of r)e.translateInPage(t,s),e.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#Z=new Map;for(const t of this.#vt)this.#Z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#Z)return!1;this.disableUserSelect(!1);const t=this.#Z;this.#Z=null;let s=!1;for(const[{x:e,y:i,pageIndex:n},r]of t)r.newX=e,r.newY=i,r.newPageIndex=n,s||=e!==r.savedX||i!==r.savedY||n!==r.savedPageIndex;if(!s)return!1;const e=(t,s,e,i)=>{if(this.#U.has(t.id)){const n=this.#j.get(i);n?t._setParentAndPosition(n,s,e):(t.pageIndex=i,t.x=s,t.y=e)}};return this.addCommands({cmd:()=>{for(const[s,{newX:i,newY:n,newPageIndex:r}]of t)e(s,i,n,r)},undo:()=>{for(const[s,{savedX:i,savedY:n,savedPageIndex:r}]of t)e(s,i,n,r)},mustExec:!0}),!0}dragSelectedEditors(t,s){if(this.#Z)for(const e of this.#Z.keys())e.drag(t,s)}rebuild(t){if(null===t.parent){const s=this.getLayer(t.pageIndex);s?(s.changeParent(t),s.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#vt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#$===t}getActive(){return this.#$}getMode(){return this.#yt}isEditingMode(){return this.#yt!==a.NONE}get imageManager(){return S(this,"imageManager",new Ft)}getSelectionBoxes(t){if(!t)return null;const s=document.getSelection();for(let e=0,i=s.rangeCount;e<i;e++)if(!t.contains(s.getRangeAt(e).commonAncestorContainer))return null;const{x:e,y:i,width:n,height:r}=t.getBoundingClientRect();let o;switch(t.getAttribute("data-main-rotation")){case"90":o=(t,s,o,h)=>({x:(s-i)/r,y:1-(t+o-e)/n,width:h/r,height:o/n});break;case"180":o=(t,s,o,h)=>({x:1-(t+o-e)/n,y:1-(s+h-i)/r,width:o/n,height:h/r});break;case"270":o=(t,s,o,h)=>({x:1-(s+h-i)/r,y:(t-e)/n,width:h/r,height:o/n});break;default:o=(t,s,o,h)=>({x:(t-e)/n,y:(s-i)/r,width:o/n,height:h/r})}const h=[];for(let t=0,e=s.rangeCount;t<e;t++){const e=s.getRangeAt(t);if(!e.collapsed)for(const{x:t,y:s,width:i,height:n}of e.getClientRects())0!==i&&0!==n&&h.push(o(t,s,i,n))}return 0===h.length?null:h}addChangedExistingAnnotation({annotationElementId:t,id:s}){(this.#V||=new Map).set(t,s)}removeChangedExistingAnnotation({annotationElementId:t}){this.#V?.delete(t)}renderAnnotationElement(t){const s=this.#V?.get(t.data.id);if(!s)return;const e=this.#W.getRawValue(s);e&&(this.#yt!==a.NONE||e.hasBeenModified)&&e.renderAnnotationElement(t)}setMissingCanvas(t,s,e){const i=this.#wt?.get(t);i&&(i.setCanvas(s,e),this.#wt.delete(t))}addMissingCanvas(t,s){(this.#wt||=new Map).set(t,s)}}class $t{#l=null;#ss=!1;#es=null;#is=null;#ns=null;#rs=null;#os=!1;#hs=null;#h=null;#as=null;#ls=null;#cs=!1;static#us=null;static _l10n=null;constructor(t){this.#h=t,this.#cs=t._uiManager.useNewAltTextFlow,$t.#us||=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){$t._l10n??=t}async render(){const t=this.#es=document.createElement("button");t.className="altText",t.tabIndex="0";const s=this.#is=document.createElement("span");t.append(s),this.#cs?(t.classList.add("new"),t.setAttribute("data-l10n-id",$t.#us.missing),s.setAttribute("data-l10n-id",$t.#us["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),s.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const e=this.#h._uiManager._signal;t.addEventListener("contextmenu",ot,{signal:e}),t.addEventListener("pointerdown",(t=>t.stopPropagation()),{signal:e});const i=t=>{t.preventDefault(),this.#h._uiManager.editAltText(this.#h),this.#cs&&this.#h._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#ds}})};return t.addEventListener("click",i,{capture:!0,signal:e}),t.addEventListener("keydown",(s=>{s.target===t&&"Enter"===s.key&&(this.#os=!0,i(s))}),{signal:e}),await this.#fs(),t}get#ds(){return(this.#l?"added":null===this.#l&&this.guessedText&&"review")||"missing"}finish(){this.#es&&(this.#es.focus({focusVisible:this.#os}),this.#os=!1)}isEmpty(){return this.#cs?null===this.#l:!this.#l&&!this.#ss}hasData(){return this.#cs?null!==this.#l||!!this.#as:this.isEmpty()}get guessedText(){return this.#as}async setGuessedText(t){null===this.#l&&(this.#as=t,this.#ls=await $t._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#fs())}toggleAltTextBadge(t=!1){if(!this.#cs||this.#l)return this.#hs?.remove(),void(this.#hs=null);if(!this.#hs){const t=this.#hs=document.createElement("div");t.className="noAltTextBadge",this.#h.div.append(t)}this.#hs.classList.toggle("hidden",!t)}serialize(t){let s=this.#l;return t||this.#as!==s||(s=this.#ls),{altText:s,decorative:this.#ss,guessedText:this.#as,textWithDisclaimer:this.#ls}}get data(){return{altText:this.#l,decorative:this.#ss}}set data({altText:t,decorative:s,guessedText:e,textWithDisclaimer:i,cancel:n=!1}){e&&(this.#as=e,this.#ls=i),this.#l===t&&this.#ss===s||(n||(this.#l=t,this.#ss=s),this.#fs())}toggle(t=!1){this.#es&&(!t&&this.#rs&&(clearTimeout(this.#rs),this.#rs=null),this.#es.disabled=!t)}shown(){this.#h._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#ds}})}destroy(){this.#es?.remove(),this.#es=null,this.#is=null,this.#ns=null,this.#hs?.remove(),this.#hs=null}async#fs(){const t=this.#es;if(!t)return;if(this.#cs){if(t.classList.toggle("done",!!this.#l),t.setAttribute("data-l10n-id",$t.#us[this.#ds]),this.#is?.setAttribute("data-l10n-id",$t.#us[`${this.#ds}-label`]),!this.#l)return void this.#ns?.remove()}else{if(!this.#l&&!this.#ss)return t.classList.remove("done"),void this.#ns?.remove();t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let s=this.#ns;if(!s){this.#ns=s=document.createElement("span"),s.className="tooltip",s.setAttribute("role","tooltip"),s.id=`alt-text-tooltip-${this.#h.id}`;const e=100,i=this.#h._uiManager._signal;i.addEventListener("abort",(()=>{clearTimeout(this.#rs),this.#rs=null}),{once:!0}),t.addEventListener("mouseenter",(()=>{this.#rs=setTimeout((()=>{this.#rs=null,this.#ns.classList.add("show"),this.#h._reportTelemetry({action:"alt_text_tooltip"})}),e)}),{signal:i}),t.addEventListener("mouseleave",(()=>{this.#rs&&(clearTimeout(this.#rs),this.#rs=null),this.#ns?.classList.remove("show")}),{signal:i})}this.#ss?s.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(s.removeAttribute("data-l10n-id"),s.textContent=this.#l),s.parentNode||t.append(s);const e=this.#h.getElementForAltText();e?.setAttribute("aria-describedby",s.id)}}class Lt{#ps=null;#gs=null;#ms=!1;#h=null;#As=null;#ws=null;#bs=null;#ys=null;#vs=!1;#xs=null;constructor(t){this.#h=t}renderForToolbar(){const t=this.#gs=document.createElement("button");return t.className="comment",this.#y(t,!1)}renderForStandalone(){const t=this.#ps=document.createElement("button");t.className="annotationCommentButton";const s=this.#h.commentButtonPosition;if(s){const{style:e}=t;e.insetInlineEnd=`calc(${100*("ltr"===this.#h._uiManager.direction?1-s[0]:s[0])}% - var(--comment-button-dim))`,e.top=`calc(${100*s[1]}% - var(--comment-button-dim))`;const i=this.#h.commentButtonColor;i&&(e.backgroundColor=i)}return this.#y(t,!0)}focusButton(){setTimeout((()=>{(this.#ps??this.#gs)?.focus()}),0)}onUpdatedColor(){if(!this.#ps)return;const t=this.#h.commentButtonColor;t&&(this.#ps.style.backgroundColor=t),this.#h._uiManager.updatePopupColor(this.#h)}get commentButtonWidth(){return(this.#ps?.getBoundingClientRect().width??0)/this.#h.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#xs)return this.#xs;if(!this.#ps)return null;const{x:t,y:s,height:e}=this.#ps.getBoundingClientRect(),{x:i,y:n,width:r,height:o}=this.#h.parent.boundingClientRect;return[(t-i)/r,(s+e-n)/o]}set commentPopupPositionInLayer(t){this.#xs=t}hasDefaultPopupPosition(){return null===this.#xs}removeStandaloneCommentButton(){this.#ps?.remove(),this.#ps=null}removeToolbarCommentButton(){this.#gs?.remove(),this.#gs=null}setCommentButtonStates({selected:t,hasPopup:s}){this.#ps&&(this.#ps.classList.toggle("selected",t),this.#ps.ariaExpanded=s)}#y(t,s){if(!this.#h._uiManager.hasCommentManager())return null;t.tabIndex="0",t.ariaHasPopup="dialog",s?(t.ariaControls="commentPopup",t.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(t.ariaControlsElements=[this.#h._uiManager.getCommentDialogElement()],t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const e=this.#h._uiManager._signal;if(!(e instanceof AbortSignal)||e.aborted)return t;t.addEventListener("contextmenu",ot,{signal:e}),s&&(t.addEventListener("focusin",(t=>{this.#h._focusEventsAllowed=!1,ht(t)}),{capture:!0,signal:e}),t.addEventListener("focusout",(t=>{this.#h._focusEventsAllowed=!0,ht(t)}),{capture:!0,signal:e})),t.addEventListener("pointerdown",(t=>t.stopPropagation()),{signal:e});const i=s=>{s.preventDefault(),t===this.#gs?this.edit():this.#h.toggleComment(!0)};return t.addEventListener("click",i,{capture:!0,signal:e}),t.addEventListener("keydown",(s=>{s.target===t&&"Enter"===s.key&&(this.#ms=!0,i(s))}),{signal:e}),t.addEventListener("pointerenter",(()=>{this.#h.toggleComment(!1,!0)}),{signal:e}),t.addEventListener("pointerleave",(()=>{this.#h.toggleComment(!1,!1)}),{signal:e}),t}edit(t){const s=this.commentPopupPositionInLayer;let e,i;if(s)[e,i]=s;else{[e,i]=this.#h.commentButtonPosition;const{width:t,height:s,x:n,y:r}=this.#h;e=n+e*t,i=r+i*s}const n=this.#h.parent.boundingClientRect,{x:r,y:o,width:h,height:a}=n;this.#h._uiManager.editComment(this.#h,r+e*h,o+i*a,{...t,parentDimensions:n})}finish(){this.#gs&&(this.#gs.focus({focusVisible:this.#ms}),this.#ms=!1)}isDeleted(){return this.#vs||""===this.#bs}isEmpty(){return null===this.#bs}hasBeenEdited(){return this.isDeleted()||this.#bs!==this.#As}serialize(){return this.data}get data(){return{text:this.#bs,richText:this.#ws,date:this.#ys,deleted:this.isDeleted()}}set data(t){if(t!==this.#bs&&(this.#ws=null),null===t)return this.#bs="",void(this.#vs=!0);this.#bs=t,this.#ys=new Date,this.#vs=!1}restoreData({text:t,richText:s,date:e}){this.#bs=t,this.#ws=s,this.#ys=e,this.#vs=!1}setInitialText(t,s=null){this.#As=t,this.data=t,this.#ys=null,this.#ws=s}shown(){}destroy(){this.#gs?.remove(),this.#gs=null,this.#ps?.remove(),this.#ps=null,this.#bs="",this.#ws=null,this.#ys=null,this.#h=null,this.#ms=!1,this.#vs=!1}}function Ut(t){t.preventDefault()}const jt=1e-4;function Gt(t){return t.cancelable?(ht(t),!0):(t.stopPropagation(),!1)}class zt{#Dt;#Ms=!1;#ks=null;#Cs;#Ss;#Ts;#Ps;#Es;#Ds=!1;#Ns=null;#Is;#Fs=new Set;#_s=null;#Rs;#Os=null;#Bs=0;constructor({container:t,isPinchingDisabled:s=null,isPinchingStopped:e=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,onPanning:o=null,signal:h}){this.#Dt=t,this.#ks=e,this.#Cs=s,this.#Ss=i,this.#Ts=n,this.#Ps=r,this.#Es=o,this.#Rs=new AbortController,this.#Is=AbortSignal.any([h,this.#Rs.signal]),t.addEventListener("touchstart",this.#$s.bind(this),{passive:!1,signal:this.#Is})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/pt.pixelRatio}get MIN_TOUCH_DISTANCE_TO_SCALE(){return 4/pt.pixelRatio}#$s(t){if(this.#Cs?.())return;this.#Ls(t);const s=this.#Fs;for(const{identifier:e}of t.changedTouches)s.add(e);if(1!==s.size){if(!this.#Os){this.#Os=new AbortController;const t=AbortSignal.any([this.#Is,this.#Os.signal]),s=this.#Dt,e={signal:t,capture:!1,passive:!1};s.addEventListener("touchmove",this.#Us.bind(this),e);const i=this.#js.bind(this);s.addEventListener("touchend",i,e),s.addEventListener("touchcancel",i,e),e.capture=!0,s.addEventListener("pointerdown",ht,e),s.addEventListener("pointermove",ht,e),s.addEventListener("pointercancel",Ut,e),s.addEventListener("pointerup",Ut,e),this.#Ss?.()}this.#Ds=Gt(t),this.#Gs(t)}else this.#zs()}#zs(){if(this.#Ns)return;const t=this.#Ns=new AbortController,s=AbortSignal.any([this.#Is,t.signal]),e=this.#Dt,i={capture:!0,signal:s,passive:!1},n=t=>{"touch"===t.pointerType&&(this.#Ns?.abort(),this.#Ns=null)};e.addEventListener("pointerdown",(t=>{"touch"===t.pointerType&&(ht(t),n(t))}),i),e.addEventListener("pointerup",n,i),e.addEventListener("pointercancel",n,i)}#Ls(t){const s=this.#Fs;if(0===s.size)return;const e=this.#Fs=new Set;for(const{identifier:i}of t.touches)s.has(i)&&e.add(i)}#Hs(t){const s=this.#Fs,e=[];for(const i of t.touches)s.has(i.identifier)&&e.push(i);return e}#Gs(t){const s=this.#Hs(t);if(2!==s.length||this.#ks?.())return void(this.#_s=null);const[e,i]=s;this.#_s={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY,panX:(e.clientX+i.clientX)/2,panY:(e.clientY+i.clientY)/2,screenPanX:(e.screenX+i.screenX)/2,screenPanY:(e.screenY+i.screenY)/2}}#Us(t){if(!this.#_s)return;const s=this.#Hs(t);if(2!==s.length)return;const e=this.#Ds;if(this.#Ds=Gt(t),!this.#Ds)return;if(!e)return void this.#Gs(t);const[i,n]=s,{screenX:r,screenY:o}=i,{screenX:h,screenY:a}=n,l=this.#_s,{touch0X:c,touch0Y:u,touch1X:d,touch1Y:f,panX:p,panY:g}=l,m=d-c,A=f-u,w=h-r,b=a-o,y=(i.clientX+n.clientX)/2,v=(i.clientY+n.clientY)/2;l.panX=y,l.panY=v;const x=y-p,M=v-g,k=(r+h)/2,C=(o+a)/2,S=Math.hypot(k-l.screenPanX,C-l.screenPanY);l.screenPanX=k,l.screenPanY=C;const T=Math.hypot(w,b),P=Math.hypot(m,A),E=this.#Ms?this.MIN_TOUCH_DISTANCE_TO_SCALE:this.MIN_TOUCH_DISTANCE_TO_PINCH+2*S;if(T<jt||P<jt||Math.abs(P-T)<=E)return void((x||M)&&this.#Es?.(x,M));l.touch0X=r,l.touch0Y=o,l.touch1X=h,l.touch1Y=a;const D=Math.sign(T-P);if(!this.#Ms)return this.#Ms=!0,this.#Bs=D,void((x||M)&&this.#Es?.(x,M));if(this.#Bs){const t=this.#Bs;if(this.#Bs=0,D!==t&&Math.abs(T-P)<=2*S)return this.#Ms=!1,void((x||M)&&this.#Es?.(x,M))}this.#Ts?.([p,g],P,T,x,M)}#js(t){if(this.#Ls(t),this.#Fs.size>=2)return void this.#Gs(t);const s=!!this.#_s;this.#Ws(),1===this.#Fs.size&&this.#zs(),s&&Gt(t)}#Ws(){this.#_s=null,this.#Ms=!1,this.#Bs=0,this.#Ds=!1,this.#Os&&(this.#Os.abort(),this.#Os=null,this.#Ps?.())}destroy(){this.#Ws(),this.#Fs.clear(),this.#Rs?.abort(),this.#Rs=null,this.#Ns?.abort(),this.#Ns=null}}class Ht{#Vs=null;#Xs=null;#l=null;#c=null;#ps=null;#Ys=!1;#Ks=null;#qs="";#Qs=null;#Js=null;#Zs=null;#te=null;#se=null;#ee="";#ie=!1;#ne=null;#re=!1;#oe=!1;#he=!1;#ae=null;#le=0;#ce=0;#ue=null;#de=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#fe=!1;#pe=Ht._zIndex++;static _borderLineWidth=-1;static _colorManager=new Ot;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=Ht.prototype._resizeWithKeyboard,s=Bt.TRANSLATE_SMALL,e=Bt.TRANSLATE_BIG;return S(this,"_resizerKeyboardManager",new Rt([[["ArrowLeft"],t,{args:[-s,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-e,0]}],[["ArrowRight"],t,{args:[s,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[e,0]}],[["ArrowUp"],t,{args:[0,-s]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-e]}],[["ArrowDown"],t,{args:[0,s]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,e]}],[["Escape"],Ht.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,this.canAddComment=!0;const{rotation:s,rawDims:{pageWidth:e,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=s,this.pageRotation=(360+s-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[e,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(t){this.pageIndex=t}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 S(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const s=new Wt({id:t._uiManager.getId(),parent:t.parent,uiManager:t._uiManager});s.annotationElementId=t.annotationElementId,s.deleted=!0,s._uiManager.addToAnnotationStorage(s)}static initialize(t,s){if(Ht._l10n??=t,Ht._l10nAlert??=Object.freeze({highlight:"pdfjs-editor-highlight-added-alert",freetext:"pdfjs-editor-freetext-added-alert",ink:"pdfjs-editor-ink-added-alert",stamp:"pdfjs-editor-stamp-added-alert",signature:"pdfjs-editor-signature-added-alert"}),Ht._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!==Ht._borderLineWidth)return;const e=getComputedStyle(document.documentElement);Ht._borderLineWidth=parseFloat(e.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,s){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,s){v("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#fe}set _isDraggable(t){this.#fe=t,this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,s]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*s/(2*t),this.y+=this.width*t/(2*s);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*s/(2*t),this.y-=this.width*t/(2*s);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.#pe}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):(this.#ge(),this.#te?.remove(),this.#te=null),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ie?this.#ie=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const s=t.relatedTarget;s?.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,s,e,i){const[n,r]=this.parentDimensions;[e,i]=this.screenToPageTranslation(e,i),this.x=(t+e)/n,this.y=(s+i)/r,this.fixAndSetPosition()}_moveAfterPaste(t,s){if(this.isClone)return void delete this.isClone;const[e,i]=this.parentDimensions;this.setAt(t*e,s*i,this.width*e,this.height*i),this._onTranslated()}#me([t,s],e,i){[e,i]=this.screenToPageTranslation(e,i),this.x+=e/t,this.y+=i/s,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,s){this.#me(this.parentDimensions,t,s)}translateInPage(t,s){this.#ne||=[this.x,this.y,this.width,this.height],this.#me(this.pageDimensions,t,s),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,s){this.#ne||=[this.x,this.y,this.width,this.height];const{div:e,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=s/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:s}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,s)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:o}=this;const[h,a]=this.getBaseTranslation();r+=h,o+=a;const{style:l}=e;l.left=`${(100*r).toFixed(2)}%`,l.top=`${(100*o).toFixed(2)}%`,this._onTranslating(r,o)}_onTranslating(t,s){}_onTranslated(t,s){}get _hasBeenMoved(){return!!this.#ne&&(this.#ne[0]!==this.x||this.#ne[1]!==this.y)}get _hasBeenResized(){return!!this.#ne&&(this.#ne[2]!==this.width||this.#ne[3]!==this.height)}getBaseTranslation(){const[t,s]=this.parentDimensions,{_borderLineWidth:e}=Ht,i=e/t,n=e/s;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:s},pageDimensions:[e,i]}=this;let{x:n,y:r,width:o,height:h}=this;if(o*=e,h*=i,n*=e,r*=i,this._mustFixPosition)switch(t){case 0:n=W(n,0,e-o),r=W(r,0,i-h);break;case 90:n=W(n,0,e-h),r=W(r,o,i);break;case 180:n=W(n,o,e),r=W(r,h,i);break;case 270:n=W(n,h,e),r=W(r,0,i-o)}this.x=n/=e,this.y=r/=i;const[a,l]=this.getBaseTranslation();n+=a,r+=l,s.left=`${(100*n).toFixed(2)}%`,s.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#Ae(t,s,e){switch(e){case 90:return[s,-t];case 180:return[-t,-s];case 270:return[-s,t];default:return[t,s]}}screenToPageTranslation(t,s){return Ht.#Ae(t,s,this.parentRotation)}pageTranslationToScreen(t,s){return Ht.#Ae(t,s,360-this.parentRotation)}#we(t){switch(t){case 90:{const[t,s]=this.pageDimensions;return[0,-t/s,s/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,s]=this.pageDimensions;return[0,t/s,-s/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:[s,e]}=this;return[s*t,e*t]}setDims(){const{div:{style:t},width:s,height:e}=this;t.width=`${(100*s).toFixed(2)}%`,t.height=`${(100*e).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#be(){if(this.#Qs)return;this.#Qs=document.createElement("div"),this.#Qs.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],s=this._uiManager._signal;for(const e of t){const t=document.createElement("div");this.#Qs.append(t),t.classList.add("resizer",e),t.setAttribute("data-resizer-name",e),t.addEventListener("pointerdown",this.#ye.bind(this,e),{signal:s}),t.addEventListener("contextmenu",ot,{signal:s}),t.tabIndex=-1}this.div.prepend(this.#Qs)}#ye(t,s){s.preventDefault();const{isMac:e}=R.platform;if(0!==s.button||s.ctrlKey&&e)return;this.#l?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#Js=[s.screenX,s.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#ve.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",ht,{passive:!1,signal:r}),window.addEventListener("contextmenu",ot,{signal:r}),this.#Zs={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const o=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(s.target).cursor;const a=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#l?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=o,this.div.style.cursor=h,this.#xe()};window.addEventListener("pointerup",a,{signal:r}),window.addEventListener("blur",a,{signal:r})}#Me(t,s,e,i){this.width=e,this.height=i,this.x=t,this.y=s,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#xe(){if(!this.#Zs)return;const{savedX:t,savedY:s,savedWidth:e,savedHeight:i}=this.#Zs;this.#Zs=null;const n=this.x,r=this.y,o=this.width,h=this.height;n===t&&r===s&&o===e&&h===i||this.addCommands({cmd:this.#Me.bind(this,n,r,o,h),undo:this.#Me.bind(this,t,s,e,i),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#ve(t,s){const[e,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,a=Ht.MIN_SIZE/e,l=Ht.MIN_SIZE/i,c=this.#we(this.rotation),u=(t,s)=>[c[0]*t+c[2]*s,c[1]*t+c[3]*s],d=this.#we(360-this.rotation);let f,p,g=!1,m=!1;switch(t){case"topLeft":g=!0,f=()=>[0,0],p=(t,s)=>[t,s];break;case"topMiddle":f=t=>[t/2,0],p=(t,s)=>[t/2,s];break;case"topRight":g=!0,f=t=>[t,0],p=(t,s)=>[0,s];break;case"middleRight":m=!0,f=(t,s)=>[t,s/2],p=(t,s)=>[0,s/2];break;case"bottomRight":g=!0,f=(t,s)=>[t,s],p=()=>[0,0];break;case"bottomMiddle":f=(t,s)=>[t/2,s],p=t=>[t/2,0];break;case"bottomLeft":g=!0,f=(t,s)=>[0,s],p=t=>[t,0];break;case"middleLeft":m=!0,f=(t,s)=>[0,s/2],p=(t,s)=>[t,s/2]}const A=f(o,h),w=p(o,h);let b=u(...w);const y=Ht._round(n+b[0]),v=Ht._round(r+b[1]);let x,M,k=1,C=1;if(s.fromKeyboard)({deltaX:x,deltaY:M}=s);else{const{screenX:t,screenY:e}=s,[i,n]=this.#Js;[x,M]=this.screenToPageTranslation(t-i,e-n),this.#Js[0]=t,this.#Js[1]=e}var S,T;if([x,M]=[d[0]*(S=x/e)+d[2]*(T=M/i),d[1]*S+d[3]*T],g){const t=Math.hypot(o,h);k=C=Math.max(Math.min(Math.hypot(w[0]-A[0]-x,w[1]-A[1]-M)/t,1/o,1/h),a/o,l/h)}else m?k=W(Math.abs(w[0]-A[0]-x),a,1)/o:C=W(Math.abs(w[1]-A[1]-M),l,1)/h;const P=Ht._round(o*k),E=Ht._round(h*C);b=u(...p(P,E));const D=y-b[0],N=v-b[1];this.#ne||=[this.x,this.y,this.width,this.height],this.width=P,this.height=E,this.x=D,this.y=N,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#l?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#oe)return this._editToolbar;this._editToolbar=new Tt(this),this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[s,e]of t)await this._editToolbar.addButton(s,e);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.#l?.destroy()}addContainer(t){const s=this._editToolbar?.div;s?s.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#l||($t.initialize(Ht._l10n),this.#l=new $t(this),this.#Vs&&(this.#l.data=this.#Vs,this.#Vs=null)),this.#l}get altTextData(){return this.#l?.data}set altTextData(t){this.#l&&(this.#l.data=t)}get guessedAltText(){return this.#l?.guessedText}async setGuessedAltText(t){await(this.#l?.setGuessedText(t))}serializeAltText(t){return this.#l?.serialize(t)}hasAltText(){return!!this.#l&&!this.#l.isEmpty()}hasAltTextData(){return this.#l?.hasData()??!1}focusCommentButton(){this.#c?.focusButton()}addCommentButton(){return this.canAddComment?this.#c||=new Lt(this):null}addStandaloneCommentButton(){this._uiManager.hasCommentManager()&&(this.#ps?this._uiManager.isEditingMode()&&this.#ps.classList.remove("hidden"):this.hasComment&&(this.#ps=this.#c.renderForStandalone(),this.div.append(this.#ps)))}removeStandaloneCommentButton(){this.#c.removeStandaloneCommentButton(),this.#ps=null}hideStandaloneCommentButton(){this.#ps?.classList.add("hidden")}get comment(){if(!this.#c)return null;const{data:{richText:t,text:s,date:e,deleted:i}}=this.#c;return{text:s,richText:t,date:e,deleted:i,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#c||=new Lt(this),"object"==typeof t&&null!==t?this.#c.restoreData(t):this.#c.data=t,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:t,popupRef:s,richText:e}){if(!s)return;if(this.#c||=new Lt(this),this.#c.setInitialText(t,e),!this.annotationElementId)return;const i=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);i&&this.updateFromAnnotationLayer(i)}get hasEditedComment(){return this.#c?.hasBeenEdited()}get hasDeletedComment(){return this.#c?.isDeleted()}get hasComment(){return!!this.#c&&!this.#c.isEmpty()&&!this.#c.isDeleted()}async editComment(t){this.#c||=new Lt(this),this.#c.edit(t)}toggleComment(t,s){this.hasComment&&this._uiManager.toggleComment(this,t,s)}setSelectedCommentButton(t){this.#c.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const s=180,e=100,[,,,i]=t.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,o=r+n+1;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[o,i-e,o+s,i]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:s}}){this.#c.data=s?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.#Ys?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#ke();const[s,e]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*e/s).toFixed(2)}%`,t.style.maxHeight=`${(100*s/e).toFixed(2)}%`);const[i,n]=this.getInitialTranslation();return this.translate(i,n),Dt(this,t,["keydown","pointerdown","dblclick"]),this.#Ce(),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),t}#Se(){this.#Zs={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#l?.toggle(!1),this.parent.togglePointerEvents(!1)}#Te(t,s,e){let i=e/s*.7+1-.7;if(1===i)return;const n=this.#we(this.rotation),r=(t,s)=>[n[0]*t+n[2]*s,n[1]*t+n[3]*s],[o,h]=this.parentDimensions,a=this.x,l=this.y,c=this.width,u=this.height,d=Ht.MIN_SIZE/o,f=Ht.MIN_SIZE/h;i=Math.max(Math.min(i,1/c,1/u),d/c,f/u);const p=Ht._round(c*i),g=Ht._round(u*i);if(p===c&&g===u)return;this.#ne||=[a,l,c,u];const m=r(c/2,u/2),A=Ht._round(a+m[0]),w=Ht._round(l+m[1]),b=r(p/2,g/2);this.x=A-b[0],this.y=w-b[1],this.width=p,this.height=g,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#Pe(){this.#l?.toggle(!0),this.parent.togglePointerEvents(!0),this.#xe()}pointerdown(t){const{isMac:s}=R.platform;0!==t.button||t.ctrlKey&&s?t.preventDefault():(this.#ie=!0,this._isDraggable?this.#Ee(t):this.#De(t))}#De(t){const{isMac:s}=R.platform;t.ctrlKey&&!s||t.shiftKey||t.metaKey&&s?this.parent.toggleSelected(this):this.parent.setSelected(this)}#Ee(t){const{isSelected:s}=this;this._uiManager.setUpDragSession();let e=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},o=t=>{i.abort(),this.#Ks=null,this.#ie=!1,this._uiManager.endDragSession()||this.#De(t),e&&this._onStopDragging()};s&&(this.#le=t.clientX,this.#ce=t.clientY,this.#Ks=t.pointerId,this.#qs=t.pointerType,window.addEventListener("pointermove",(t=>{e||(e=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:s,clientY:i,pointerId:n}=t;if(n!==this.#Ks)return void ht(t);const[r,o]=this.screenToPageTranslation(s-this.#le,i-this.#ce);this.#le=s,this.#ce=i,this._uiManager.dragSelectedEditors(r,o),this.div.scrollIntoView({block:"nearest"})}),r),window.addEventListener("touchmove",ht,r),window.addEventListener("pointerdown",(t=>{t.pointerType===this.#qs&&(this.#de||t.isPrimary)&&o(t),ht(t)}),r));const h=t=>{this.#Ks&&this.#Ks!==t.pointerId?ht(t):o(t)};window.addEventListener("pointerup",h,{signal:n}),window.addEventListener("blur",h,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#ae&&clearTimeout(this.#ae),this.#ae=setTimeout((()=>{this.#ae=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,s,e){t.changeParent(this),this.x=s,this.y=e,this.fixAndSetPosition(),this._onTranslated()}getRect(t,s,e=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[o,h]=this.pageTranslation,a=t/i,l=s/i,c=this.x*n,u=this.y*r,d=this.width*n,f=this.height*r;switch(e){case 0:return[c+a+o,r-u-l-f+h,c+a+d+o,r-u-l+h];case 90:return[c+l+o,r-u+a+h,c+l+f+o,r-u+a+d+h];case 180:return[c-a-d+o,r-u+l+h,c-a+o,r-u+l+f+h];case 270:return[c-l-f+o,r-u-a-d+h,c-l+o,r-u-a+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,s){const[e,i,n,r]=t,o=n-e,h=r-i;switch(this.rotation){case 0:return[e,s-r,o,h];case 90:return[e,s-i,h,o];case 180:return[n,s-i,o,h];case 270:return[n,s-r,h,o];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&Ht._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#c?.onUpdatedColor()}getData(){const{comment:{text:t,color:s,date:e,opacity:i,deleted:n,richText:r},uid:o,pageIndex:h,creationDate:a,modificationDate:l}=this;return{id:o,pageIndex:h,rect:this.getPDFRect(),richText:r,contentsObj:{str:t},creationDate:a,modificationDate:e||l,popupRef:!n,color:s,opacity:i}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#oe=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#oe=!1,!0)}isInEditMode(){return this.#oe}shouldGetKeyboardEvents(){return this.#he}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:s,bottom:e,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return s<r&&i>0&&t<n&&e>0}#ke(){if(this.#se||!this.div)return;this.#se=new AbortController;const t=this._uiManager.combinedSignal(this.#se);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}#Ce(){!this.#de&&this.div&&this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#de=new zt({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Se.bind(this),onPinching:this.#Te.bind(this),onPinchEnd:this.#Pe.bind(this),signal:this._uiManager._signal}))}rebuild(){this.#ke(),this.#Ce()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,s=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,s,e){const i=new this.prototype.constructor({parent:s,id:e.getId(),uiManager:e,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});i.rotation=t.rotation,i.#Vs=t.accessibilityData,i._isCopy=t.isCopy||!1;const[n,r]=i.pageDimensions,[o,h,a,l]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=a/n,i.height=l/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#se?.abort(),this.#se=null,this.isEmpty()||this.commit(),this.#de?.destroy(),this.#de=null,this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#ae&&(clearTimeout(this.#ae),this.#ae=null),this.#ge(),this.removeEditToolbar(),this.#ue){for(const t of this.#ue.values())clearTimeout(t);this.#ue=null}this.parent=null,this.#te?.remove(),this.#te=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#be(),this.#Qs.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,s]}=this,[e,i,n,r]=this.getPDFRect();return[Ht._round(e+(n-e)*t),Ht._round(i+(r-i)*(1-s))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#c.commentPopupPositionInLayer}set commentPopupPosition(t){this.#c.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#c.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#c.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#c?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Zs={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const s=this.#Qs.children;if(!this.#Xs){this.#Xs=Array.from(s);const t=this.#Ne.bind(this),e=this.#Ie.bind(this),i=this._uiManager._signal;for(const s of this.#Xs){const n=s.getAttribute("data-resizer-name");s.setAttribute("role","spinbutton"),s.addEventListener("keydown",t,{signal:i}),s.addEventListener("blur",e,{signal:i}),s.addEventListener("focus",this.#Fe.bind(this,n),{signal:i}),s.setAttribute("data-l10n-id",Ht._l10nResizer[n])}}const e=this.#Xs[0];let i=0;for(const t of s){if(t===e)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Xs.length/4);if(n!==i){if(n<i)for(let t=0;t<i-n;t++)this.#Qs.append(this.#Qs.firstElementChild);else if(n>i)for(let t=0;t<n-i;t++)this.#Qs.firstElementChild.before(this.#Qs.lastElementChild);let t=0;for(const e of s){const s=this.#Xs[t++].getAttribute("data-resizer-name");e.setAttribute("data-l10n-id",Ht._l10nResizer[s])}}this.#_e(0),this.#he=!0,this.#Qs.firstElementChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#Ne(t){Ht._resizerKeyboardManager.exec(this,t)}#Ie(t){this.#he&&t.relatedTarget?.parentNode!==this.#Qs&&this.#ge()}#Fe(t){this.#ee=this.#he?t:""}#_e(t){if(this.#Xs)for(const s of this.#Xs)s.tabIndex=t}_resizeWithKeyboard(t,s){this.#he&&this.#ve(this.#ee,{deltaX:t,deltaY:s,fromKeyboard:!0})}#ge(){this.#he=!1,this.#_e(-1),this.#xe()}_stopResizingWithKeyboard(){this.#ge(),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.#l?.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.#Qs?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#l?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,s){}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.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#re}set isEditing(t){this.#re=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,s=!1){if(s){this.#ue||=new Map;const{action:s}=t;let e=this.#ue.get(s);return e&&clearTimeout(e),e=setTimeout((()=>{this._reportTelemetry(t),this.#ue.delete(s),0===this.#ue.size&&(this.#ue=null)}),Ht._telemetryTimeout),void this.#ue.set(s,e)}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.#Ys=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Ys=!0}updateFakeAnnotationElement(t){if(this.#te||this.deleted)return this.deleted?(this.#te.remove(),void(this.#te=null)):void((this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#te.updateEdited({rect:this.getPDFRect(),popup:this.comment}));this.#te=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;let s=t.container.querySelector(".annotationContent");if(s){if("CANVAS"===s.nodeName){const t=s;s=document.createElement("div"),s.classList.add("annotationContent",this.editorType),t.before(s)}}else s=document.createElement("div"),s.classList.add("annotationContent",this.editorType),t.container.prepend(s);return s}resetAnnotationElement(t){const{firstElementChild:s}=t.container;"DIV"===s?.nodeName&&s.classList.contains("annotationContent")&&s.remove()}}class Wt extends Ht{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Vt=3285377520,Xt=4294901760,Yt=65535;class Kt{constructor(t){this.h1=t?4294967295&t:Vt,this.h2=t?4294967295&t:Vt}update(t){let s,e;if("string"==typeof t){s=new Uint8Array(2*t.length),e=0;for(let i=0,n=t.length;i<n;i++){const n=t.charCodeAt(i);n<=255?s[e++]=n:(s[e++]=n>>>8,s[e++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");s=t.slice(),e=s.byteLength}const i=e>>2,n=e-4*i,r=new Uint32Array(s.buffer,0,i);let o=0,h=0,a=this.h1,l=this.h2;const c=3432918353,u=461845907,d=11601,f=13715;for(let t=0;t<i;t++)1&t?(o=r[t],o=o*c&Xt|o*d&Yt,o=o<<15|o>>>17,o=o*u&Xt|o*f&Yt,a^=o,a=a<<13|a>>>19,a=5*a+3864292196):(h=r[t],h=h*c&Xt|h*d&Yt,h=h<<15|h>>>17,h=h*u&Xt|h*f&Yt,l^=h,l=l<<13|l>>>19,l=5*l+3864292196);switch(o=0,n){case 3:o^=s[4*i+2]<<16;case 2:o^=s[4*i+1]<<8;case 1:o^=s[4*i],o=o*c&Xt|o*d&Yt,o=o<<15|o>>>17,o=o*u&Xt|o*f&Yt,1&i?a^=o:l^=o}this.h1=a,this.h2=l}hexdigest(){let t=this.h1,s=this.h2;return t^=s>>>1,t=3981806797*t&Xt|36045*t&Yt,s=4283543511*s&Xt|(2950163797*(s<<16|t>>>16)&Xt)>>>16,t^=s>>>1,t=444984403*t&Xt|60499*t&Yt,s=3301882366*s&Xt|(3120437893*(s<<16|t>>>16)&Xt)>>>16,t^=s>>>1,(t>>>0).toString(16).padStart(8,"0")+(s>>>0).toString(16).padStart(8,"0")}}const qt=Object.freeze({map:null,hash:"",transfer:void 0});class Qt{#Re=!1;#Oe=null;#Be=null;#$e=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(t,s){const e=this.#$e.get(t);return void 0===e?s:Object.assign(s,e)}getRawValue(t){return this.#$e.get(t)}remove(t){const s=this.#$e.get(t);void 0!==s&&(s instanceof Ht&&this.#Be.delete(s.annotationElementId),this.#$e.delete(t),0===this.#$e.size&&this.resetModified(),this.#$e.values().some((t=>t instanceof Ht))||this.onAnnotationEditor?.(null))}setValue(t,s){const e=this.#$e.get(t);let i=!1;if(void 0!==e)for(const[t,n]of Object.entries(s))e[t]!==n&&(i=!0,e[t]=n);else i=!0,this.#$e.set(t,s);i&&this.#Le(),s instanceof Ht&&((this.#Be||=new Map).set(s.annotationElementId,s),this.onAnnotationEditor?.(s.constructor._type))}has(t){return this.#$e.has(t)}get size(){return this.#$e.size}#Le(){this.#Re||(this.#Re=!0,this.onSetModified?.())}resetModified(){this.#Re&&(this.#Re=!1,this.onResetModified?.())}get print(){return new Jt(this)}get serializable(){if(0===this.#$e.size)return qt;const t=new Map,s=new Kt,e=[],i=Object.create(null);let n=!1;for(const[e,r]of this.#$e){const o=r instanceof Ht?r.serialize(!1,i):r;r.page&&(r.pageIndex=r.page._pageIndex,delete r.page),o&&(t.set(e,o),s.update(`${e}:${JSON.stringify(o)}`),n||=!!o.bitmap)}if(n)for(const s of t.values())s.bitmap&&e.push(s.bitmap);return t.size>0?{map:t,hash:s.hexdigest(),transfer:e}:qt}get editorStats(){let t=null;const s=new Map;let e=0,i=0;for(const n of this.#$e.values()){if(!(n instanceof Ht)){n.popup&&(n.popup.deleted?i+=1:e+=1);continue}n.isCommentDeleted?i+=1:n.hasEditedComment&&(e+=1);const r=n.telemetryFinalData;if(!r)continue;const{type:o}=r;s.getOrInsertComputed(o,(()=>Object.getPrototypeOf(n).constructor)),t||=Object.create(null);const h=t[o]||=new Map;for(const[t,s]of Object.entries(r)){if("type"===t)continue;const e=h.getOrInsertComputed(t,G);e.set(s,(e.get(s)??0)+1)}}if((i>0||e>0)&&(t||=Object.create(null),t.comments={deleted:i,edited:e}),!t)return null;for(const[e,i]of s)t[e]=i.computeTelemetryFinalData(t[e]);return t}resetModifiedIds(){this.#Oe=null}updateEditor(t,s){const e=this.#Be?.get(t);return!!e&&(e.updateFromAnnotationLayer(s),!0)}getEditor(t){return this.#Be?.get(t)||null}get modifiedIds(){if(this.#Oe)return this.#Oe;const t=[];if(this.#Be)for(const s of this.#Be.values())s.serialize()&&t.push(s.annotationElementId);let s="";if(t.length){const e=new Kt;e.update(t.join(",")),s=e.hexdigest()}return this.#Oe={ids:new Set(t),hash:s}}[Symbol.iterator](){return this.#$e.entries()}}class Jt extends Qt{#Ue=qt;constructor(t){super();const{serializable:s}=t;if(s===qt)return;const{map:e,hash:i,transfer:n}=s,r=structuredClone(e,n?{transfer:n}:null);this.#Ue={map:r,hash:i,transfer:[]}}get print(){v("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Ue}get modifiedIds(){return S(this,"modifiedIds",{ids:new Set,hash:""})}}const Zt="__forcedDependency",{floor:ts,ceil:ss}=Math;function es(t,s,e,i,n,r){t[4*s+0]=Math.min(t[4*s+0],e),t[4*s+1]=Math.min(t[4*s+1],i),t[4*s+2]=Math.max(t[4*s+2],n),t[4*s+3]=Math.max(t[4*s+3],r)}const is=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class ns{#je;#Ge;constructor(t,s){this.#je=t,this.#Ge=s}get length(){return this.#je.length}isEmpty(t){return this.#je[t]===is}minX(t){return this.#Ge[4*t+0]/256}minY(t){return this.#Ge[4*t+1]/256}maxX(t){return(this.#Ge[4*t+2]+1)/256}maxY(t){return(this.#Ge[4*t+3]+1)/256}}const rs=(t,s)=>t?.getOrInsertComputed(s,(()=>({dependencies:new Set,isRenderingOperation:!1})));class os{#ze=[[1,0,0,1,0,0]];#He=[-1/0,-1/0,1/0,1/0];#We=new Float64Array(s);_pendingBBoxIdx=-1;#Ve;#Xe;#Ye;#je;_savesStack=[];_markedContentStack=[];constructor(t,s){this.#Ve=t.width,this.#Xe=t.height,this.#Ke(s)}growOperationsCount(t){t>=this.#je.length&&this.#Ke(t,this.#je)}#Ke(t,s){const e=new ArrayBuffer(4*t);this.#Ye=new Uint8ClampedArray(e),this.#je=new Uint32Array(e),s&&s.length>0?(this.#je.set(s),this.#je.fill(is,s.length)):this.#je.fill(is)}get clipBox(){return this.#He}save(t){return this.#He={__proto__:this.#He},this._savesStack.push(t),this}restore(t,s){const e=Object.getPrototypeOf(this.#He);if(null===e)return this;this.#He=e;const i=this._savesStack.pop();return void 0!==i&&(s?.(i,t),this.#je[t]=this.#je[i]),this}recordOpenMarker(t){return this._savesStack.push(t),this}getOpenMarker(){return 0===this._savesStack.length?null:this._savesStack.at(-1)}recordCloseMarker(t,s){const e=this._savesStack.pop();return void 0!==e&&(s?.(e,t),this.#je[t]=this.#je[e]),this}beginMarkedContent(t){return this._markedContentStack.push(t),this}endMarkedContent(t,s){const e=this._markedContentStack.pop();return void 0!==e&&(s?.(e,t),this.#je[t]=this.#je[e]),this}pushBaseTransform(t){return this.#ze.push(O.multiplyByDOMMatrix(this.#ze.at(-1),t.getTransform())),this}popBaseTransform(){return this.#ze.length>1&&this.#ze.pop(),this}resetBBox(t){return this._pendingBBoxIdx!==t&&(this._pendingBBoxIdx=t,this.#We.set(s,0)),this}recordClipBox(t,e,i,n,r,o){const h=O.multiplyByDOMMatrix(this.#ze.at(-1),e.getTransform()),a=s.slice();O.axialAlignedBoundingBox([i,r,n,o],h,a);const l=O.intersect(this.#He,a);return l?(this.#He[0]=l[0],this.#He[1]=l[1],this.#He[2]=l[2],this.#He[3]=l[3]):(this.#He[0]=this.#He[1]=1/0,this.#He[2]=this.#He[3]=-1/0),this}recordBBox(t,e,i,n,r,o){const h=this.#He;if(h[0]===1/0)return this;const a=O.multiplyByDOMMatrix(this.#ze.at(-1),e.getTransform());if(h[0]===-1/0)return O.axialAlignedBoundingBox([i,r,n,o],a,this.#We),this;const l=s.slice();return O.axialAlignedBoundingBox([i,r,n,o],a,l),this.#We[0]=W(l[0],h[0],this.#We[0]),this.#We[1]=W(l[1],h[1],this.#We[1]),this.#We[2]=W(l[2],this.#We[2],h[2]),this.#We[3]=W(l[3],this.#We[3],h[3]),this}recordFullPageBBox(t){return this.#We[0]=Math.max(0,this.#He[0]),this.#We[1]=Math.max(0,this.#He[1]),this.#We[2]=Math.min(this.#Ve,this.#He[2]),this.#We[3]=Math.min(this.#Xe,this.#He[3]),this}recordOperation(t,s=!1,e){if(this._pendingBBoxIdx!==t)return this;const i=ts(256*this.#We[0]/this.#Ve),n=ts(256*this.#We[1]/this.#Xe),r=ss(256*this.#We[2]/this.#Ve),o=ss(256*this.#We[3]/this.#Xe);if(es(this.#Ye,t,i,n,r,o),e)for(const s of e)for(const e of s)e!==t&&es(this.#Ye,e,i,n,r,o);return s||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(t){return this._pendingBBoxIdx===t&&(this._pendingBBoxIdx=-1,this.#He[0]=Math.max(this.#He[0],this.#We[0]),this.#He[1]=Math.max(this.#He[1],this.#We[1]),this.#He[2]=Math.min(this.#He[2],this.#We[2]),this.#He[3]=Math.min(this.#He[3],this.#We[3])),this}take(){return new ns(this.#je,this.#Ye)}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(t,s){return this}recordIncrementalData(t,s){return this}resetIncrementalData(t,s){return this}recordNamedData(t,s){return this}recordSimpleDataFromNamed(t,s,e){return this}recordFutureForcedDependency(t,s){return this}inheritSimpleDataAsFutureForcedDependencies(t){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(t,s,e,i=1,n=0,r=0,o){return this}getSimpleIndex(t){}recordDependencies(t,s){return this}recordNamedDependency(t,s){return this}recordShowTextOperation(t,s=!1){return this}}class hs{#qe={__proto__:null};#Qe={__proto__:null,transform:[],moveText:[],sameLineText:[],[Zt]:[]};#Je=new Map;#Ze=new Set;#ti=new Map;#si;#ei;#ii;constructor(t,s=!1){this.#ii=t,s&&(this.#si=new Map,this.#ei=(t,s)=>{rs(this.#si,s).dependencies.add(t)})}get clipBox(){return this.#ii.clipBox}growOperationsCount(t){this.#ii.growOperationsCount(t)}save(t){return this.#qe={__proto__:this.#qe},this.#Qe={__proto__:this.#Qe,transform:{__proto__:this.#Qe.transform},moveText:{__proto__:this.#Qe.moveText},sameLineText:{__proto__:this.#Qe.sameLineText},[Zt]:{__proto__:this.#Qe[Zt]}},this.#ii.save(t),this}restore(t){this.#ii.restore(t,this.#ei);const s=Object.getPrototypeOf(this.#qe);return null===s||(this.#qe=s,this.#Qe=Object.getPrototypeOf(this.#Qe)),this}recordOpenMarker(t){return this.#ii.recordOpenMarker(t,this.#ei),this}getOpenMarker(){return this.#ii.getOpenMarker()}recordCloseMarker(t){return this.#ii.recordCloseMarker(t,this.#ei),this}beginMarkedContent(t){return this.#ii.beginMarkedContent(t),this}endMarkedContent(t){return this.#ii.endMarkedContent(t,this.#ei),this}pushBaseTransform(t){return this.#ii.pushBaseTransform(t),this}popBaseTransform(){return this.#ii.popBaseTransform(),this}recordSimpleData(t,s){return this.#qe[t]=s,this}recordIncrementalData(t,s){return this.#Qe[t].push(s),this}resetIncrementalData(t,s){return this.#Qe[t].length=0,this}recordNamedData(t,s){return this.#Je.set(t,s),this}recordSimpleDataFromNamed(t,s,e){this.#qe[t]=this.#Je.get(s)??e}recordFutureForcedDependency(t,s){return this.recordIncrementalData(Zt,s),this}inheritSimpleDataAsFutureForcedDependencies(t){for(const s of t)s in this.#qe&&this.recordFutureForcedDependency(s,this.#qe[s]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#Ze)this.recordFutureForcedDependency(Zt,t);return this}resetBBox(t){return this.#ii.resetBBox(t),this}recordClipBox(t,s,e,i,n,r){return this.#ii.recordClipBox(t,s,e,i,n,r),this}recordBBox(t,s,e,i,n,r){return this.#ii.recordBBox(t,s,e,i,n,r),this}recordCharacterBBox(t,s,e,i=1,n=0,r=0,o){const h=e.bbox;let a,l;if(h&&(a=h[2]!==h[0]&&h[3]!==h[1]&&this.#ti.get(e),!1!==a&&(l=[0,0,0,0],O.axialAlignedBoundingBox(h,e.fontMatrix,l),1===i&&0===n&&0===r||function(t,s,e,i,n){let r;t?(t<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=t,n[2]*=t,s<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=s,n[3]*=s):n.fill(0),n[0]+=e,n[1]+=i,n[2]+=e,n[3]+=i}(i,-i,n,r,l),a)))return this.recordBBox(t,s,l[0],l[2],l[1],l[3]);if(!o)return this.recordFullPageBBox(t);const c=o();return h&&l&&void 0===a&&(a=l[0]<=n-c.actualBoundingBoxLeft&&l[2]>=n+c.actualBoundingBoxRight&&l[1]<=r-c.actualBoundingBoxAscent&&l[3]>=r+c.actualBoundingBoxDescent,this.#ti.set(e,a),a)?this.recordBBox(t,s,l[0],l[2],l[1],l[3]):this.recordBBox(t,s,n-c.actualBoundingBoxLeft,n+c.actualBoundingBoxRight,r-c.actualBoundingBoxAscent,r+c.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#ii.recordFullPageBBox(t),this}getSimpleIndex(t){return this.#qe[t]}recordDependencies(t,s){const e=this.#Ze,i=this.#qe,n=this.#Qe;for(const t of s)t in this.#qe?e.add(i[t]):t in n&&n[t].forEach(e.add,e);return this}recordNamedDependency(t,s){return this.#Je.has(s)&&this.#Ze.add(this.#Je.get(s)),this}recordOperation(t,s=!1){if(this.recordDependencies(t,[Zt]),this.#si){const s=rs(this.#si,t),{dependencies:e}=s;this.#Ze.forEach(e.add,e),this.#ii._savesStack.forEach(e.add,e),this.#ii._markedContentStack.forEach(e.add,e),e.delete(t),s.isRenderingOperation=!0}const e=!s&&t===this.#ii._pendingBBoxIdx;return this.#ii.recordOperation(t,s,[this.#Ze,this.#ii._savesStack,this.#ii._markedContentStack]),e&&this.#Ze.clear(),this}recordShowTextOperation(t,s=!1){const e=Array.from(this.#Ze);this.recordOperation(t,s),this.recordIncrementalData("sameLineText",t);for(const t of e)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,s=!1){const e=!s&&t===this.#ii._pendingBBoxIdx;return this.#ii.bboxToClipBoxDropOperation(t),e&&this.#Ze.clear(),this}take(){return this.#ti.clear(),this.#ii.take()}takeDebugMetadata(){return this.#si}}class as{#ni;#ri;#oi;#hi=0;#ai=0;constructor(t,s,e){if(t instanceof as&&t.#oi===!!e)return t;this.#ni=t,this.#ri=s,this.#oi=!!e}get clipBox(){return this.#ni.clipBox}growOperationsCount(){throw new Error("Unreachable")}save(t){return this.#ai++,this.#ni.save(this.#ri),this}restore(t){return this.#ai>0&&(this.#ni.restore(this.#ri),this.#ai--),this}recordOpenMarker(t){return this.#hi++,this}getOpenMarker(){return this.#hi>0?this.#ri:this.#ni.getOpenMarker()}recordCloseMarker(t){return this.#hi--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#ni.pushBaseTransform(t),this}popBaseTransform(){return this.#ni.popBaseTransform(),this}recordSimpleData(t,s){return this.#ni.recordSimpleData(t,this.#ri),this}recordIncrementalData(t,s){return this.#ni.recordIncrementalData(t,this.#ri),this}resetIncrementalData(t,s){return this.#ni.resetIncrementalData(t,this.#ri),this}recordNamedData(t,s){return this}recordSimpleDataFromNamed(t,s,e){return this.#ni.recordSimpleDataFromNamed(t,s,this.#ri),this}recordFutureForcedDependency(t,s){return this.#ni.recordFutureForcedDependency(t,this.#ri),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#ni.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#ni.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#oi||this.#ni.resetBBox(this.#ri),this}recordClipBox(t,s,e,i,n,r){return this.#oi||this.#ni.recordClipBox(this.#ri,s,e,i,n,r),this}recordBBox(t,s,e,i,n,r){return this.#oi||this.#ni.recordBBox(this.#ri,s,e,i,n,r),this}recordCharacterBBox(t,s,e,i,n,r,o){return this.#oi||this.#ni.recordCharacterBBox(this.#ri,s,e,i,n,r,o),this}recordFullPageBBox(t){return this.#oi||this.#ni.recordFullPageBBox(this.#ri),this}getSimpleIndex(t){return this.#ni.getSimpleIndex(t)}recordDependencies(t,s){return this.#ni.recordDependencies(this.#ri,s),this}recordNamedDependency(t,s){return this.#ni.recordNamedDependency(this.#ri,s),this}recordOperation(t){return this.#ni.recordOperation(this.#ri,!0),this}recordShowTextOperation(t){return this.#ni.recordShowTextOperation(this.#ri,!0),this}bboxToClipBoxDropOperation(t){return this.#oi||this.#ni.bboxToClipBoxDropOperation(this.#ri,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const ls=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],cs=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],us=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],ds=["filter","fillColor","fillAlpha"],fs=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],ps=["transform"],gs=["transform","fillColor"];class ms{#Ve;#Xe;#li=4;#ci=0;#Ge=new ms.#ui(6*this.#li);static#ui=R.isFloat16ArraySupported?Float16Array:Float32Array;constructor(t){this.#Ve=t.width,this.#Xe=t.height}record(t,e,i,n){if(this.#ci===this.#li){this.#li*=2;const t=new ms.#ui(6*this.#li);t.set(this.#Ge),this.#Ge=t}const r=ut(t);let o;if(n[0]!==1/0){const t=s.slice();O.axialAlignedBoundingBox([0,-i,e,0],r,t);const h=O.intersect(n,t);if(!h)return;const[a,l,c,u]=h;if(a!==t[0]||l!==t[1]||c!==t[2]||u!==t[3]){const t=Math.atan2(r[1],r[0]),s=Math.abs(Math.sin(t)),e=Math.abs(Math.cos(t));if(s<1e-6||e<1e-6||Math.abs(s-e)<1e-6)o=[a,l,a,u,c,l];else{const t=c-a,i=u-l,n=s*s,r=e*e,h=e*s,d=r-n,f=(i*r-t*h)/d;o=[a+(i*h-t*n)/d,l,a,l+f,c,u-f]}}}o||(o=[0,-i,0,0,e,-i],O.applyTransform(o,r,0),O.applyTransform(o,r,2),O.applyTransform(o,r,4)),o[0]/=this.#Ve,o[1]/=this.#Xe,o[2]/=this.#Ve,o[3]/=this.#Xe,o[4]/=this.#Ve,o[5]/=this.#Xe,this.#Ge.set(o,6*this.#ci),this.#ci++}take(){return this.#Ge.subarray(0,6*this.#ci)}}const As=/\p{Cc}/u;function ws(t){return function(t){const s=t[0];if(t.length<2||'"'!==s&&"'"!==s||t.at(-1)!==s)return!1;const e=t.length-1;for(let i=1;i<e;i++){const n=t[i];if(n===s||As.test(n))return!1;if("\\"===n&&(++i>=e||As.test(t[i])))return!1}return!0}(t)?t:`"${t.replaceAll(/["\\\p{Cc}]/gu,(t=>'"'===t||"\\"===t?`\\${t}`:`\\${t.codePointAt(0).toString(16)} `))}"`}class bs{#di=new Set;#fi=null;constructor({ownerDocument:t=globalThis.document,styleElement:s=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){const s=this.#pi();s.insertRule(t,s.cssRules.length)}#pi(){if(this.#fi)return this.#fi;const t=this._document.defaultView?.CSSStyleSheet||globalThis.CSSStyleSheet;if(!this.styleElement&&t){const{adoptedStyleSheets:s}=this._document;if(s){const e=new t;return s.push(e),this.#fi=e}}return this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)),this.#fi=this.styleElement.sheet}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);if(this.nativeFontFaces.clear(),this.#di.clear(),this.#fi){const{adoptedStyleSheets:t}=this._document;t?.includes(this.#fi)&&(this._document.adoptedStyleSheets=t.filter((t=>t!==this.#fi))),this.#fi=null}this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:s,_inspectFont:e}){if(t&&!this.#di.has(t.loadedName))if(x(!s,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,r=new FontFace(s,i,n);this.addNativeFontFace(r);try{await r.load(),this.#di.add(s),e?.(t)}catch{y(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}}else v("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 s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(e){throw y(`Failed to load font '${s.family}': '${e}'.`),t.disableFontFace=!0,e}}return}const s=t.createFontFaceRule();if(s){if(this.insertRule(s),this.isSyncFontLoadingSupported)return;await new Promise((s=>{const e=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,e)}))}}get isFontLoadingAPISupported(){return S(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return S(this,"isSyncFontLoadingSupported",t||R.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:s}=this,e={done:!1,complete:function(){for(x(!e.done,"completeRequest() cannot be called twice."),e.done=!0;s.length>0&&s[0].done;){const t=s.shift();setTimeout(t.callback,0)}},callback:t};return s.push(e),e}get _loadTestFont(){return S(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,s){function e(t,s){return t.charCodeAt(s)<<24|t.charCodeAt(s+1)<<16|t.charCodeAt(s+2)<<8|255&t.charCodeAt(s+3)}function i(t,s,e,i){return t.substring(0,s)+i+t.substring(s+e)}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let a=0;const l=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=i(c,976,l.length,l);const u=1482184792;let d=e(c,16);for(n=0,r=l.length-3;n<r;n+=4)d=d-u+e(l,n)|0;var f;n<l.length&&(d=d-u+e(l+"XXX",n)|0),c=i(c,16,4,(f=d,String.fromCharCode(f>>24&255,f>>16&255,f>>8&255,255&f)));const p=`url(data:font/opentype;base64,${btoa(c)});`;this.insertRule(`@font-face {font-family:"${l}";src:${p}}`);const g=this._document.createElement("div");g.style.visibility="hidden",g.style.width=g.style.height="10px",g.style.position="absolute",g.style.top=g.style.left="0px";for(const s of[t.loadedName,l]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=s,g.append(t)}this._document.body.append(g),function t(s,e){if(++a>30)return y("Load test font never loaded."),void e();h.font="30px "+s,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0?e():setTimeout(t.bind(null,s,e))}(l,(()=>{g.remove(),s.complete()}))}}class ys{compiledGlyphs=Object.create(null);#gi;constructor(t,s=null,e,i){this.#gi=t,this._inspectFont=s,e&&(this.charProcOperatorList=e),i&&Object.assign(this,i)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const s={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(s.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(ws(this.cssFontInfo.fontFamily),this.data,s)}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,${this.data.toBase64()});`;let s;if(this.cssFontInfo){let e=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(e+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),s=`@font-face {font-family:${ws(this.cssFontInfo.fontFamily)};${e}src:${t}}`}else s=`@font-face {font-family:"${this.loadedName}";src:${t}}`;return this._inspectFont?.(this,t),s}getPathGenerator(t,s){if(void 0!==this.compiledGlyphs[s])return this.compiledGlyphs[s];const e=this.loadedName+"_path_"+s;let i;try{i=t.get(e)}catch(t){y(`getPathGenerator - ignoring character: "${t}".`)}const n=St(i?.path);return this.fontExtraProperties||t.delete(e),this.compiledGlyphs[s]=n}get black(){return this.#gi.black}get bold(){return this.#gi.bold}get disableFontFace(){return this.#gi.disableFontFace}set disableFontFace(t){S(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#gi.fontExtraProperties}get isInvalidPDFjsFont(){return this.#gi.isInvalidPDFjsFont}get isType3Font(){return this.#gi.isType3Font}get italic(){return this.#gi.italic}get missingFile(){return this.#gi.missingFile}get remeasure(){return this.#gi.remeasure}get vertical(){return this.#gi.vertical}get ascent(){return this.#gi.ascent}get defaultWidth(){return this.#gi.defaultWidth}get descent(){return this.#gi.descent}get bbox(){return this.#gi.bbox}get fontMatrix(){return this.#gi.fontMatrix}get fallbackName(){return this.#gi.fallbackName}get loadedName(){return this.#gi.loadedName}get mimetype(){return this.#gi.mimetype}get name(){return this.#gi.name}get data(){return this.#gi.data}clearData(){this.#gi.clearData()}get cssFontInfo(){return this.#gi.cssFontInfo}get systemFontInfo(){return this.#gi.systemFontInfo}get defaultVMetrics(){return this.#gi.defaultVMetrics}}class vs{static strings=["fontFamily","fontWeight","italicAngle"]}class xs{static strings=["css","loadedName","baseFontName","src"]}class Ms{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static OFFSET_NUMBERS=Math.ceil(2*this.bools.length/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+8*this.numbers.length;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6}class ks{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16}class Cs{static get decoder(){return S(this,"decoder",new TextDecoder)}static get encoder(){return S(this,"encoder",new TextEncoder)}}class Ss{#mi;#Ai;constructor(t){this.#mi=t,this.#Ai=new DataView(t)}#wi(t){x(t<vs.strings.length,"Invalid string index");const{decoder:s}=Cs;let e=0;for(let s=0;s<t;s++)e+=this.#Ai.getUint32(e)+4;const i=this.#Ai.getUint32(e);return s.decode(new Uint8Array(this.#mi,e+4,i))}get fontFamily(){return this.#wi(0)}get fontWeight(){return this.#wi(1)}get italicAngle(){return this.#wi(2)}}class Ts{#mi;#Ai;constructor(t){this.#mi=t,this.#Ai=new DataView(t)}get guessFallback(){return 0!==this.#Ai.getUint8(0)}#wi(t){x(t<xs.strings.length,"Invalid string index");const{decoder:s}=Cs;let e=5;for(let s=0;s<t;s++)e+=this.#Ai.getUint32(e)+4;const i=this.#Ai.getUint32(e);return s.decode(new Uint8Array(this.#mi,e+4,i))}get css(){return this.#wi(0)}get loadedName(){return this.#wi(1)}get baseFontName(){return this.#wi(2)}get src(){return this.#wi(3)}get style(){const{decoder:t}=Cs;let s=1;s+=4+this.#Ai.getUint32(s);const e=this.#Ai.getUint32(s),i=t.decode(new Uint8Array(this.#mi,s+4,e));s+=4+e;const n=this.#Ai.getUint32(s);return{style:i,weight:t.decode(new Uint8Array(this.#mi,s+4,n))}}}class Ps{#mi;#Ai;constructor({buffer:t,extra:s}){this.#mi=t,this.#Ai=new DataView(t),s&&Object.assign(this,s)}#bi(t){x(t<Ms.bools.length,"Invalid boolean index");const s=Math.floor(t/4),e=2*t%8,i=this.#Ai.getUint8(s)>>e&3;return 0===i?void 0:2===i}get black(){return this.#bi(0)}get bold(){return this.#bi(1)}get disableFontFace(){return this.#bi(2)}get fontExtraProperties(){return this.#bi(3)}get isInvalidPDFjsFont(){return this.#bi(4)}get isType3Font(){return this.#bi(5)}get italic(){return this.#bi(6)}get missingFile(){return this.#bi(7)}get remeasure(){return this.#bi(8)}get vertical(){return this.#bi(9)}#yi(t){return x(t<Ms.numbers.length,"Invalid number index"),this.#Ai.getFloat64(Ms.OFFSET_NUMBERS+8*t)}get ascent(){return this.#yi(0)}get defaultWidth(){return this.#yi(1)}get descent(){return this.#yi(2)}#vi(t,s,e,i){const n=this.#Ai.getUint8(t);if(0===n)return;x(n===s,"Invalid array length."),t+=1;const r=new Array(n);for(let s=0;s<n;s++)r[s]=this.#Ai[e](t,!0),t+=i;return r}get bbox(){return this.#vi(Ms.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return this.#vi(Ms.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return this.#vi(Ms.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}#wi(t){x(t<Ms.strings.length,"Invalid string index");const{decoder:s}=Cs;let e=Ms.OFFSET_STRINGS+4;for(let s=0;s<t;s++)e+=this.#Ai.getUint32(e)+4;const i=this.#Ai.getUint32(e);return s.decode(new Uint8Array(this.#mi,e+4,i))}get fallbackName(){return this.#wi(0)}get loadedName(){return this.#wi(1)}get mimetype(){return this.#wi(2)}get name(){return this.#wi(3)}#xi(){let t=Ms.OFFSET_STRINGS;return t+=4+this.#Ai.getUint32(t),t+=4+this.#Ai.getUint32(t),t+=4+this.#Ai.getUint32(t),{offset:t,length:this.#Ai.getUint32(t)}}get data(){const{offset:t,length:s}=this.#xi();return 0===s?void 0:new Uint8Array(this.#mi,t+4,s)}clearData(){const{offset:t,length:s}=this.#xi();0!==s&&(this.#Ai.setUint32(t,0),this.#mi=new Uint8Array(this.#mi,0,t+4).slice().buffer,this.#Ai=new DataView(this.#mi))}get cssFontInfo(){let t=Ms.OFFSET_STRINGS;t+=4+this.#Ai.getUint32(t),t+=4+this.#Ai.getUint32(t);const s=this.#Ai.getUint32(t);if(0===s)return null;const e=new Uint8Array(s);return e.set(new Uint8Array(this.#mi,t+4,s)),new Ss(e.buffer)}get systemFontInfo(){let t=Ms.OFFSET_STRINGS;t+=4+this.#Ai.getUint32(t);const s=this.#Ai.getUint32(t);if(0===s)return null;const e=new Uint8Array(s);return e.set(new Uint8Array(this.#mi,t+4,s)),new Ts(e.buffer)}}class Es{constructor(t){this.buffer=t,this.view=new DataView(t),this.data=new Uint8Array(t)}getIR(){const t=this.view,e=this.data[ks.KIND],i=!!this.data[ks.HAS_BBOX],n=!!this.data[ks.HAS_BACKGROUND],r=t.getUint32(ks.N_COORD,!0),o=t.getUint32(ks.N_COLOR,!0),h=t.getUint32(ks.N_STOP,!0);let a=20;const l=new Float32Array(this.buffer,a,2*r);a+=8*r;const c=new Uint8Array(this.buffer,a,4*o);a+=4*o;const u=[];for(let s=0;s<h;++s){const s=t.getFloat32(a,!0);a+=4;const e=t.getUint32(a,!0);a+=4,u.push([s,`#${e.toString(16).padStart(6,"0")}`])}let d=null;if(i){d=[];for(let s=0;s<4;++s)d.push(t.getFloat32(a,!0)),a+=4}let f=null;if(n&&(f=new Uint8Array(this.buffer,a,3),a+=3),1===e)return["RadialAxial","axial",d,u,Array.from(l.slice(0,2)),Array.from(l.slice(2,4)),null,null];if(2===e)return["RadialAxial","radial",d,u,[l[0],l[1]],[l[3],l[4]],l[2],l[5]];if(3===e){const t=this.data[ks.SHADING_TYPE];let e=null;if(l.length>0){e=s.slice();for(let t=0,s=l.length;t<s;t+=2)O.pointBoundingBox(l[t],l[t+1],e)}return["Mesh",t,l,c,r,e,d,f]}throw new Error(`Unsupported pattern kind: ${e}`)}}class Ds{#mi;constructor(t){this.#mi=t}get path(){return R.isFloat16ArraySupported?new Float16Array(this.#mi):new Float32Array(this.#mi)}}function Ns(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const Is=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,Fs=function(t,s,e){if(!Array.isArray(e)||e.length<2)return!1;const[i,n,...r]=e;if(!t(i)&&!Number.isInteger(i))return!1;if(!s(n))return!1;const o=r.length;let h=!0;switch(n.name){case"XYZ":if(o<2||o>3)return!1;break;case"Fit":case"FitB":return 0===o;case"FitH":case"FitBH":case"FitV":case"FitBV":if(o>1)return!1;break;case"FitR":if(4!==o)return!1;h=!1;break;default:return!1}for(const t of r)if(!("number"==typeof t||h&&null===t))return!1;return!0}.bind(null,Is,(t=>"object"==typeof t&&"string"==typeof t?.name));class _s{#Mi=new Map;#ki=Promise.resolve();postMessage(t,s){const e={data:structuredClone(t,s?{transfer:s}:null)};this.#ki.then((()=>{for(const[t]of this.#Mi)t.call(this,e)}))}addEventListener(t,s,e=null){let i=null;if(e?.signal instanceof AbortSignal){const{signal:n}=e;if(n.aborted)return void y("LoopbackPort - cannot use an `aborted` signal.");const r=()=>this.removeEventListener(t,s);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#Mi.set(s,i)}removeEventListener(t,s){const e=this.#Mi.get(s);e?.(),this.#Mi.delete(s)}terminate(){for(const[,t]of this.#Mi)t?.();this.#Mi.clear()}}function Rs(){}function Os(t){if(t instanceof F||t instanceof D||t instanceof P||t instanceof N||t instanceof E)return t;switch(t instanceof Error||"object"==typeof t&&null!==t||v('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new F(t.message);case"InvalidPDFException":return new D(t.message);case"PasswordException":return new P(t.message,t.code);case"ResponseException":return new N(t.message,t.status,t.missing);case"UnknownErrorException":return new E(t.message,t.details)}return new E(t.message,t.toString())}class Bs{#Ci=new AbortController;constructor(t,s,e){this.sourceName=t,this.targetName=s,this.comObj=e,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),e.addEventListener("message",this.#Si.bind(this),{signal:this.#Ci.signal})}#Si({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#Ti(t);if(t.callback){const s=t.callbackId,e=this.callbackCapabilities[s];if(!e)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],1===t.callback)e.resolve(t.data);else{if(2!==t.callback)throw new Error("Unexpected callback case");e.reject(Os(t.reason))}return}const s=this.actionHandler[t.action];if(!s)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const e=this.sourceName,i=t.sourceName,n=this.comObj;Promise.try(s,t.data).then((function(s){n.postMessage({sourceName:e,targetName:i,callback:1,callbackId:t.callbackId,data:s})}),(function(s){n.postMessage({sourceName:e,targetName:i,callback:2,callbackId:t.callbackId,reason:Os(s)})}))}else t.streamId?this.#Pi(t):s(t.data)}on(t,s){const e=this.actionHandler;if(e[t])throw new Error(`There is already an actionName called "${t}"`);e[t]=s}send(t,s,e){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:s},e)}sendWithPromise(t,s,e){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:s},e)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,s,e,i){const n=this.streamId++,r=this.sourceName,o=this.targetName,h=this.comObj;return new ReadableStream({start:e=>{const a=Promise.withResolvers();return this.streamControllers[n]={controller:e,startCall:a,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:o,action:t,streamId:n,data:s,desiredSize:e.desiredSize},i),a.promise},pull:t=>{const s=Promise.withResolvers();return this.streamControllers[n].pullCall=s,h.postMessage({sourceName:r,targetName:o,stream:6,streamId:n,desiredSize:t.desiredSize}),s.promise},cancel:t=>{x(t instanceof Error,"cancel must have a valid reason");const s=Promise.withResolvers();return this.streamControllers[n].cancelCall=s,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:o,stream:1,streamId:n,reason:Os(t)}),s.promise}},e)}#Pi(t){const s=t.streamId,e=this.sourceName,i=t.sourceName,n=this.comObj,r=this,o=this.actionHandler[t.action],h={enqueue(t,r=1,o){if(this.isCancelled)return;const h=this.desiredSize;this.desiredSize-=r,h>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:e,targetName:i,stream:4,streamId:s,chunk:t},o)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:e,targetName:i,stream:3,streamId:s}),delete r.streamSinks[s])},error(t){x(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:e,targetName:i,stream:5,streamId:s,reason:Os(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};h.sinkCapability.resolve(),h.ready=h.sinkCapability.promise,this.streamSinks[s]=h,Promise.try(o,t.data,h).then((function(){n.postMessage({sourceName:e,targetName:i,stream:8,streamId:s,success:!0})}),(function(t){n.postMessage({sourceName:e,targetName:i,stream:8,streamId:s,reason:Os(t)})}))}#Ti(t){const s=t.streamId,e=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[s],o=this.streamSinks[s];switch(t.stream){case 8:t.success?r.startCall.resolve():r.startCall.reject(Os(t.reason));break;case 7:t.success?r.pullCall.resolve():r.pullCall.reject(Os(t.reason));break;case 6:if(!o){n.postMessage({sourceName:e,targetName:i,stream:7,streamId:s,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,Promise.try(o.onPull||Rs).then((function(){n.postMessage({sourceName:e,targetName:i,stream:7,streamId:s,success:!0})}),(function(t){n.postMessage({sourceName:e,targetName:i,stream:7,streamId:s,reason:Os(t)})}));break;case 4:if(x(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case 3:if(x(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#Ei(r,s);break;case 5:x(r,"error should have stream controller"),r.controller.error(Os(t.reason)),this.#Ei(r,s);break;case 2:t.success?r.cancelCall.resolve():r.cancelCall.reject(Os(t.reason)),this.#Ei(r,s);break;case 1:if(!o)break;const h=Os(t.reason);Promise.try(o.onCancel||Rs,h).then((function(){n.postMessage({sourceName:e,targetName:i,stream:2,streamId:s,success:!0})}),(function(t){n.postMessage({sourceName:e,targetName:i,stream:2,streamId:s,reason:Os(t)})})),o.sinkCapability.reject(h),o.isCancelled=!0,delete this.streamSinks[s];break;default:throw new Error("Unexpected stream case")}}async#Ei(t,s){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[s]}destroy(){this.#Ci?.abort(),this.#Ci=null}}class $s{#Di=Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"});constructor({cMapUrl:t=null,standardFontDataUrl:s=null,wasmUrl:e=null}){this.cMapUrl=t,this.standardFontDataUrl=s,this.wasmUrl=e}async fetch({kind:t,filename:s}){switch(t){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:v(`Not implemented: ${t}`)}const e=this[t];if(!e)throw new Error(`Ensure that the \`${t}\` API parameter is provided.`);const i=`${e}${s}`;return this._fetch(i,t).catch((()=>{throw new Error(`Unable to load ${this.#Di[t]} data at: ${i}`)}))}async _fetch(t,s){v("Abstract method `_fetch` called.")}}class Ls extends $s{async _fetch(t,s){const e="cMapUrl"!==s||t.endsWith(".bcmap")?"bytes":"text",i=await J(t,e);return i instanceof Uint8Array?i:_(i)}}class Us{#Ni=!1;constructor({enableHWA:t=!1}){this.#Ni=t}create(t,s){if(t<=0||s<=0)throw new Error("Invalid canvas size");const e=this._createCanvas(t,s);return{canvas:e,context:e.getContext("2d",{willReadFrequently:!this.#Ni})}}reset({canvas:t},s,e){if(!t)throw new Error("Canvas is not specified");if(s<=0||e<=0)throw new Error("Invalid canvas size");t.width=s,t.height=e}destroy(t){const{canvas:s}=t;if(!s)throw new Error("Canvas is not specified");s.width=s.height=0,t.canvas=null,t.context=null}_createCanvas(t,s){v("Abstract method `_createCanvas` called.")}}class js extends Us{constructor({ownerDocument:t=globalThis.document,enableHWA:s=!1}){super({enableHWA:s}),this._document=t}_createCanvas(t,s){const e=this._document.createElement("canvas");return e.width=t,e.height=s,e}}class Gs{addFilter(t){return"none"}addHCMFilter(t,s){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addKnockoutFilter(t=0){return"none"}addHighlightHCMFilter(t,s,e,i,n){return"none"}addSelectionHCMFilter(t,s){return"none"}addSelectionFilter(){return"none"}createSelectionStyle(t=null){return null}destroy(t=!1){}}class zs extends Gs{#Ii;#Fi;#_i;#Ri;#Oi;#Bi;#T=0;constructor({docId:t,ownerDocument:s=globalThis.document}){super(),this.#Ri=t,this.#Oi=s}get#E(){return this.#Fi||=new Map}get#$i(){return this.#Bi||=new Map}get#Li(){if(!this.#_i){const t=this.#Oi.createElement("div"),{style:s}=t;s.colorScheme="only light",s.visibility="hidden",s.contain="strict",s.width=s.height=0,s.position="absolute",s.top=s.left=0,s.zIndex=-1;const e=this.#Oi.createElementNS(n,"svg");e.setAttribute("width",0),e.setAttribute("height",0),this.#_i=this.#Oi.createElementNS(n,"defs"),t.append(e),e.append(this.#_i),this.#Oi.body.append(t)}return this.#_i}#Ui(t){if(1===t.length){const s=t[0],e=new Array(256);for(let t=0;t<256;t++)e[t]=s[t]/255;const i=e.join(",");return[i,i,i]}const[s,e,i]=t,n=new Array(256),r=new Array(256),o=new Array(256);for(let t=0;t<256;t++)n[t]=s[t]/255,r[t]=e[t]/255,o[t]=i[t]/255;return[n.join(","),r.join(","),o.join(",")]}#ji(t){if(void 0===this.#Ii){this.#Ii="";const t=this.#Oi.URL;t!==this.#Oi.baseURI&&(tt(t)?y('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ii=k(t,""))}return`url(${this.#Ii}#${t})`}addFilter(t){if(!t)return"none";let s=this.#E.get(t);if(s)return s;const[e,i,n]=this.#Ui(t),r=1===t.length?e:`${e}${i}${n}`;if(s=this.#E.get(r),s)return this.#E.set(t,s),s;const o=`g_${this.#Ri}_transfer_map_${this.#T++}`,h=this.#ji(o);this.#E.set(t,h),this.#E.set(r,h);const a=this.#Gi(o);return this.#zi(e,i,n,a),h}addHCMFilter(t,s){const e=`${t}-${s}`,i="base";let n=this.#$i.get(i);if(n?.key===e)return n.url;if(n?(n.filter?.remove(),n.key=e,n.url="none",n.filter=null):(n={key:e,url:"none",filter:null},this.#$i.set(i,n)),!t||!s)return n.url;const r=this.#Hi(t);t=O.makeHexColor(...r);const o=this.#Hi(s);if(s=O.makeHexColor(...o),this.#Wi(),"#000000"===t&&"#ffffff"===s||t===s)return n.url;const h=Array.from({length:256},((t,s)=>vt(s/255))).join(","),a=`g_${this.#Ri}_hcm_filter`,l=n.filter=this.#Gi(a);this.#zi(h,h,h,l),this.#Vi(l);const c=(t,s)=>{const e=r[t]/255,i=o[t]/255,n=new Array(s+1);for(let t=0;t<=s;t++)n[t]=e+t/s*(i-e);return n.join(",")};return this.#zi(c(0,5),c(1,5),c(2,5),l),n.url=this.#ji(a),n.url}addSelectionHCMFilter(t,s){return this.addHighlightHCMFilter("selection",t,s,"HighlightText","Highlight")}addSelectionFilter(){return this.addHighlightHCMFilter("selection_default","black","white","HighlightText","Highlight")}createSelectionStyle(t=null){const s=t?this.addSelectionHCMFilter(t.foreground,t.background):this.addSelectionFilter();return"none"!==s&&R.platform.isFirefox?{"backdrop-filter":s,"background-color":"transparent"}:null}addAlphaFilter(t){let s=this.#E.get(t);if(s)return s;const[e]=this.#Ui([t]),i=`alpha_${e}`;if(s=this.#E.get(i),s)return this.#E.set(t,s),s;const n=`g_${this.#Ri}_alpha_map_${this.#T++}`,r=this.#ji(n);this.#E.set(t,r),this.#E.set(i,r);const o=this.#Gi(n);return this.#Xi(e,o),r}addLuminosityFilter(t){let s,e,i=this.#E.get(t||"luminosity");if(i)return i;if(t?([s]=this.#Ui([t]),e=`luminosity_${s}`):e="luminosity",i=this.#E.get(e),i)return this.#E.set(t,i),i;const n=`g_${this.#Ri}_luminosity_map_${this.#T++}`,r=this.#ji(n);this.#E.set(t,r),this.#E.set(e,r);const o=this.#Gi(n);return this.#Yi(o),t&&this.#Xi(s,o),r}addKnockoutFilter(t=0){const s=t>0?Math.min(1/t,1e6):1e6,e=`knockout_${s}`,i=this.#E.get(e);if(i)return i;const r=`g_${this.#Ri}_knockout_filter_${this.#T++}`,o=this.#ji(r);this.#E.set(e,o);const h=this.#Gi(r),a=this.#Oi.createElementNS(n,"feComponentTransfer");h.append(a);const l=this.#Oi.createElementNS(n,"feFuncA");return l.setAttribute("type","linear"),l.setAttribute("slope",`${s}`),l.setAttribute("intercept","0"),a.append(l),o}addHighlightHCMFilter(t,s,e,i,n){const r=`${s}-${e}-${i}-${n}`;let o=this.#$i.get(t);if(o?.key===r)return o.url;if(o?(o.filter?.remove(),o.key=r,o.url="none",o.filter=null):(o={key:r,url:"none",filter:null},this.#$i.set(t,o)),!s||!e)return o.url;const[h,a]=[s,e].map(this.#Hi.bind(this));let l=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),c=Math.round(.2126*a[0]+.7152*a[1]+.0722*a[2]),[u,d]=[i,n].map(this.#Ki.bind(this));c<l&&([l,c,u,d]=[c,l,d,u]),this.#Wi();const f=(t,s,e)=>{const i=new Array(256),n=(c-l)/e,r=t/255,o=(s-t)/(255*e);let h=0;for(let t=0;t<=e;t++){const s=Math.round(l+t*n),e=r+t*o;for(let t=h;t<=s;t++)i[t]=e;h=s+1}for(let t=h;t<256;t++)i[t]=i[h-1];return i.join(",")},p=`g_${this.#Ri}_hcm_${t}_filter`,g=o.filter=this.#Gi(p);return this.#Vi(g),this.#zi(f(u[0],d[0],5),f(u[1],d[1],5),f(u[2],d[2],5),g),o.url=this.#ji(p),o.url}destroy(t=!1){t&&this.#Bi?.size||(this.#_i?.parentNode.parentNode.remove(),this.#_i=null,this.#Fi?.clear(),this.#Fi=null,this.#Bi?.clear(),this.#Bi=null,this.#T=0)}#Yi(t){const s=this.#Oi.createElementNS(n,"feColorMatrix");s.setAttribute("type","matrix"),s.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(s)}#Vi(t){const s=this.#Oi.createElementNS(n,"feColorMatrix");s.setAttribute("type","matrix"),s.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(s)}#Gi(t){const s=this.#Oi.createElementNS(n,"filter");return s.setAttribute("color-interpolation-filters","sRGB"),s.setAttribute("id",t),this.#Li.append(s),s}#qi(t,s,e){const i=this.#Oi.createElementNS(n,s);i.setAttribute("type","discrete"),i.setAttribute("tableValues",e),t.append(i)}#zi(t,s,e,i){const r=this.#Oi.createElementNS(n,"feComponentTransfer");i.append(r),this.#qi(r,"feFuncR",t),this.#qi(r,"feFuncG",s),this.#qi(r,"feFuncB",e)}#Xi(t,s){const e=this.#Oi.createElementNS(n,"feComponentTransfer");s.append(e),this.#qi(e,"feFuncA",t)}#Hi(t){return this.#Li.style.color="CanvasText",this.#Li.style.backgroundColor=t,ct(getComputedStyle(this.#Li).getPropertyValue("background-color"))}#Qi(t){return this.#Li.style.color="CanvasText",this.#Li.style.backgroundColor=t,lt(getComputedStyle(this.#Li).getPropertyValue("background-color"))}#Wi(){this.#Li.style.color="",this.#Li.style.backgroundColor=""}#Ki(t){const[s,e,i,n]=this.#Qi(t);if(1===n)return[s,e,i];const[r,o,h]=this.#Hi("Canvas");return[Hs(s,r,n),Hs(e,o,n),Hs(i,h,n)]}}function Hs(t,s,e){return Math.round(e*t+(1-e)*s)}t&&y("Please use the `legacy` build in Node.js environments.");class Ws extends Gs{}class Vs extends Us{_createCanvas(t,s){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,s)}}class Xs extends $s{async _fetch(t,s){return async function(t){const s=process.getBuiltinModule("fs/promises"),e=await s.readFile(t);return new Uint8Array(e)}(t)}}function Ys({src:t,srcPos:s=0,dest:e,width:i,height:n,nonBlackColor:r=4294967295,inverseDecode:o=!1}){const h=R.isLittleEndian?4278190080:255,[a,l]=o?[r,h]:[h,r],c=i>>3,u=7&i,d=a^l,f=t.length;e=new Uint32Array(e.buffer);let p=0;for(let i=0;i<n;++i){for(const i=s+c;s<i;++s,p+=8){const i=t[s];e[p]=a^-(i>>7&1)&d,e[p+1]=a^-(i>>6&1)&d,e[p+2]=a^-(i>>5&1)&d,e[p+3]=a^-(i>>4&1)&d,e[p+4]=a^-(i>>3&1)&d,e[p+5]=a^-(i>>2&1)&d,e[p+6]=a^-(i>>1&1)&d,e[p+7]=a^-(1&i)&d}if(0===u)continue;const i=s<f?t[s++]:255;for(let t=0;t<u;++t,++p)e[p]=a^-(i>>7-t&1)&d}return{srcPos:s,destPos:p}}function Ks({src:t,srcPos:s=0,dest:e,destPos:i=0,width:n,height:r}){let o=0;const h=n*r*3,a=h>>2,l=new Uint32Array(t.buffer,s,a),c=R.isLittleEndian?4278190080:255;if(R.isLittleEndian){for(;o<a-2;o+=3,i+=4){const t=l[o],s=l[o+1],n=l[o+2];e[i]=t|c,e[i+1]=t>>>24|s<<8|c,e[i+2]=s>>>16|n<<16|c,e[i+3]=n>>>8|c}for(let n=4*o,r=s+h;n<r;n+=3)e[i++]=t[n]|t[n+1]<<8|t[n+2]<<16|c}else{for(;o<a-2;o+=3,i+=4){const t=l[o],s=l[o+1],n=l[o+2];e[i]=t|c,e[i+1]=t<<24|s>>>8|c,e[i+2]=s<<16|n>>>16|c,e[i+3]=n<<8|c}for(let n=4*o,r=s+h;n<r;n+=3)e[i++]=t[n]<<24|t[n+1]<<16|t[n+2]<<8|c}return{srcPos:s+h,destPos:i}}const qs=new class{#Ji=null;#Zi=null;#tn=null;#sn=null;async#en(){if(!globalThis.navigator?.gpu)return!1;try{const t=await navigator.gpu.requestAdapter();return!!t&&(this.#sn=navigator.gpu.getPreferredCanvasFormat(),this.#Zi=await t.requestDevice(),!0)}catch{return!1}}init(){return this.#Ji||=this.#en()}get isReady(){return null!==this.#Zi}loadMeshShader(){if(!this.#Zi||this.#tn)return;const t=this.#Zi.createShaderModule({code:"\nstruct Uniforms {\n offsetX : f32,\n offsetY : f32,\n scaleX : f32,\n scaleY : f32,\n paddedWidth : f32,\n paddedHeight : f32,\n borderSize : f32,\n _pad : f32,\n};\n\n@group(0) @binding(0) var<uniform> u : Uniforms;\n\nstruct VertexInput {\n @location(0) position : vec2<f32>,\n @location(1) color : vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position : vec4<f32>,\n @location(0) color : vec3<f32>,\n};\n\n@vertex\nfn vs_main(in : VertexInput) -> VertexOutput {\n var out : VertexOutput;\n let cx = (in.position.x + u.offsetX) * u.scaleX;\n let cy = (in.position.y + u.offsetY) * u.scaleY;\n out.position = vec4<f32>(\n ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,\n 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,\n 0.0,\n 1.0\n );\n out.color = in.color.rgb;\n return out;\n}\n\n@fragment\nfn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {\n return vec4<f32>(in.color, 1.0);\n}\n"});this.#tn=this.#Zi.createRenderPipeline({layout:"auto",vertex:{module:t,entryPoint:"vs_main",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:t,entryPoint:"fs_main",targets:[{format:this.#sn}]},primitive:{topology:"triangle-list"}})}draw(t,s,e,i,n,r,o,h){this.loadMeshShader();const a=this.#Zi,{offsetX:l,offsetY:c,scaleX:u,scaleY:d}=i,f=a.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&a.queue.writeBuffer(f,0,t);const p=a.createBuffer({size:Math.max(s.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});s.byteLength>0&&a.queue.writeBuffer(p,0,s);const g=a.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});a.queue.writeBuffer(g,0,new Float32Array([l,c,u,d,r,o,h,0]));const m=a.createBindGroup({layout:this.#tn.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:g}}]}),A=new OffscreenCanvas(r,o),w=A.getContext("webgpu");w.configure({device:a,format:this.#sn,alphaMode:n?"opaque":"premultiplied"});const b=n?{r:n[0]/255,g:n[1]/255,b:n[2]/255,a:1}:{r:0,g:0,b:0,a:0},y=a.createCommandEncoder(),v=y.beginRenderPass({colorAttachments:[{view:w.getCurrentTexture().createView(),clearValue:b,loadOp:"clear",storeOp:"store"}]});return e>0&&(v.setPipeline(this.#tn),v.setBindGroup(0,m),v.setVertexBuffer(0,f),v.setVertexBuffer(1,p),v.draw(e)),v.end(),a.queue.submit([y.finish()]),f.destroy(),p.destroy(),g.destroy(),A.transferToImageBitmap()}},Qs="Fill",Js="Stroke",Zs="Shading";function te(t,s){if(!s)return;const e=s[2]-s[0],i=s[3]-s[1],n=new Path2D;n.rect(s[0],s[1],e,i),t.clip(n)}class se{matrix=null;isModifyingCurrentTransform(){return!1}getPattern(){v("Abstract method `getPattern` called.")}}class ee extends se{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]}isOriginBased(){return 0===this._p0[0]&&0===this._p0[1]&&(!this.isRadial()||0===this._p1[0]&&0===this._p1[1])}isRadial(){return"radial"===this._type}areConic(){if(!this.isRadial())return!1;const t=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return t+this._r1>this._r0&&t+this._r0>this._r1}_createGradient(t,s=null){let e,i=this._p0,n=this._p1;if(s&&(i=i.slice(),n=n.slice(),O.applyTransform(i,s),O.applyTransform(n,s)),"axial"===this._type)e=t.createLinearGradient(i[0],i[1],n[0],n[1]);else if("radial"===this._type){let r=this._r0,o=this._r1;if(s){const t=new Float32Array(2);O.singularValueDecompose2dScale(s,t),r*=t[0],o*=t[0]}e=t.createRadialGradient(i[0],i[1],r,n[0],n[1],o)}for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}_createReversedGradient(t,s=null){let e=this._p1,i=this._p0;s&&(e=e.slice(),i=i.slice(),O.applyTransform(e,s),O.applyTransform(i,s));let n=this._r1,r=this._r0;if(s){const t=new Float32Array(2);O.singularValueDecompose2dScale(s,t),n*=t[0],r*=t[0]}const o=t.createRadialGradient(e[0],e[1],n,i[0],i[1],r),h=this._colorStops.map((([t,s])=>[1-t,s])).reverse();for(const[t,s]of h)o.addColorStop(t,s);return o}getPattern(t,s,e,i){let n;if(i===Js||i===Qs){if(this.isOriginBased()){let i=O.transform(e,s.baseTransform);this.matrix&&(i=O.transform(i,this.matrix));const n=.001,r=Math.hypot(i[0],i[1]),o=Math.hypot(i[2],i[3]);if(Math.abs((i[0]*i[2]+i[1]*i[3])/(r*o))<n){if(!this.isRadial())return this._createGradient(t,i);if(Math.abs(r-o)<n)return this._createGradient(t,i)}}const r=s.current.getClippedPathBoundingBox(i,ut(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,a=s.canvasFactory.create(o,h),l=a.context;l.clearRect(0,0,l.canvas.width,l.canvas.height),l.beginPath(),l.rect(0,0,l.canvas.width,l.canvas.height),l.translate(-r[0],-r[1]),e=O.transform(e,[1,0,0,1,r[0],r[1]]),l.transform(...s.baseTransform),this.matrix&&l.transform(...this.matrix),te(l,this._bbox),this.areConic()&&(l.fillStyle=this._createReversedGradient(l),l.fill()),l.fillStyle=this._createGradient(l),l.fill(),n=t.createPattern(a.canvas,"no-repeat"),s.canvasFactory.destroy(a);const c=new DOMMatrix(e);n.setTransform(c)}else this.areConic()&&(t.save(),te(t,this._bbox),t.fillStyle=this._createReversedGradient(t),t.fillRect(-1e10,-1e10,2e10,2e10),t.restore()),te(t,this._bbox),n=this._createGradient(t);return n}}function ie(t,s,e,i,n,r,o,h){const a=s.coords,l=s.colors,c=t.data,u=4*t.width;let d;a[2*e+1]>a[2*i+1]&&(d=e,e=i,i=d,d=r,r=o,o=d),a[2*i+1]>a[2*n+1]&&(d=i,i=n,n=d,d=o,o=h,h=d),a[2*e+1]>a[2*i+1]&&(d=e,e=i,i=d,d=r,r=o,o=d);const f=(a[2*e]+s.offsetX)*s.scaleX,p=(a[2*e+1]+s.offsetY)*s.scaleY,g=(a[2*i]+s.offsetX)*s.scaleX,m=(a[2*i+1]+s.offsetY)*s.scaleY,A=(a[2*n]+s.offsetX)*s.scaleX,w=(a[2*n+1]+s.offsetY)*s.scaleY;if(p>=w)return;const b=l[4*r],y=l[4*r+1],v=l[4*r+2],x=l[4*o],M=l[4*o+1],k=l[4*o+2],C=l[4*h],S=l[4*h+1],T=l[4*h+2],P=Math.round(p),E=Math.round(w);let D,N,I,F,_,R,O,B;for(let t=P;t<=E;t++){if(t<m){const s=t<p?0:(p-t)/(p-m);D=f-(f-g)*s,N=b-(b-x)*s,I=y-(y-M)*s,F=v-(v-k)*s}else{let s;s=t>w?1:m===w?0:(m-t)/(m-w),D=g-(g-A)*s,N=x-(x-C)*s,I=M-(M-S)*s,F=k-(k-T)*s}let s;s=t<p?0:t>w?1:(p-t)/(p-w),_=f-(f-A)*s,R=b-(b-C)*s,O=y-(y-S)*s,B=v-(v-T)*s;const e=Math.round(Math.min(D,_)),i=Math.round(Math.max(D,_));let n=u*t+4*e;for(let t=e;t<=i;t++)s=(D-t)/(D-_),s<0?s=0:s>1&&(s=1),c[n++]=N-(N-R)*s|0,c[n++]=I-(I-O)*s|0,c[n++]=F-(F-B)*s|0,c[n++]=255}}class ne extends se{constructor(t){super(),this._posData=t[2],this._colData=t[3],this._vertexCount=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],qs.loadMeshShader()}_createMeshCanvas(t,s,e){const i=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),r=Math.ceil(this._bounds[2])-i,o=Math.ceil(this._bounds[3])-n,h=Math.min(Math.ceil(Math.abs(r*t[0]*1.1)),3e3)||1,a=Math.min(Math.ceil(Math.abs(o*t[1]*1.1)),3e3)||1,l=r?r/h:1,c=o?o/a:1,u={coords:this._posData,colors:this._colData,offsetX:-i,offsetY:-n,scaleX:1/l,scaleY:1/c},d=h+4,f=a+4,p=e.create(d,f);if(qs.isReady&&this._vertexCount>48)p.context.drawImage(function(t,s,e,i,n,r,o){return qs.draw(t,s,e,i,n,r,o,2)}(this._posData,this._colData,this._vertexCount,u,s,d,f),0,0);else{const t=p.context.createImageData(h,a);if(s){const e=t.data;for(let t=0,i=e.length;t<i;t+=4)e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=255}for(let s=0,e=this._vertexCount;s<e;s+=3)ie(t,u,s,s+1,s+2,s,s+1,s+2);p.context.putImageData(t,2,2)}return{canvas:p.canvas,offsetX:i-2*l,offsetY:n-2*c,scaleX:l,scaleY:c}}isModifyingCurrentTransform(){return!0}getPattern(t,s,e,i){te(t,this._bbox);const n=new Float32Array(2);if(i===Zs)O.singularValueDecompose2dScale(ut(t),n);else if(this.matrix){O.singularValueDecompose2dScale(this.matrix,n);const[t,e]=n;O.singularValueDecompose2dScale(s.baseTransform,n),n[0]*=t,n[1]*=e}else O.singularValueDecompose2dScale(s.baseTransform,n);const r=this._createMeshCanvas(n,i===Zs?null:this._background,s.canvasFactory);i!==Zs&&(t.setTransform(...s.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY);const o=t.createPattern(r.canvas,"no-repeat");return s.canvasFactory.destroy(r),o}}class re extends se{getPattern(){return"hotpink"}}class oe{static MAX_PATTERN_SIZE=3e3;constructor(t,s,e,i){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.needsIsolation=t[9]??!0,this.ctx=s,this.canvasGraphicsFactory=e,this.baseTransform=i,this.patternBaseMatrix=this.matrix?O.transform(i,this.matrix):i}canSkipPatternCanvas([t,s,e,i]){const[n,r,o,h]=this.bbox,a=Math.abs(this.xstep),l=Math.abs(this.ystep);if(t>a+1e-6||s>l+1e-6)return null;const c=Math.floor((e-o)/a)+1,u=Math.ceil((e+t-n)/a)-1,d=Math.floor((i-h)/l)+1,f=Math.ceil((i+s-r)/l)-1;return u<=c&&f<=d?[c,d]:null}updatePatternDims(t,s){const e=O.inverseTransform(this.patternBaseMatrix),i=[t[0],t[1]],n=[t[2],t[3]];O.applyTransform(i,e),O.applyTransform(n,e),s[0]=Math.abs(n[0]-i[0]),s[1]=Math.abs(n[1]-i[1]),s[2]=Math.min(i[0],n[0]),s[3]=Math.min(i[1],n[1])}_renderTileCanvas(t,s,e,i){const[n,r,o,h]=this.bbox,a=t.canvasFactory.create(e.size,i.size),l=a.context,c=this.canvasGraphicsFactory.createCanvasGraphics(l,s);return c.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(c,this.paintType,this.color),l.translate(-e.scale*n,-i.scale*r),c.transform(0,e.scale,0,0,i.scale,0,0),l.save(),c.dependencyTracker?.save(),this.clipBbox(c,n,r,o,h),c.baseTransform=ut(c.ctx),c.executeOperatorList(this.operatorList),c.endDrawing(),c.dependencyTracker?.restore(),l.restore(),a}_getCombinedScales(){const t=new Float32Array(2);O.singularValueDecompose2dScale(this.matrix,t);const[s,e]=t;return O.singularValueDecompose2dScale(this.baseTransform,t),[s*t[0],e*t[1]]}drawPattern(t,s,e=!1,[i,n],r){const[o,h,a,l]=this.bbox,c=t.dependencyTracker;if(c&&(t.dependencyTracker=new as(c,r)),t.save(),e?t.ctx.clip(s,"evenodd"):t.ctx.clip(s),t.ctx.setTransform(...this.patternBaseMatrix),t.ctx.translate(i*this.xstep,n*this.ystep),this.needsIsolation||1!==t.ctx.globalAlpha||"source-over"!==t.ctx.globalCompositeOperation||t.inSMaskMode){const s=a-o,e=l-h,[i,n]=this._getCombinedScales(),c=this.getSizeAndScale(s,this.ctx.canvas.width,i),u=this.getSizeAndScale(e,this.ctx.canvas.height,n),d=this._renderTileCanvas(t,r,c,u);t.ctx.drawImage(d.canvas,o,h,s,e),t.canvasFactory.destroy(d)}else this.setFillAndStrokeStyleToContext(t,this.paintType,this.color),this.clipBbox(t,o,h,a,l),t.baseTransformStack.push(t.baseTransform),t.baseTransform=ut(t.ctx),t.executeOperatorList(this.operatorList),t.baseTransform=t.baseTransformStack.pop();t.restore(),c&&(t.dependencyTracker=c)}createPatternCanvas(t,s){const[e,i,n,r]=this.bbox,o=n-e,h=r-i;let{xstep:a,ystep:l}=this;a=Math.abs(a),l=Math.abs(l),b("TilingType: "+this.tilingType);const[c,u]=this._getCombinedScales();let d=o,f=h,p=!1,g=!1;Math.ceil(a*c)>=Math.ceil(o*c)?d=a:p=!0,Math.ceil(l*u)>=Math.ceil(h*u)?f=l:g=!0;const m=this.getSizeAndScale(d,this.ctx.canvas.width,c),A=this.getSizeAndScale(f,this.ctx.canvas.height,u),w=this._renderTileCanvas(t,s,m,A);if(p||g){const s=w.canvas;p&&(d=a),g&&(f=l);const n=this.getSizeAndScale(d,this.ctx.canvas.width,c),r=this.getSizeAndScale(f,this.ctx.canvas.height,u),m=n.size,A=r.size,b=t.canvasFactory.create(m,A),y=b.context,v=p?Math.floor(o/a):0,x=g?Math.floor(h/l):0;for(let t=0;t<=v;t++)for(let e=0;e<=x;e++)y.drawImage(s,m*t,A*e,m,A,0,0,m,A);return t.canvasFactory.destroy(w),{canvas:b.canvas,canvasEntry:b,scaleX:n.scale,scaleY:r.scale,offsetX:e,offsetY:i}}return{canvas:w.canvas,canvasEntry:w,scaleX:m.scale,scaleY:A.scale,offsetX:e,offsetY:i}}getSizeAndScale(t,s,e){const i=Math.max(oe.MAX_PATTERN_SIZE,s);let n=Math.ceil(t*e);return n>=i?n=i:e=n/t,{scale:e,size:n}}clipBbox(t,s,e,i,n){const r=i-s,o=n-e,h=new Path2D;h.rect(s,e,r,o),O.axialAlignedBoundingBox([s,e,i,n],ut(t.ctx),t.current.minMax),t.ctx.clip(h),t.current.updateClipFromPath()}setFillAndStrokeStyleToContext(t,s,e){const i=t.ctx,n=t.current;switch(n.patternFill=n.patternStroke=!1,s){case 1:const{fillStyle:t,strokeStyle:r}=this.ctx;i.fillStyle=n.fillColor=t,i.strokeStyle=n.strokeColor=r;break;case 2:i.fillStyle=i.strokeStyle=e,n.fillColor=n.strokeColor=e;break;default:throw new I(`Unsupported paint type: ${s}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,s,e,i,n){const r=i!==Zs?O.transform(e,this.patternBaseMatrix):e,o=this.createPatternCanvas(s,n);let h=new DOMMatrix(r);h=h.translate(o.offsetX,o.offsetY),h=h.scale(1/o.scaleX,1/o.scaleY);const a=t.createPattern(o.canvas,"repeat");return s.canvasFactory.destroy(o.canvasEntry),a.setTransform(h),a}}const he=16,ae=new Float32Array(2);function le(t,s){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");const e=new Map;for(const i of["save","restore","rotate","scale","translate","transform","setTransform","resetTransform","clip","moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath","beginPath"]){const n=t[i];"function"==typeof n&&"function"==typeof s[i]&&(e.set(i,n),t[i]=function(...t){return s[i](...t),n.apply(this,t)})}t._removeMirroring=()=>{for(const[s,i]of e)t[s]=i;delete t._removeMirroring}}function ce(t,s,e,i,n,r,o,h,a,l){const[c,u,d,f,p,g]=ut(t);if(0===u&&0===d){const m=Math.round(o*c+p),A=Math.round(h*f+g),w=Math.abs(Math.round((o+a)*c+p)-m)||1,b=Math.abs(Math.round((h+l)*f+g)-A)||1;return t.setTransform(Math.sign(c),0,0,Math.sign(f),m,A),t.drawImage(s,e,i,n,r,0,0,w,b),t.setTransform(c,u,d,f,p,g),[w,b]}if(0===c&&0===f){const m=Math.round(h*d+p),A=Math.round(o*u+g),w=Math.abs(Math.round((h+l)*d+p)-m)||1,b=Math.abs(Math.round((o+a)*u+g)-A)||1;return t.setTransform(0,Math.sign(u),Math.sign(d),0,m,A),t.drawImage(s,e,i,n,r,0,0,b,w),t.setTransform(c,u,d,f,p,g),[b,w]}return t.drawImage(s,e,i,n,r,o,h,a,l),[Math.hypot(c,u)*a,Math.hypot(d,f)*l]}class ue{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=i;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=0;textRise=0;fillColor="#000000";strokeColor="#000000";tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";minMax=e.slice();constructor(t,s){this.clipBox=new Float32Array([0,0,t,s])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t.tilingPatternDims=this.tilingPatternDims?.slice(),t}getPathBoundingBox(t=Qs,s=null){const e=this.minMax.slice();if(t===Js){s||v("Stroke bounding box must include transform."),O.singularValueDecompose2dScale(s,ae);const t=ae[0]*this.lineWidth/2,i=ae[1]*this.lineWidth/2;e[0]-=t,e[1]-=i,e[2]+=t,e[3]+=i}return e}updateClipFromPath(){const t=O.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(e,0)}getClippedPathBoundingBox(t=Qs,s=null){return O.intersect(this.clipBox,this.getPathBoundingBox(t,s))}}function de(t,s){const{width:e,height:i,kind:n}=s,r=i%he,o=(i-r)/he,h=0===r?o:o+1,a=t.createImageData(e,he);let l=0;const c=s.data,d=a.data;let f;if(n===u.GRAYSCALE_1BPP)for(f=0;f<h;f++)({srcPos:l}=Ys({src:c,srcPos:l,dest:d,width:e,height:f<o?he:r})),t.putImageData(a,0,f*he);else if(n===u.RGBA_32BPP){let s=0,i=e*he*4;for(f=0;f<o;f++)d.set(c.subarray(l,l+i)),l+=i,t.putImageData(a,0,s),s+=he;f<h&&(i=e*r*4,d.set(c.subarray(l,l+i)),t.putImageData(a,0,s))}else{if(n!==u.RGB_24BPP)throw new Error(`bad image kind: ${n}`);for(f=0;f<h;f++)({srcPos:l}=Ks({src:c,srcPos:l,dest:new Uint32Array(d.buffer),width:e,height:f<o?he:r})),t.putImageData(a,0,f*he)}}function fe(t,s){if(s.bitmap)return void t.drawImage(s.bitmap,0,0);const{width:e,height:i}=s,n=i%he,r=(i-n)/he,o=0===n?r:r+1,h=t.createImageData(e,he);let a=0;const l=s.data,c=h.data;for(let s=0;s<o;s++)({srcPos:a}=Ys({src:l,srcPos:a,dest:c,width:e,height:s<r?he:n,nonBlackColor:0})),t.putImageData(h,0,s*he)}function pe(t,s){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const i of e)void 0!==t[i]&&(s[i]=t[i]);void 0!==t.setLineDash&&(s.setLineDash(t.getLineDash()),s.lineDashOffset=t.lineDashOffset)}function ge(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:s}=t;"none"!==s&&""!==s&&(t.filter="none")}function me(t,s){if(s)return!0;O.singularValueDecompose2dScale(t,ae);const e=Math.fround(pt.pixelRatio*Q.PDF_TO_CSS_UNITS);return ae[0]<=e&&ae[1]<=e}const Ae=["butt","round","square"],we=["miter","round","bevel"],be={},ye={};class ve{static#in=null;#nn=0;#rn=0;#on=null;#hn=null;#an=null;#ln=null;#cn=1;#un;#dn=null;#fn=[];constructor(t,s,e,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,a,l,c){this.ctx=t,this.current=new ue(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.commonObjs=s,this.objs=e,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.tempSMask=null,this.smaskGroupCanvases=[],this.smaskPreparedEntry=null,this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=o||[],this.optionalContentConfig=r,this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=a,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=l??null,this.imagesTracker=c??null}getObject(t,s,e=null){return"string"==typeof s?(this.dependencyTracker?.recordNamedDependency(t,s),s.startsWith("g_")?this.commonObjs.get(s):this.objs.get(s)):e}beginDrawing({transform:t,viewport:s,transparency:e=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,e){const t=this.transparentCanvasEntry=this.canvasFactory.create(n,r);this.compositeCtx=this.ctx,({canvas:this.transparentCanvas,context:this.ctx}=t),this.ctx.save(),this.ctx.transform(...ut(this.compositeCtx))}this.ctx.save(),ge(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[3]),this.ctx.transform(...s.transform),this.viewportScale=s.scale,this.baseTransform=ut(this.ctx)}executeOperatorList(t,s,e,i,n){const r=t.argsArray,o=t.fnArray;let h=s||0;const a=r.length;if(a===h)return h;const l=a-h>10&&"function"==typeof e,c=l?Date.now()+15:0;let u=0;const d=this.commonObjs,f=this.objs;let g,m;for(;;){if(void 0!==i){if(h===i.nextBreakPoint)return i.breakIt(h,e),h;if(i.shouldSkip(h)){if(++h===a)return h;continue}}if(!n||n(h))if(g=o[h],m=r[h]??null,g!==p.dependency)null===m?this[g](h):this[g](h,...m);else for(const t of m){this.dependencyTracker?.recordNamedData(t,h);const s=t.startsWith("g_")?d:f;if(!s.has(t))return s.get(t,e),h}if(h++,h===a)return h;if(l&&++u>10){if(Date.now()>c)return e(),h;u=0}}}#pn(){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.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)}endDrawing(){this.#pn();for(const t of this.smaskGroupCanvases)this.canvasFactory.destroy(t);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(const t of this.#fn)this.#gn(t);this.#fn.length=0,this.#on=null,this.#hn=null,this.#an=null,this.#ln=null,this.#cn=1,this.#dn=null,this.#rn=0,this.#nn=0,this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const s of t.values())"undefined"!=typeof HTMLCanvasElement&&s instanceof HTMLCanvasElement&&(s.width=s.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#mn()}#mn(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const s=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=s}}}_scaleImage(t,s){const e=t.width??t.displayWidth,i=t.height??t.displayHeight,n=[];let r=Math.max(Math.hypot(s[0],s[1]),1),o=Math.max(Math.hypot(s[2],s[3]),1),h=e,a=i;for(;r>2&&h>1||o>2&&a>1;){let t=h,s=a;r>2&&h>1&&(t=Math.ceil(h/2),r/=h/t),o>2&&a>1&&(s=Math.ceil(a/2),o/=a/s),n.push({newWidth:t,newHeight:s}),h=t,a=s}if(0===n.length)return{img:t,paintWidth:e,paintHeight:i,tmpCanvas:null};if(1===n.length){const{newWidth:s,newHeight:r}=n[0],o=this.canvasFactory.create(s,r);return o.context.drawImage(t,0,0,e,i,0,0,s,r),{img:o.canvas,paintWidth:s,paintHeight:r,tmpCanvas:o}}let l=this.canvasFactory.create(1,1),c=this.canvasFactory.create(1,1),u=e,d=i,f=t;for(const{newWidth:t,newHeight:s}of n)this.canvasFactory.reset(c,t,s),c.context.drawImage(f,0,0,u,d,0,0,t,s),[l,c]=[c,l],f=l.canvas,u=t,d=s;return this.canvasFactory.destroy(c),{img:l.canvas,paintWidth:u,paintHeight:d,tmpCanvas:l}}_createMaskCanvas(t,s){const i=this.ctx,{width:n,height:r}=s,o=this.current.fillColor,h=this.current.patternFill,a=ut(i);let l,c,u,d;if((s.bitmap||s.data)&&s.count>1){const e=s.bitmap||s.data.buffer;c=JSON.stringify(h?a:[a.slice(0,4),o]),l=this._cachedBitmapsMap.getOrInsertComputed(e,G);const i=l.get(c);if(i&&!h){const s=Math.round(Math.min(a[0],a[2])+a[4]),e=Math.round(Math.min(a[1],a[3])+a[5]);return this.dependencyTracker?.recordDependencies(t,gs),{canvas:i,offsetX:s,offsetY:e}}u=i}u||(d=this.canvasFactory.create(n,r),fe(d.context,s));let f=O.transform(a,[1/n,0,0,-1/r,0,0]);f=O.transform(f,[1,0,0,1,0,-r]);const p=e.slice();O.axialAlignedBoundingBox([0,0,n,r],f,p);const[g,m,A,w]=p,b=Math.round(A-g)||1,y=Math.round(w-m)||1,v=this.canvasFactory.create(b,y),x=v.context,M=g,k=m;x.translate(-M,-k),x.transform(...f);let C=null;if(!u){const t=this._scaleImage(d.canvas,dt(x));u=t.img,C=t.tmpCanvas,u!==d.canvas&&(this.canvasFactory.destroy(d),d=null),l&&h&&(l.set(c,u),C=null,d=null)}x.imageSmoothingEnabled=me(ut(x),s.interpolate),ce(x,u,0,0,u.width,u.height,0,0,n,r),C&&this.canvasFactory.destroy(C),d&&this.canvasFactory.destroy(d),x.globalCompositeOperation="source-in";const S=O.transform(dt(x),[1,0,0,1,-M,-k]);return x.fillStyle=h?o.getPattern(i,this,S,Qs,t):o,x.fillRect(0,0,n,r),l&&!h&&l.set(c,v.canvas),this.dependencyTracker?.recordDependencies(t,gs),{canvas:v.canvas,canvasEntry:l&&!h?null:v,offsetX:Math.round(M),offsetY:Math.round(k)}}setLineWidth(t,s){this.dependencyTracker?.recordSimpleData("lineWidth",t),s!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=s,this.ctx.lineWidth=s}setLineCap(t,s){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=Ae[s]}setLineJoin(t,s){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=we[s]}setMiterLimit(t,s){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=s}setDash(t,s,e){this.dependencyTracker?.recordSimpleData("dash",t);const i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(s),i.lineDashOffset=e)}setRenderingIntent(t,s){}setFlatness(t,s){}setGState(t,s){for(const[e,i]of s)switch(e){case"LW":this.setLineWidth(t,i);break;case"LC":this.setLineCap(t,i);break;case"LJ":this.setLineJoin(t,i);break;case"ML":this.setMiterLimit(t,i);break;case"D":this.setDash(t,i[0],i[1]);break;case"RI":this.setRenderingIntent(t,i);break;case"FL":this.setFlatness(t,i);break;case"Font":this.setFont(t,i[0],i[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=i;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=i;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=i;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=i?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(t);break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&(this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(t){t!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(t))}checkSMaskState(t){const s=this.inSMaskMode;this.current.activeSMask&&!s?this.beginSMaskMode(t):!this.current.activeSMask&&s?this.endSMaskMode():this.current.activeSMask&&s&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(t){const{canvas:s,subtype:e,backdrop:i,transferMap:n}=t,r="Luminosity"===e||"Alpha"===e&&n;if(!(r||"Luminosity"===e&&i))return void(this.smaskPreparedFor=t);let o;if("Luminosity"===e&&i){const[t,s,e]=lt(i),r=Math.round(.3*t+.59*s+.11*e);o=n?.[r]??r}else o=n?.[0]??0;const{width:h,height:a}=this.ctx.canvas,l=h*a<s.width*s.height*4,c=r?{url:"Alpha"===e?this.filterFactory.addAlphaFilter(n):this.filterFactory.addLuminosityFilter(n),subtype:e,transferMap:n}:null,u="Luminosity"===e?i:null;let d,f,p;l?(d=this._bakeSMaskCanvas(s,t.offsetX,t.offsetY,h,a,u,c),f=0,p=0):(d=this._bakeSMaskCanvas(s,0,0,s.width,s.height,u,c),f=t.offsetX,p=t.offsetY),this.smaskPreparedEntry=d,this.smaskPreparedFor=t,this.smaskPreparedOffsetX=f,this.smaskPreparedOffsetY=p,this.smaskPreparedOOBAlpha=l||0===o?null:o}_bakeSMaskCanvas(t,s,e,i,n,r,o){r||o||v("_bakeSMaskCanvas with neither backdrop nor filter");const h=this.canvasFactory.create(i,n),a=h.context;if(a.drawImage(t,s,e),r&&(a.globalCompositeOperation="destination-atop",a.fillStyle=r,a.fillRect(0,0,i,n)),!o)return h;const l=this.canvasFactory.create(i,n),c=l.context;c.filter=o.url;const u=R.isCanvasFilterSupported&&"none"!==c.filter&&""!==c.filter;if(c.drawImage(h.canvas,0,0),R.isCanvasFilterSupported&&(c.filter="none"),!u){const t=c.getImageData(0,0,i,n),{data:s}=t,{transferMap:e}=o;if("Luminosity"===o.subtype)for(let t=0,i=s.length;t<i;t+=4){const i=.3*s[t]+.59*s[t+1]+.11*s[t+2]+.5|0;s[t]=s[t+1]=s[t+2]=0,s[t+3]=e?.[i]??i}else for(let t=3,i=s.length;t<i;t+=4)s[t]=e[s[t]];c.putImageData(t,0,0)}return this.canvasFactory.destroy(h),l}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:s,height:e}=this.ctx.canvas,i=this.canvasFactory.create(s,e);this.smaskScratchCanvas=i,this.suspendedCtx=this.ctx;const n=this.ctx=i.context;n.setTransform(this.suspendedCtx.getTransform()),pe(this.suspendedCtx,n),le(n,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),pe(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}#An(t,s=null,e=1){const{width:i,height:n}=t,r=s??this.canvasFactory.create(i,n),o=r.context,h=(e=Math.round(255*e)/255)<1;h&&void 0===this.#un&&(this.#un=R.isCanvasFilterSupported?new Map:"none");let a="none";if(h&&this.#un instanceof Map&&(a=this.#un.getOrInsertComputed(e,(()=>this.filterFactory.addKnockoutFilter(e)))),!h||"none"!==a)return s&&(o.save(),o.setTransform(1,0,0,1,0,0),o.clearRect(0,0,i,n),o.restore()),o.filter=a,o.drawImage(t,0,0),o.filter="none",r;const l=t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,i,n),c=o.createImageData(i,n),u=l.data,d=c.data,f=e>0?1/e:1e6;for(let t=3,s=u.length;t<s;t+=4)d[t]=Math.min(Math.round(u[t]*f),255);return o.putImageData(c,0,0),r}#wn(t,s,e,i){let n=t?.[s]??null;if(!n||n.canvas.width===e&&n.canvas.height===i||(this.canvasFactory.destroy(n),n=null),!n)return n=this.canvasFactory.create(e,i),t&&(t[s]=n),n;const r=n.context;return r.save(),r.setTransform(1,0,0,1,0,0),r.clearRect(0,0,e,i),r.restore(),n}#bn(t,s,e={}){const{backdropCanvas:i=null,destTransform:n=[1,0,0,1,0,0],backdropOffset:r=[0,0],reuseMaskEntry:o=null,poolMeta:h=null,sourceAlpha:a=1,sourceFilter:l="none",knockoutAlpha:c=1}=e,{width:u,height:d}=s,f=this.#An(s,o,c),p=t.globalCompositeOperation;if(t.save(),t.setTransform(...n),t.globalAlpha=1,R.isCanvasFilterSupported&&(t.filter="none"),t.globalCompositeOperation="destination-out",t.drawImage(f.canvas,0,0),i){const[s,e]=r,n=this.#wn(h,"knockoutBackdropEntry",u,d),o=n.context;o.drawImage(i,s,e,u,d,0,0,u,d),o.globalCompositeOperation="destination-in",o.drawImage(f.canvas,0,0),o.globalCompositeOperation="source-over",t.globalCompositeOperation="destination-over",t.drawImage(n.canvas,0,0),h||this.canvasFactory.destroy(n)}t.globalCompositeOperation=p,t.globalAlpha=a,R.isCanvasFilterSupported&&(t.filter=l??"none"),t.drawImage(s,0,0),t.restore(),o||this.canvasFactory.destroy(f)}#yn(t=1){if(0===this.#nn||this.#rn>0||!this.contentVisible)return!1;this.#rn++,this.#cn=t;const s=this.#fn.at(-1),{canvas:e}=this.ctx,i=this.#wn(s,"knockoutTempEntry",e.width,e.height);this.#on=i;const n=i.context;return n.save(),n.setTransform(this.ctx.getTransform()),pe(this.ctx,n),this.#ln=n.globalCompositeOperation,n.globalCompositeOperation="source-over",le(n,this.ctx),this.#dn=s,this.#hn=this.ctx,this.#an=this.suspendedCtx,this.ctx=n,this.inSMaskMode&&(this.suspendedCtx=n),!0}#vn(t){if(!t)return;const s=this.#on,e=this.#hn,i=this.#an,n=s.context;this.#on=null,this.#hn=null,this.#an=null,this.inSMaskMode&&this.suspendedCtx===n&&this.ctx!==n&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=i),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=this.#ln,this.#ln=null,pe(this.ctx,e),this.ctx=e;const r=this.#dn;this.#dn=null;const o=this.#cn;this.#cn=1;try{this.#bn(i??e,s.canvas,{backdropCanvas:r?.backdropCtx?.canvas??null,backdropOffset:r?.backdropCtx?[r.offsetX,r.offsetY]:[0,0],reuseMaskEntry:r?.knockoutMaskEntry??null,poolMeta:r,knockoutAlpha:o})}finally{n.restore(),this.#rn--,r||this.canvasFactory.destroy(s)}}compose(t){if(!this.current.activeSMask)return;t=t?[Math.floor(t[0]),Math.floor(t[1]),Math.ceil(t[2]),Math.ceil(t[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const s=this.suspendedCtx,e=this.#rn>0&&s===this.ctx;this.composeSMask(e?null:s,this.current.activeSMask,this.ctx,t),e||(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,s,e,i){const n=i[0],r=i[1],o=i[2]-n,h=i[3]-r;if(0===o||0===h)return;const a=this.smaskPreparedEntry;if(a){let t=n,i=r,l=o,c=h;const u=this.smaskPreparedOOBAlpha,d=null!==u;if(d&&(t=Math.max(n,s.offsetX),i=Math.max(r,s.offsetY),l=Math.min(n+o,s.offsetX+s.canvas.width)-t,c=Math.min(r+h,s.offsetY+s.canvas.height)-i),l>0&&c>0){const s=t-this.smaskPreparedOffsetX,n=i-this.smaskPreparedOffsetY;e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);const r=new Path2D;r.rect(t,i,l,c),e.clip(r),e.globalCompositeOperation="destination-in",e.drawImage(a.canvas,s,n,l,c,t,i,l,c),e.restore()}d&&u<255&&this._applySMaskOOBAlpha(e,n,r,o,h,t,i,t+l,i+c,u)}else this.genericComposeSMask(s,e,o,h,n,r);t&&(t.save(),t.globalAlpha=1,t.globalCompositeOperation=s.blendMode||"source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(e.canvas,n,r,o,h,n,r,o,h),t.restore())}_applySMaskOOBAlpha(t,s,e,i,n,r,o,h,a,l){const c=r<h&&o<a;if(c&&r===s&&o===e&&h===s+i&&a===e+n)return;const u=new Path2D;u.rect(s,e,i,n),c&&u.rect(r,o,h-r,a-o),t.save(),t.globalAlpha=l/255,t.setTransform(1,0,0,1,0,0),t.clip(u,"evenodd"),t.globalCompositeOperation="destination-in",t.fillStyle="#000000",t.fillRect(s,e,i,n),t.restore()}genericComposeSMask(t,s,e,i,n,r){const{context:o,offsetX:h,offsetY:a}=t;s.save(),s.globalAlpha=1,s.setTransform(1,0,0,1,0,0);const l=new Path2D;l.rect(n,r,e,i),s.clip(l),s.globalCompositeOperation="destination-in",s.drawImage(o.canvas,n-h,r-a,e,i,n,r,e,i),s.restore()}save(t){this.inSMaskMode&&pe(this.ctx,this.suspendedCtx),this.ctx.save();const s=this.current;this.stateStack.push(s),this.current=s.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&&(pe(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform())),this.checkSMaskState(t),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,s,e,i,n,r,o){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(s,e,i,n,r,o),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,s,e,i){let[n]=e;if(!i)return n||=e[0]=new Path2D,s!==p.stroke&&s!==p.closeStroke&&(this.current.tilingPatternDims=null),void this[s](t,n);if(null!==this.dependencyTracker){const e=s===p.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,i[0]-e,i[2]+e,i[1]-e,i[3]+e).recordDependencies(t,["transform"])}n instanceof Path2D||(n=e[0]=St(n)),O.axialAlignedBoundingBox(i,ut(this.ctx),this.current.minMax);const r=this.current.tilingPatternDims;if(r&&s!==p.stroke&&s!==p.closeStroke&&this.current.fillColor instanceof oe){const t=O.intersect(this.current.clipBox,this.current.minMax);t?this.current.fillColor.updatePatternDims(t,r):this.current.tilingPatternDims=null}this[s](t,n),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,s,e=!0){const i=e&&this.#yn(this.current.strokeAlpha),n=this.ctx,r=this.current.strokeColor;if(n.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof r&&r?.getPattern){const e=r.isModifyingCurrentTransform()?n.getTransform():null;if(n.save(),n.strokeStyle=r.getPattern(n,this,dt(n),Js,t),e){const t=new Path2D;t.addPath(s,n.getTransform().invertSelf().multiplySelf(e)),s=t}this.rescaleAndStroke(s,!1),n.restore()}else this.rescaleAndStroke(s,!0);this.dependencyTracker?.recordDependencies(t,ls),e&&this.consumePath(t,s,this.current.getClippedPathBoundingBox(Js,ut(this.ctx))),n.globalAlpha=this.current.fillAlpha,this.#vn(i)}closeStroke(t,s){this.stroke(t,s)}fill(t,s,e=!0){const i=e&&this.#yn(this.current.fillAlpha),n=this.ctx,r=this.current.fillColor,o=this.current.patternFill;let h=!1;const a=this.current.getClippedPathBoundingBox();if(this.dependencyTracker?.recordDependencies(t,cs),o){const o=this.current.tilingPatternDims,l=o&&r.canSkipPatternCanvas(o);if(l)return r.drawPattern(this,s,this.pendingEOFill,l,t),this.pendingEOFill=!1,e&&this.consumePath(t,s,a),this.current.tilingPatternDims=null,void this.#vn(i);const c=r.isModifyingCurrentTransform()?n.getTransform():null;if(this.dependencyTracker?.save(t),n.save(),n.fillStyle=r.getPattern(n,this,dt(n),Qs,t),c){const t=new Path2D;t.addPath(s,n.getTransform().invertSelf().multiplySelf(c)),s=t}h=!0}this.contentVisible&&null!==a&&(this.pendingEOFill?(n.fill(s,"evenodd"),this.pendingEOFill=!1):n.fill(s)),h&&(n.restore(),this.dependencyTracker?.restore(t)),e&&this.consumePath(t,s,a),this.#vn(i)}eoFill(t,s){this.pendingEOFill=!0,this.fill(t,s)}fillStroke(t,s){const e=this.#yn(Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(t,s,!1),this.stroke(t,s,!1),this.consumePath(t,s),this.#vn(e)}eoFillStroke(t,s){this.pendingEOFill=!0,this.fillStroke(t,s)}closeFillStroke(t,s){this.fillStroke(t,s)}closeEOFillStroke(t,s){this.pendingEOFill=!0,this.fillStroke(t,s)}endPath(t,s){this.consumePath(t,s)}rawFillPath(t,s){const e=this.#yn(this.current.fillAlpha);this.ctx.fill(s),this.dependencyTracker?.recordDependencies(t,ds).recordOperation(t),this.#vn(e)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=be}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=ye}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 s=this.pendingTextPaths,e=this.ctx;if(this.dependencyTracker){const{dependencyTracker:e}=this;void 0!==s&&e.recordFutureForcedDependency("textClip",e.getOpenMarker()).recordFutureForcedDependency("textClip",t),e.recordCloseMarker(t)}if(void 0!==s){const t=new Path2D,i=e.getTransform().invertSelf();for(const{transform:e,x:n,y:r,fontSize:o,path:h}of s)h&&t.addPath(h,new DOMMatrix(e).preMultiplySelf(i).translate(n,r).scale(o,-o));e.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,s){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=s}setWordSpacing(t,s){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=s}setHScale(t,s){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=s/100}setLeading(t,s){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-s}setFont(t,s,e){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",s,t);const n=this.commonObjs.get(s),r=this.current;if(!n)throw new Error(`Can't find font for ${s}`);if(r.fontMatrix=n.fontMatrix||i,0!==r.fontMatrix[0]&&0!==r.fontMatrix[3]||y("Invalid font matrix for font "+s),e<0?(e=-e,r.fontDirection=-1):r.fontDirection=1,this.current.font=n,this.current.fontSize=e,n.isType3Font)return;const o=n.loadedName||"sans-serif",h=n.systemFontInfo?.css||`"${o}", ${n.fallbackName}`;let a="normal";n.black?a="900":n.bold&&(a="bold");const l=n.italic?"italic":"normal",c=W(e,16,100);this.current.fontSizeScale=e/c,this.ctx.font=`${l} ${a} ${c}px ${h}`}setTextRenderingMode(t,s){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=s}setTextRise(t,s){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=s}moveText(t,s,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=s,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,s,e){this.setLeading(t,-e),this.moveText(t,s,e)}setTextMatrix(t,s){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);const{current:e}=this;e.textMatrix=s,e.textMatrixScale=Math.hypot(s[0],s[1]),e.x=e.lineX=0,e.y=e.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#xn(t,s,e){const i=new Path2D;return i.addPath(t,new DOMMatrix(e).invertSelf().multiplySelf(s)),i}paintChar(t,s,e,i,n,r){const o=this.ctx,h=this.current,a=h.font,l=h.textRenderingMode,c=h.fontSize/h.fontSizeScale,u=3&l,d=!!(4&l),f=h.patternFill&&!a.missingFile,p=h.patternStroke&&!a.missingFile;let g;if((a.disableFontFace||d||f||p)&&!a.missingFile&&(g=a.getPathGenerator(this.commonObjs,s)),g&&(a.disableFontFace||f||p)){let s;if(o.save(),o.translate(e,i),o.scale(c,-c),this.dependencyTracker?.recordCharacterBBox(t,o,a),0===u||2===u)if(n){s=o.getTransform(),o.setTransform(...n);const t=this.#xn(g,s,n);o.fill(t)}else o.fill(g);if(1===u||2===u)if(r){s||=o.getTransform(),o.setTransform(...r);const{a:t,b:e,c:i,d:n}=s,h=O.inverseTransform(r),a=O.transform([t,e,i,n,0,0],h);O.singularValueDecompose2dScale(a,ae),o.lineWidth*=Math.max(ae[0],ae[1])/c,o.stroke(this.#xn(g,s,r))}else o.lineWidth/=c,o.stroke(g);o.restore()}else 0!==u&&2!==u||(o.fillText(s,e,i),this.dependencyTracker?.recordCharacterBBox(t,o,a,c,e,i,(()=>o.measureText(s)))),1!==u&&2!==u||(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,o,a,c,e,i,(()=>o.measureText(s))).recordDependencies(t,ls),o.strokeText(s,e,i));d&&((this.pendingTextPaths||=[]).push({transform:ut(o),x:e,y:i,fontSize:c,path:g}),this.dependencyTracker?.recordCharacterBBox(t,o,a,c,e,i))}get isFontSubpixelAAEnabled(){const t=this.canvasFactory.create(10,10),s=t.context;s.scale(1.5,1),s.fillText("I",0,10);const e=s.getImageData(0,0,10,10).data;this.canvasFactory.destroy(t);let i=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){i=!0;break}return S(this,"isFontSubpixelAAEnabled",i)}showText(t,s){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,fs).resetBBox(t),4&this.current.textRenderingMode&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());const e=this.current,i=e.font;if(i.isType3Font){const i=this.#yn(e.fillAlpha);return this.showType3Text(t,s),this.dependencyTracker?.recordShowTextOperation(t),void this.#vn(i)}const n=e.fontSize;if(0===n)return void this.dependencyTracker?.recordOperation(t);const r=this.#yn(e.fillAlpha),o=this.ctx,h=e.fontSizeScale,a=e.charSpacing,l=e.wordSpacing,c=e.fontDirection,u=e.textHScale*c,d=s.length,f=i.vertical,p=f?1:-1,g=i.defaultVMetrics,m=n*e.fontMatrix[0],A=0===e.textRenderingMode&&!i.disableFontFace&&!e.patternFill;let w,b;o.save(),e.textMatrix&&o.transform(...e.textMatrix),o.translate(e.x,e.y+e.textRise),o.scale(u,c>0?-1:1);const y=3&e.textRenderingMode,v=0===y||2===y,x=1===y||2===y;let M=e.lineWidth;const k=e.textMatrixScale;if(0===k||0===M?x&&(M=this.getSinglePixelWidth()):M/=k,1!==h&&(o.scale(h,h),M/=h),o.lineWidth=M,v&&e.patternFill){o.save();const s=e.fillColor.getPattern(o,this,dt(o),Qs,t);w=ut(o),o.restore(),o.fillStyle=s}if(x&&e.patternStroke){o.save();const s=e.strokeColor.getPattern(o,this,dt(o),Js,t);b=ut(o),o.restore(),o.strokeStyle=s}if(i.isInvalidPDFjsFont){const i=[];let n=0;for(const t of s)i.push(t.unicode),n+=t.width;const h=i.join("");if(o.fillText(h,0,0),null!==this.dependencyTracker){const s=o.measureText(h);this.dependencyTracker.recordBBox(t,this.ctx,-s.actualBoundingBoxLeft,s.actualBoundingBoxRight,-s.actualBoundingBoxAscent,s.actualBoundingBoxDescent).recordShowTextOperation(t)}return e.x+=n*m*u,o.restore(),this.compose(),void this.#vn(r)}let C,S=0;for(C=0;C<d;++C){const e=s[C];if("number"==typeof e){S+=p*e*n/1e3;continue}let r=!1;const u=(e.isSpace?l:0)+a,d=e.fontChar,y=e.accent;let v,x,M,k=e.width;if(f){const t=e.vmetric||g,s=-(e.vmetric?t[1]:.5*k)*m;k=t?-t[0]:k,v=s/h,x=(S+t[2]*m)/h}else v=S/h,x=0;if(i.remeasure&&k>0){M=o.measureText(d);const t=1e3*M.width/n*h;if(k<t&&this.isFontSubpixelAAEnabled){const s=k/t;r=!0,o.save(),o.scale(s,1),v/=s}else k!==t&&(v+=(k-t)/2e3*n/h)}this.contentVisible&&(e.isInFont||i.missingFile)&&(A&&!y?(o.fillText(d,v,x),this.dependencyTracker?.recordCharacterBBox(t,o,M?{bbox:null}:i,n/h,v,x,(()=>M??o.measureText(d)))):(this.paintChar(t,d,v,x,w,b),y&&this.paintChar(t,y.fontChar,v+n*y.offset.x/h,x-n*y.offset.y/h,w,b))),S+=f?k*m-u*c:k*m+u*c,r&&o.restore()}f?e.y-=S:e.x+=S*u,o.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(t),this.#vn(r)}showType3Text(t,s){const e=this.ctx,n=this.current,r=n.font,o=n.fontSize,h=n.fontDirection,a=r.vertical?1:-1,l=n.charSpacing,c=n.wordSpacing,u=n.textHScale*h,d=n.fontMatrix||i,f=s.length;let g,m,A,w;if(3===n.textRenderingMode||0===o)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),n.textMatrix&&e.transform(...n.textMatrix),e.translate(n.x,n.y+n.textRise),e.scale(u,h);const b=this.dependencyTracker;for(this.dependencyTracker=b?new as(b,t):null,g=0;g<f;++g){if(m=s[g],"number"==typeof m){w=a*m*o/1e3,this.ctx.translate(w,0),n.x+=w*u;continue}const t=(m.isSpace?c:0)+l,i=r.charProcOperatorList.get(m.operatorListId);i?this.contentVisible&&(this.save(),i.fnArray[0]===p.setCharWidth&&(n.fillAlpha=n.strokeAlpha=1,e.globalAlpha=1),e.scale(o,o),e.transform(...d),this.executeOperatorList(i),this.restore()):y(`Type3 character "${m.operatorListId}" is not available.`);const h=[m.width,0];O.applyTransform(h,d),A=h[0]*o+t,e.translate(A,0),n.x+=A*u}e.restore(),b&&(this.dependencyTracker=b)}setCharWidth(t,s,e){}setCharWidthAndBounds(t,s,e,i,n,r,o){const h=new Path2D;h.rect(i,n,r-i,o-n),this.ctx.clip(h),this.dependencyTracker?.recordBBox(t,this.ctx,i,r,n,o).recordClipBox(t,this.ctx,i,r,n,o),this.endPath(t)}getColorN_Pattern(t,s){let e;if("TilingPattern"===s[0]){const t=this.baseTransform||ut(this.ctx);e=new oe(s,this.ctx,{createCanvasGraphics:(t,s)=>new ve(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new as(this.dependencyTracker,s,!0):null)},t)}else e=this._getPattern(t,s[1],s[2]);return e}setStrokeColorN(t,...s){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,s),this.current.patternStroke=!0}setFillColorN(t,...s){this.dependencyTracker?.recordSimpleData("fillColor",t);const e=this.current.fillColor=this.getColorN_Pattern(t,s);this.current.patternFill=!0,this.current.tilingPatternDims=e instanceof oe?[0,0,0,0]:null}setStrokeRGBColor(t,s){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=s,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,s){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=s,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(t,s,e=null){const i=this.cachedPatterns.getOrInsertComputed(s,(()=>function(t){switch(t[0]){case"RadialAxial":return new ee(t);case"Mesh":return new ne(t);case"Dummy":return new re}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,s))));return e&&(i.matrix=e),i}shadingFill(t,s){if(!this.contentVisible)return;const i=this.#yn(this.current.fillAlpha),n=this.ctx;this.save(t);const r=this._getPattern(t,s);n.fillStyle=r.getPattern(n,this,dt(n),Zs,t);const o=dt(n);if(o){const{width:t,height:s}=n.canvas,i=e.slice();O.axialAlignedBoundingBox([0,0,t,s],o,i);const[r,h,a,l]=i;this.ctx.fillRect(r,h,a-r,l-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,ps).recordDependencies(t,cs).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t),this.#vn(i)}beginInlineImage(){v("Should not call beginInlineImage")}beginImageData(){v("Should not call beginImageData")}paintFormXObjectBegin(t,s,e){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),s&&this.transform(t,...s),this.baseTransform=ut(this.ctx),e)){O.axialAlignedBoundingBox(e,this.baseTransform,this.current.minMax);const[s,i,n,r]=e,o=new Path2D;o.rect(s,i,n-s,r-i),this.ctx.clip(o),this.dependencyTracker?.recordClipBox(t,this.ctx,s,n,i,r),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,s){if(!this.contentVisible)return;this.save(t);const{inSMaskMode:i}=this;i&&(this.endSMaskMode(),this.current.activeSMask=null);const n=this.ctx;if(!(s.needsIsolation&&(s.isolated||s.hasSoftMask)||s.knockout||s.isGray||0!==this.#nn||1!==n.globalAlpha||"source-over"!==n.globalCompositeOperation||i)){if(s.bbox){let t=new Path2D;const[e,i,r,o]=s.bbox;if(t.rect(e,i,r-e,o-i),s.matrix){const e=new Path2D;e.addPath(t,new DOMMatrix(s.matrix)),t=e}n.clip(t)}return this.groupStack.push(null),this.#fn.push(null),void this.groupLevel++}s.isolated||s.knockout||0!==this.#nn||b("TODO: Fully support non-isolated non-knockout groups.");const r=ut(n);s.matrix&&n.transform(...s.matrix);const o=[0,0,n.canvas.width,n.canvas.height];let h;s.bbox?(h=e.slice(),O.axialAlignedBoundingBox(s.bbox,ut(n),h),h=O.intersect(h,o)||[0,0,0,0]):h=o;const a=Math.floor(h[0]),l=Math.floor(h[1]),c=Math.max(Math.ceil(h[2])-a,1),u=Math.max(Math.ceil(h[3])-l,1);this.current.startNewPathAndClipBox([0,0,c,u]);const d=this.canvasFactory.create(c,u);s.smask&&this.smaskGroupCanvases.push(d);const f=d.context,p=s.knockout&&!s.isolated?n:null,g=!s.isolated&&!s.knockout&&!s.smask&&s.needsIsolation&&this.#nn>0,m=s.knockout?this.canvasFactory.create(c,u):null,A=this.#nn;s.knockout?this.#nn++:this.#nn=0,f.translate(-a,-l),f.transform(...r);const w=!s.isolated&&!s.smask&&s.needsIsolation,y=w&&!i&&0===A&&!s.knockout&&!s.isGray&&s.hasSoftMask&&1===n.globalAlpha&&"source-over"===n.globalCompositeOperation&&"none"===this.current.transferMaps;if(w&&(i||y)&&(f.save(),f.setTransform(1,0,0,1,0,0),f.drawImage(n.canvas,-a,-l),f.restore()),s.bbox){let t=new Path2D;const[e,i,n,r]=s.bbox;if(t.rect(e,i,n-e,r-i),s.matrix){const e=new Path2D;e.addPath(t,new DOMMatrix(s.matrix)),t=e}f.clip(t)}s.smask&&this.smaskStack.push({canvas:d.canvas,context:f,offsetX:a,offsetY:l,subtype:s.smask.subtype,backdrop:s.smask.backdrop,transferMap:s.smask.transferMap||null}),s.smask&&!this.dependencyTracker||(n.setTransform(1,0,0,1,0,0),n.translate(a,l),n.save()),pe(n,f),this.ctx=f,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(n),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(n),this.#fn.push({backdropCtx:p,savedKnockoutLevel:A,offsetX:a,offsetY:l,hasInnerBackdrop:g,replaceBackdrop:y,knockoutMaskEntry:m,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(t,s){if(!this.contentVisible)return;this.groupLevel--;const i=this.ctx,n=this.groupStack.pop(),r=this.#fn.pop();if(r&&(this.#nn=r.savedKnockoutLevel),null!==n)if(s.isGray&&this.#Mn(i),this.ctx=n,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),s.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())),this.#gn(r);else{this.ctx.restore();const s=ut(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...s);const o=e.slice();O.axialAlignedBoundingBox([0,0,i.canvas.width,i.canvas.height],s,o);const h=this.#fn.at(-1);if(this.#nn>0)if(r.hasInnerBackdrop){const{width:t,height:e}=i.canvas,o=this.canvasFactory.create(t,e),h=o.context;h.drawImage(n.canvas,r.offsetX,r.offsetY,t,e,0,0,t,e),h.globalCompositeOperation="source-over",h.drawImage(i.canvas,0,0);const a=this.#An(i.canvas);h.globalCompositeOperation="destination-in",h.drawImage(a.canvas,0,0);const l=this.ctx.globalCompositeOperation,c=this.ctx.globalAlpha,u=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...s),this.ctx.globalAlpha=1,R.isCanvasFilterSupported&&(this.ctx.filter="none"),this.ctx.globalCompositeOperation="destination-out",this.ctx.drawImage(a.canvas,0,0),this.ctx.globalCompositeOperation=l,this.ctx.globalAlpha=c,R.isCanvasFilterSupported&&(this.ctx.filter=u??"none"),this.ctx.drawImage(o.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(a),this.canvasFactory.destroy(o)}else{const t=h?.backdropCtx??null;this.#bn(this.ctx,i.canvas,{backdropCanvas:t?.canvas??null,destTransform:s,backdropOffset:t?[h.offsetX+r.offsetX,h.offsetY+r.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}else{if(r.replaceBackdrop){const t=new Path2D;t.rect(0,0,i.canvas.width,i.canvas.height),this.ctx.clip(t),this.ctx.globalCompositeOperation="copy"}this.ctx.drawImage(i.canvas,0,0)}this.ctx.restore(),this.canvasFactory.destroy({canvas:i.canvas,context:i}),this.#gn(r),this.compose(o)}else this.restore(t)}#Mn(t){const{canvas:s}=t,{width:e,height:i}=s;if(R.isCanvasFilterSupported)return t.save(),t.setTransform(1,0,0,1,0,0),t.filter="grayscale(1)",t.globalAlpha=1,t.globalCompositeOperation="copy",t.drawImage(s,0,0),void t.restore();const n=t.getImageData(0,0,e,i),{data:r}=n;for(let t=0,s=r.length;t<s;t+=4)r[t]=r[t+1]=r[t+2]=.2126*r[t]+.7152*r[t+1]+.0722*r[t+2]+.5|0;t.putImageData(n,0,0)}#gn(t){t&&(t.knockoutMaskEntry&&(this.canvasFactory.destroy(t.knockoutMaskEntry),t.knockoutMaskEntry=null),t.knockoutTempEntry&&(this.canvasFactory.destroy(t.knockoutTempEntry),t.knockoutTempEntry=null),t.knockoutBackdropEntry&&(this.canvasFactory.destroy(t.knockoutBackdropEntry),t.knockoutBackdropEntry=null))}beginAnnotation(t,s,e,i,n,r,o){if(this.#pn(),ge(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const n=e[2]-e[0],h=e[3]-e[1];if(r&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0],i[5]-=e[1],O.singularValueDecompose2dScale(ut(this.ctx),ae);const{viewportScale:t}=this,r=Math.ceil(n*this.outputScaleX*t),a=Math.ceil(h*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(r,a);const{canvas:l,context:c}=this.annotationCanvas;if(o){const t=this.annotationCanvasMap.getOrInsertComputed(s,j);l.setAttribute("data-canvas-name",o);const e=t.findIndex((t=>t.getAttribute("data-canvas-name")===o));-1===e?t.push(l):t[e]=l}else this.annotationCanvasMap.set(s,l);this.annotationCanvas.savedCtx=this.ctx,this.ctx=c,this.ctx.save(),this.ctx.setTransform(ae[0],0,0,-ae[1],0,h*ae[1]),ge(this.ctx)}else{ge(this.ctx),this.endPath(t);const s=new Path2D;s.rect(e[0],e[1],n,h),this.ctx.clip(s)}}this.current=new ue(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(t,...i),this.transform(t,...n),this.baseTransform=ut(this.ctx)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#mn(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(t,s){if(!this.contentVisible)return;const e=s.count;(s=this.getObject(t,s.data,s)).count=e;const i=this.#yn(this.current.fillAlpha),n=this.ctx,r=this._createMaskCanvas(t,s),o=r.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(o,r.offsetX,r.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,r.offsetX,r.offsetX+o.width,r.offsetY,r.offsetY+o.height).recordOperation(t),n.restore(),r.canvasEntry&&this.canvasFactory.destroy(r.canvasEntry),this.compose(),this.#vn(i)}paintImageMaskXObjectRepeat(t,s,e,i=0,n=0,r,o){if(!this.contentVisible)return;s=this.getObject(t,s.data,s);const h=this.#yn(this.current.fillAlpha),a=this.ctx;a.save();const l=ut(a);a.transform(e,i,n,r,0,0);const c=this._createMaskCanvas(t,s);a.setTransform(1,0,0,1,c.offsetX-l[4],c.offsetY-l[5]),this.dependencyTracker?.resetBBox(t);for(let s=0,h=o.length;s<h;s+=2){const h=O.transform(l,[e,i,n,r,o[s],o[s+1]]);a.drawImage(c.canvas,h[4],h[5]),this.dependencyTracker?.recordBBox(t,this.ctx,h[4],h[4]+c.canvas.width,h[5],h[5]+c.canvas.height)}a.restore(),c.canvasEntry&&this.canvasFactory.destroy(c.canvasEntry),this.compose(),this.dependencyTracker?.recordOperation(t),this.#vn(h)}paintImageMaskXObjectGroup(t,s){if(!this.contentVisible)return;const e=this.#yn(this.current.fillAlpha),i=this.ctx,n=this.current.fillColor,r=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,gs);for(const e of s){const{data:s,width:o,height:h,transform:a}=e,l=this.canvasFactory.create(o,h),c=l.context;c.save(),fe(c,this.getObject(t,s,e)),c.globalCompositeOperation="source-in",c.fillStyle=r?n.getPattern(c,this,dt(i),Qs,t):n,c.fillRect(0,0,o,h),c.restore(),i.save(),i.transform(...a),i.scale(1,-1),ce(i,l.canvas,0,0,o,h,0,-1,1,1),this.canvasFactory.destroy(l),this.dependencyTracker?.recordBBox(t,i,0,o,0,h),i.restore()}this.compose(),this.dependencyTracker?.recordOperation(t),this.#vn(e)}paintImageXObject(t,s){if(!this.contentVisible)return;const e=this.getObject(t,s);e?this.paintInlineImageXObject(t,e):y("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,s,e,i,n){if(!this.contentVisible)return;const r=this.getObject(t,s);if(!r)return void y("Dependent image isn't ready yet");const o=r.width,h=r.height,a=[];for(let t=0,s=n.length;t<s;t+=2)a.push({transform:[e,0,0,i,n[t],n[t+1]],x:0,y:0,w:o,h});this.paintInlineImageXObjectGroup(t,r,a)}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{img:t.bitmap,canvasEntry:null};const{bitmap:s,width:e,height:i}=t,n=this.canvasFactory.create(e,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(s,0,0),r.filter="none",{img:n.canvas,canvasEntry:n}}paintInlineImageXObject(t,s){if(!this.contentVisible)return;const e=s.width,i=s.height,n=this.#yn(this.current.fillAlpha),r=this.ctx;this.save(t);const{filter:o}=r;let h;"none"!==o&&""!==o&&(r.filter="none"),r.scale(1/e,-1/i);let a=null;if(s.bitmap){const t=this.applyTransferMapsToBitmap(s);h=t.img,a=t.canvasEntry}else{const t=this.canvasFactory.create(e,i);de(t.context,s),h=this.applyTransferMapsToCanvas(t.context),a=t}const l=this._scaleImage(h,dt(r));r.imageSmoothingEnabled=me(ut(r),s.interpolate),this.dependencyTracker&&(this.dependencyTracker.resetBBox(t).recordBBox(t,r,0,e,-i,0).recordDependencies(t,us).recordOperation(t),this.imagesTracker?.record(r,e,i,this.dependencyTracker.clipBox)),ce(r,l.img,0,0,l.paintWidth,l.paintHeight,0,-i,e,i),l.tmpCanvas&&this.canvasFactory.destroy(l.tmpCanvas),a&&this.canvasFactory.destroy(a),this.compose(),this.restore(t),this.#vn(n)}paintInlineImageXObjectGroup(t,s,e){if(!this.contentVisible)return;const i=this.#yn(this.current.fillAlpha),n=this.ctx;let r,o=null;if(s.bitmap)r=s.bitmap;else{const t=this.canvasFactory.create(s.width,s.height);de(t.context,s),r=this.applyTransferMapsToCanvas(t.context),o=t}this.dependencyTracker?.resetBBox(t);for(const s of e)n.save(),n.transform(...s.transform),n.scale(1,-1),ce(n,r,s.x,s.y,s.w,s.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,n,0,1,-1,0),n.restore();o&&this.canvasFactory.destroy(o),this.dependencyTracker?.recordOperation(t),this.compose(),this.#vn(i)}paintSolidColorImageMask(t){if(!this.contentVisible)return;const s=this.#yn(this.current.fillAlpha);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,cs).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose(),this.#vn(s)}markPoint(t,s){}markPointProps(t,s,e){}beginMarkedContent(t,s){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,s,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push("OC"===s?{visible:this.optionalContentConfig.isVisible(e)}:{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,s,e){const i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(e);const n=this.ctx;this.pendingClip?(i||(this.pendingClip===ye?n.clip(s,"evenodd"):n.clip(s)),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=ut(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const s=Math.abs(t[0]*t[3]-t[2]*t[1]),e=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(e,i)/s}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:s,b:e,c:i,d:n}=this.ctx.getTransform();let r,o;if(0===e&&0===i){const e=Math.abs(s),i=Math.abs(n);if(e===i)if(0===t)r=o=1/e;else{const s=e*t;r=o=s<1?1/s:1}else if(0===t)r=1/e,o=1/i;else{const s=e*t,n=i*t;r=s<1?1/s:1,o=n<1?1/n:1}}else{const h=Math.abs(s*n-e*i),a=Math.hypot(s,e),l=Math.hypot(i,n);if(0===t)r=l/h,o=a/h;else{const s=t*h;r=l>s?l/s:1,o=a>s?a/s:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t,s){const{ctx:e,current:{lineWidth:i}}=this,[n,r]=this.getScaleForStroking();if(n===r)return e.lineWidth=(i||1)*n,void e.stroke(t);const o=ve.#in??=new DOMMatrix,h=e.getLineDash();s&&e.save(),e.scale(n,r),o.a=1/n,o.d=1/r;const a=new Path2D;if(a.addPath(t,o),h.length>0){const t=Math.max(n,r);e.setLineDash(h.map((s=>s/t))),e.lineDashOffset/=t}e.lineWidth=i||1,e.stroke(a),s&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in p)void 0!==ve.prototype[t]&&(ve.prototype[p[t]]=ve.prototype[t]);class xe{#kn=null;#Cn=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,s,e){this._source=t,this.#kn=s,this.#Cn=e}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return x(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new this.#kn(this)}getRangeReader(t,s){if(s<=this._progressiveDataLength)return null;const e=new this.#Cn(this,t,s);return this._rangeReaders.add(e),e}cancelAllRequests(t){this._fullReader?.cancel(t);for(const s of new Set(this._rangeReaders))s.cancel(t)}}class Me{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=t}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}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(){v("Abstract method `read` called")}cancel(t){v("Abstract method `cancel` called")}}class ke{_stream=null;constructor(t,s,e){this._stream=t}async read(){v("Abstract method `read` called")}cancel(t){v("Abstract method `cancel` called")}}function Ce(t,s){const e=new Headers;if(!t||!s||"object"!=typeof s)return e;for(const t in s){const i=s[t];void 0!==i&&e.append(t,i)}return e}function Se(t){return URL.parse(t)?.origin??null}function Te({responseHeaders:t,isHttp:s,rangeChunkSize:e,disableRange:i}){const n={contentLength:0,isRangeSupported:!1},r=parseInt(t.get("Content-Length"),10);return Number.isInteger(r)?(n.contentLength=r,r<=2*e||i||!s||"bytes"!==t.get("Accept-Ranges")||"identity"===(t.get("Content-Encoding")||"identity")&&(n.isRangeSupported=!0),n):n}function Pe(t){const s=t.get("Content-Disposition");if(s){let t=function(t){let s=!0,e=i("filename\\*","i").exec(t);if(e){e=e[1];let t=o(e);return t=unescape(t),t=h(t),t=a(t),r(t)}if(e=function(t){const s=[];let e;const n=i("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(e=n.exec(t));){let[,t,i,n]=e;if(t=parseInt(t,10),t in s){if(0===t)break}else s[t]=[i,n]}const r=[];for(let t=0;t<s.length&&t in s;++t){let[e,i]=s[t];i=o(i),e&&(i=unescape(i),0===t&&(i=h(i))),r.push(i)}return r.join("")}(t),e)return r(a(e));if(e=i("filename","i").exec(t),e){e=e[1];let t=o(e);return t=a(t),r(t)}function i(t,s){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',s)}function n(t,e){if(t){if(!/^[\x00-\xFF]+$/.test(e))return e;try{const i=new TextDecoder(t,{fatal:!0}),n=_(e);e=i.decode(n),s=!1}catch{}}return e}function r(t){return s&&/[\x80-\xff]/.test(t)&&(t=n("utf-8",t),s&&(t=n("iso-8859-1",t))),t}function o(t){if(t.startsWith('"')){const s=t.slice(1).split('\\"');for(let t=0;t<s.length;++t){const e=s[t].indexOf('"');-1!==e&&(s[t]=s[t].slice(0,e),s.length=t+1),s[t]=s[t].replaceAll(/\\(.)/g,"$1")}t=s.join('"')}return t}function h(t){const s=t.indexOf("'");return-1===s?t:n(t.slice(0,s),t.slice(s+1).replace(/^[^']*'/,""))}function a(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QB])\?((?:[^?]|\?(?!=))*)\?=/gi,(function(t,s,e,i){if("q"===e||"Q"===e)return n(s,i=(i=i.replaceAll("_"," ")).replaceAll(/=([0-9a-f]{2})/gi,(function(t,s){return String.fromCharCode(parseInt(s,16))})));try{i=atob(i)}catch{}return n(s,i)}))}return""}(s);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(st(t))return t}return null}function Ee(t,s){return new N(`Unexpected server response (${t}) while retrieving PDF "${s.href}".`,t,404===t||0===t&&"file:"===s.protocol)}function De(t,s){if(t!==s)throw new Error(`Expected range response-origin "${t}" to match "${s}".`)}function Ne(t,s,e,i){return fetch(t,{method:"GET",headers:s,signal:i.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"})}function Ie(t,s){if(200!==t&&206!==t)throw Ee(t,s)}function Fe(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;throw new Error(`getArrayBuffer - unexpected data: ${t}`)}class _e extends xe{_responseOrigin=null;constructor(t){super(t,Re,Oe);const{httpHeaders:s,url:e}=t;x(/https?:/.test(e.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=Ce(!0,s)}}class Re extends Me{_abortController=new AbortController;_reader=null;constructor(t){super(t);const{disableRange:s,disableStream:e,rangeChunkSize:i,url:n,withCredentials:r}=t._source;this._isStreamingSupported=!e;const o=new Headers(t.headers);Ne(n,o,r,this._abortController).then((e=>{t._responseOrigin=Se(e.url),Ie(e.status,n),this._reader=e.body.getReader();const r=e.headers,{contentLength:o,isRangeSupported:h}=Te({responseHeaders:r,isHttp:!0,rangeChunkSize:i,disableRange:s});this._contentLength=o,this._isRangeSupported=h,this._filename=Pe(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new F("Streaming is disabled.")),this._headersCapability.resolve()})).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:s}=await this._reader.read();return s?{value:t,done:s}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Fe(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Oe extends ke{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,s,e){super(t,s,e);const{url:i,withCredentials:n}=t._source,r=new Headers(t.headers);r.append("Range",`bytes=${s}-${e-1}`),Ne(i,r,n,this._abortController).then((s=>{De(Se(s.url),t._responseOrigin),Ie(s.status,i),this._reader=s.body.getReader(),this._readCapability.resolve()})).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:s}=await this._reader.read();return s?{value:t,done:s}:{value:Fe(t),done:!1}}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}function Be(t){return t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function $e(){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}class Le extends xe{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,Ue,je);const{pdfDataRangeTransport:s}=t,{initialData:e,progressiveDone:i}=s;if(e?.length>0){const t=Be(e);this._queuedChunks.push(t)}this._progressiveDone=i,s.transportReady((t=>{switch(t.type){case"range":case"progressiveRead":this.#Sn(t.begin,t.chunk);break;case"progressiveDone":this._fullReader?.progressiveDone(),this._progressiveDone=!0}}))}#Sn(t,s){const e=Be(s);if(void 0===t)this._fullReader?this._fullReader._enqueue(e):this._queuedChunks.push(e);else{const s=this._rangeReaders.keys().find((s=>s._begin===t));x(s,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),s._enqueue(e)}}getFullReader(){const t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,s){const e=super.getRangeReader(t,s);return e&&(e.onDone=()=>this._rangeReaders.delete(e),this._source.pdfDataRangeTransport.requestDataRange(t,s)),e}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}}class Ue extends Me{#Tn=$e.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:s,disableRange:e,disableStream:i}=t._source,{length:n,contentDispositionFilename:r}=s;this._queuedChunks=t._queuedChunks||[];for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._done=t._progressiveDone,this._contentLength=n,this._isStreamingSupported=!i,this._isRangeSupported=!e,st(r)&&(this._filename=r),this._headersCapability.resolve();const o=this._loaded;Promise.resolve().then((()=>{o>0&&this._loaded===o&&this._callOnProgress()}))}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength,this._callOnProgress())}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,this.#Tn()}progressiveDone(){this._done||=!0,0===this._queuedChunks.length&&this.#Tn()}}class je extends ke{#Tn=$e.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,s,e){super(t,s,e),this._begin=s}_enqueue(t){this._done||(0===this._requests.length?this._queuedChunk=t:(this._requests.shift().resolve({value:t,done:!1}),this.#Tn()),this._done=!0,this.onDone?.())}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,this.#Tn(),this.onDone?.()}}class Ge extends xe{#Pn=new WeakMap;_responseOrigin=null;constructor(t){super(t,ze,He);const{httpHeaders:s,url:e}=t;this.url=e,this.isHttp=/https?:/.test(e.protocol),this.headers=Ce(this.isHttp,s)}_request(t){const s=new XMLHttpRequest,e={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#Pn.set(s,e),s.open("GET",this.url),s.withCredentials=this._source.withCredentials;for(const[t,e]of this.headers)s.setRequestHeader(t,e);return this.isHttp&&"begin"in t&&"end"in t?(s.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),e.validateStatus=t=>206===t||200===t):e.validateStatus=t=>200===t,s.responseType="arraybuffer",x(t.onError,"Expected `onError` callback to be provided."),s.onerror=()=>t.onError(s.status),s.onreadystatechange=this.#En.bind(this,s),s.onprogress=this.#Dn.bind(this,s),s.send(null),s}#Dn(t,s){const e=this.#Pn.get(t);e?.onProgress?.(s)}#En(t,s){const e=this.#Pn.get(t);if(!e)return;if(t.readyState>=2&&e.onHeadersReceived&&(e.onHeadersReceived(),delete e.onHeadersReceived),4!==t.readyState)return;if(!this.#Pn.has(t))return;if(this.#Pn.delete(t),0===t.status&&this.isHttp)return void e.onError(t.status);const i=t.status||200;if(!e.validateStatus(i))return void e.onError(t.status);const n="string"!=typeof(r=t.response)?r:_(r).buffer;var r;if(206===i){const s=t.getResponseHeader("Content-Range");/bytes \d+-\d+\/\d+/.test(s)?e.onDone(n):(y('Missing or invalid "Content-Range" header.'),e.onError(0))}else n?e.onDone(n):e.onError(t.status)}_abortRequest(t){this.#Pn.has(t)&&(this.#Pn.delete(t),t.abort())}getRangeReader(t,s){const e=super.getRangeReader(t,s);return e&&(e.onClosed=()=>this._rangeReaders.delete(e)),e}}class ze extends Me{#Tn=$e.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t),this._fullRequestXhr=t._request({onHeadersReceived:this.#Nn.bind(this),onDone:this.#In.bind(this),onError:this.#Fn.bind(this),onProgress:this.#Dn.bind(this)})}#Nn(){const t=this._stream,{disableRange:s,rangeChunkSize:e}=t._source,i=this._fullRequestXhr;t._responseOrigin=Se(i.responseURL);const n=i.getAllResponseHeaders(),r=new Headers(n?function(t){let s=t.length;for(;s>0&&" "!==t[s-1]&&/\s/.test(t[s-1]);)s--;return t.slice(0,s)}(n.trimStart()).split(/[\r\n]+/).map((t=>{const[s,...e]=t.split(": ");return[s,e.join(": ")]})):[]),{contentLength:o,isRangeSupported:h}=Te({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:e,disableRange:s});this._contentLength=o,this._isRangeSupported=h,this._filename=Pe(r),this._isRangeSupported&&t._abortRequest(i),this._headersCapability.resolve()}#In(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._cachedChunks.push(t),this._done=!0,0===this._cachedChunks.length&&this.#Tn()}#Fn(t){this._storedError=Ee(t,this._stream.url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#Dn(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}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),this.#Tn(),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}class He extends ke{#Tn=$e.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,s,e){super(t,s,e),this._requestXhr=t._request({begin:s,end:e,onHeadersReceived:this.#Nn.bind(this),onDone:this.#In.bind(this),onError:this.#Fn.bind(this),onProgress:null})}#Nn(){const t=Se(this._requestXhr?.responseURL);try{De(t,this._stream._responseOrigin)}catch(t){this._storedError=t,this.#Fn(0)}}#In(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0,this.#Tn(),this.onClosed?.()}#Fn(t){this._storedError??=Ee(t,this._stream.url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}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,this.#Tn(),this._stream._abortRequest(this._requestXhr),this.onClosed?.()}}function We(t,s=null){const e=process.getBuiltinModule("fs"),{Readable:i}=process.getBuiltinModule("stream"),n=e.createReadStream(t,s);return i.toWeb(n)}class Ve extends xe{constructor(t){super(t,Xe,Ye);const{url:s}=t;x("file:"===s.protocol,"PDFNodeStream only supports file:// URLs.")}}class Xe extends Me{_reader=null;constructor(t){super(t);const{disableRange:s,disableStream:e,rangeChunkSize:i,url:n}=t._source;this._isStreamingSupported=!e,process.getBuiltinModule("fs/promises").lstat(n).then((t=>{const e=We(n);this._reader=e.getReader();const{size:r}=t;this._contentLength=r,this._isRangeSupported=!s&&r>2*i,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new F("Streaming is disabled.")),this._headersCapability.resolve()})).catch((t=>{"ENOENT"===t.code&&(t=Ee(0,n)),this._headersCapability.reject(t)}))}async read(){await this._headersCapability.promise;const{value:t,done:s}=await this._reader.read();return s?{value:t,done:s}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Fe(t),done:!1})}cancel(t){this._reader?.cancel(t)}}class Ye extends ke{_readCapability=Promise.withResolvers();_reader=null;constructor(t,s,e){super(t,s,e);const{url:i}=t._source;try{const t=We(i,{start:s,end:e-1});this._reader=t.getReader(),this._readCapability.resolve()}catch(t){this._readCapability.reject(t)}}async read(){await this._readCapability.promise;const{value:t,done:s}=await this._reader.read();return s?{value:t,done:s}:{value:Fe(t),done:!1}}cancel(t){this._reader?.cancel(t)}}class Ke{static#_n=null;static#Rn="";static get workerPort(){return this.#_n}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#_n=t}static get workerSrc(){return this.#Rn}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Rn=t}}class qe{#On;#Bn;constructor({parsedData:t,rawData:s}){this.#On=t,this.#Bn=s}getRaw(){return this.#Bn}get(t){return this.#On.get(t)??null}[Symbol.iterator](){return this.#On.entries()}}const Qe=Symbol("INTERNAL");class Je{#$n=!1;#Ln=!1;#Un=!1;#jn=!0;constructor(t,{name:s,intent:e,usage:i,rbGroups:n}){this.#$n=!!(2&t),this.#Ln=!!(4&t),this.name=s,this.intent=e,this.usage=i,this.rbGroups=n}get visible(){if(this.#Un)return this.#jn;if(!this.#jn)return!1;const{print:t,view:s}=this.usage;return this.#$n?"OFF"!==s?.viewState:!this.#Ln||"OFF"!==t?.printState}_setVisible(t,s,e=!1){t!==Qe&&v("Internal method `_setVisible` called."),this.#Un=e,this.#jn=s}get serializable(){return{userSet:this.#Un,visible:this.#jn}}}class Ze{#Gn=null;#zn=new Map;#Hn=null;#Wn=null;#Vn;creator=null;name=null;constructor(t,s=2,e=null){if(this.#Vn=t,this.renderingIntent=s,null!==t){this.name=t.name,this.creator=t.creator,this.#Wn=t.order;for(const e of t.groups)this.#zn.set(e.id,new Je(s,e));if(e){e.size!==this.#zn.size&&v("Incorrect serialized groupState.");for(const[t,s]of e)this.#zn.get(t)._setVisible(Qe,s.visible,s.userSet)}else{if("OFF"===t.baseState)for(const t of this.#zn.values())t._setVisible(Qe,!1);for(const s of t.on)this.#zn.get(s)._setVisible(Qe,!0);for(const s of t.off)this.#zn.get(s)._setVisible(Qe,!1)}this.#Hn=this.getHash()}}#Xn(t){const s=t.length;if(s<2)return!0;const e=t[0];for(let i=1;i<s;i++){const s=t[i];let n;if(Array.isArray(s))n=this.#Xn(s);else{if(!this.#zn.has(s))return y(`Optional content group not found: ${s}`),!0;n=this.#zn.get(s).visible}switch(e){case"And":if(!n)return!1;break;case"Or":if(n)return!0;break;case"Not":return!n;default:return!0}}return"And"===e}isVisible(t){if(0===this.#zn.size)return!0;if(!t)return b("Optional content group not defined."),!0;if("OCG"===t.type)return this.#zn.has(t.id)?this.#zn.get(t.id).visible:(y(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#Xn(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const s of t.ids){if(!this.#zn.has(s))return y(`Optional content group not found: ${s}`),!0;if(this.#zn.get(s).visible)return!0}return!1}if("AllOn"===t.policy){for(const s of t.ids){if(!this.#zn.has(s))return y(`Optional content group not found: ${s}`),!0;if(!this.#zn.get(s).visible)return!1}return!0}if("AnyOff"===t.policy){for(const s of t.ids){if(!this.#zn.has(s))return y(`Optional content group not found: ${s}`),!0;if(!this.#zn.get(s).visible)return!0}return!1}if("AllOff"===t.policy){for(const s of t.ids){if(!this.#zn.has(s))return y(`Optional content group not found: ${s}`),!0;if(this.#zn.get(s).visible)return!1}return!0}return y(`Unknown optional content policy ${t.policy}.`),!0}return y(`Unknown group type ${t.type}.`),!0}setVisibility(t,s=!0,e=!0){const i=this.#zn.get(t);if(i){if(e&&s&&i.rbGroups.length)for(const s of i.rbGroups)for(const e of s)e!==t&&this.#zn.get(e)?._setVisible(Qe,!1,!0);i._setVisible(Qe,!!s,!0),this.#Gn=null}else y(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:s}){let e;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":e=i;continue}const t=this.#zn.get(i);if(t)switch(e){case"ON":this.setVisibility(i,!0,s);break;case"OFF":this.setVisibility(i,!1,s);break;case"Toggle":this.setVisibility(i,!t.visible,s)}}this.#Gn=null}get hasInitialVisibility(){return null===this.#Hn||this.getHash()===this.#Hn}getOrder(){return this.#zn.size?this.#Wn?this.#Wn.slice():[...this.#zn.keys()]:null}getGroup(t){return this.#zn.get(t)||null}getHash(){if(null!==this.#Gn)return this.#Gn;const t=new Kt;for(const[s,e]of this.#zn)t.update(`${s}:${e.visible}`);return this.#Gn=t.hexdigest()}[Symbol.iterator](){return this.#zn.entries()}get serializable(){const t=new Map;for(const[s,e]of this.#zn)t.set(s,e.serializable);return{data:this.#Vn,renderingIntent:this.renderingIntent,groupState:t}}static fromSerializable({data:t,renderingIntent:s,groupState:e}){return new Ze(t,s,e)}}class ti{#Yn=null;#Kn=null;#qn=0;#Qn=null;#Jn=null;get pagesNumber(){return this.#qn}set pagesNumber(t){this.#qn!==t&&(this.#qn=t,this.#Yn=null,this.#Kn=null)}#Zn(){if(this.#Yn)return;const t=this.#qn,s=this.#Yn=new Uint32Array(t);for(let e=0;e<t;e++)s[e]=e+1;this.#Kn=new Int32Array(s)}#tr(){const t=new Map,s=this.#Yn;for(let e=0,i=this.#qn;e<i;e++){const i=s[e],n=t.get(i);n?n.push(e+1):t.set(i,[e+1])}return t}movePages(t,s,e){this.#Zn();const i=this.#Yn,n=s.length,r=new Uint32Array(n);let o=0;for(let t=0;t<n;t++){const n=s[t]-1;r[t]=i[n],n<e&&o++}const h=this.#qn,a=h-n,l=new Int32Array(h),c=W(e-o,0,a);for(let s=0,e=0;s<h;s++)t.has(s+1)||(i[e]=i[s],l[e++]=s+1);i.copyWithin(c+n,c,a),i.set(r,c),l.copyWithin(c+n,c,a),l.set(s,c),this.#Kn=l,i.every(((t,s)=>t===s+1))&&(this.#Yn=null)}deletePages(t){this.#Zn();const s=this.#Yn,e=this.#tr();this.#Jn={pageNumberToId:s.slice(),pagesNumber:this.#qn,prevPageNumbers:this.#Kn.slice()};const i=this.#qn-t.length;this.#qn=i;const n=this.#Yn=new Uint32Array(i);this.#Kn=new Int32Array(i);let r=0,o=0;for(const e of t){const t=e-1;t!==r&&(n.set(s.subarray(r,t),o),o+=t-r),r=t+1}r<s.length&&n.set(s.subarray(r),o),this.#sr(e,new Set(t))}cancelDelete(){this.#Jn&&(this.#Yn=this.#Jn.pageNumberToId,this.#qn=this.#Jn.pagesNumber,this.#Kn=this.#Jn.prevPageNumbers,this.#Jn=null)}cleanSavedData(){this.#Jn=null}copyPages(t){this.#Zn(),this.#Qn={pageNumbers:t,pageIds:t.map((t=>this.#Yn[t-1]))}}cancelCopy(){this.#Qn=null}pastePages(t){this.#Zn();const s=this.#Yn,e=this.#tr(),{pageNumbers:i,pageIds:n}=this.#Qn,r=this.#qn+i.length;this.#qn=r;const o=this.#Yn=new Uint32Array(r);this.#Kn=new Int32Array(r),o.set(s.subarray(0,t),0),o.set(n,t),o.set(s.subarray(t),t+i.length),this.#sr(e,null,t,i),this.#Qn=null}#sr(t,s=null,e=-1,i=null){const n=this.#Kn,r=this.#Yn,o=e+(i?.length??0),h=new Map;for(let a=0,l=this.#qn;a<l;a++){if(a>=e&&a<o){n[a]=-i[a-e];continue}const l=r[a],c=t.get(l);let u=h.get(l)||0;if(s&&c)for(;u<c.length&&s.has(c[u]);)u++;n[a]=c?.[u],h.set(l,u+1)}}hasBeenAltered(){return null!==this.#Yn}#er(t=null){if(!this.#Yn)return null;const s=new Int32Array(this.#qn).fill(-1),e=new Map;if(t)for(const i of t){const t=this.getPageId(i),n=e.get(t)??0;e.set(t,n+1),s[i-1]=n}else for(let t=0,i=this.#qn;t<i;t++){const i=this.#Yn[t],n=e.get(i)??0;e.set(i,n+1),s[t]=n}return s}getPageMappingForSaving(t=null,s=this.#er()){t??=this.#tr();let e=0;for(const s of t.values())e=Math.max(e,s.length);const i=new Array(e);for(let t=0;t<e;t++)i[t]={document:null,pageIndices:[],includePages:[]};for(const[s,e]of t)for(let t=0,n=e.length;t<n;t++)i[t].includePages.push([s-1,e[t]-1]);for(const{includePages:t,pageIndices:s}of i){t.sort(((t,s)=>t[0]-s[0]));for(let e=0,i=t.length;e<i;e++)s.push(t[e][1]),t[e]=t[e][0]}return{pageInfos:i,copyLevels:s}}extractPages(t){t=Array.from(t).sort(((t,s)=>t-s));const s=new Map;for(let e=0,i=t.length;e<i;e++){const i=this.getPageId(t[e]);s.getOrInsertComputed(i,j).push(e+1)}return this.getPageMappingForSaving(s,this.#er(t))}getPrevPageNumber(t){return this.#Kn?.[t-1]??0}getPageNumber(t){if(!this.#Yn)return t;const s=this.#Yn;for(let e=0,i=this.#qn;e<i;e++)if(s[e]===t)return e+1;return 0}getPageId(t){return this.#Yn?.[t-1]??t}getMapping(){return this.#Yn?.subarray(0,this.pagesNumber)}}const si=Symbol("INITIAL_DATA"),ei=()=>({...Promise.withResolvers(),data:si});class ii{#ir=new Map;get(t,s=null){if(s){const e=this.#ir.getOrInsertComputed(t,ei);return e.promise.then((()=>s(e.data))),null}const e=this.#ir.get(t);if(!e||e.data===si)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return e.data}has(t){const s=this.#ir.get(t);return!!s&&s.data!==si}delete(t){const s=this.#ir.get(t);return!(!s||s.data===si||(this.#ir.delete(t),0))}resolve(t,s=null){const e=this.#ir.getOrInsertComputed(t,ei);if(e.data!==si)throw new Error(`Object already resolved ${t}.`);e.data=s,e.resolve()}clear(){for(const{data:t}of this.#ir.values())t?.bitmap?.close();this.#ir.clear()}*[Symbol.iterator](){for(const[t,{data:s}]of this.#ir)s!==si&&(yield[t,s])}}class ni{#nr=Promise.withResolvers();#Dt=null;#rr=!1;#or=!!globalThis.FontInspector?.enabled;#hr=null;#ar=null;#lr=null;#cr=0;#ur=0;#dr=null;#fr=null;#pr=0;#gr=0;#mr=Object.create(null);#Ar=[];#wr=null;#br=[];#yr=new WeakMap;#vr=null;static#xr=new Map;static#Mr=new Map;static#kr=new WeakMap;static#Cr=null;static#Sr=new Set;constructor({textContentSource:t,images:s,container:e,viewport:i}){if(t instanceof ReadableStream)this.#wr=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#wr=new ReadableStream({start(s){s.enqueue(t),s.close()}})}this.#Dt=this.#fr=e,this.#hr=s,this.#gr=i.scale*pt.pixelRatio,this.#pr=i.rotation,this.#lr={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:r,pageX:o,pageY:h}=i.rawDims;this.#vr=[1,0,0,-1,-o,h+r],this.#ur=n,this.#cr=r,ni.#Tr(),e.style.setProperty("--min-font-size",ni.#Cr),ft(e,i),this.#nr.promise.finally((()=>{ni.#Sr.delete(this),this.#lr=null,this.#mr=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:s}=R.platform;return S(this,"fontFamilyMap",new Map([["sans-serif",(t&&s?"Calibri, ":"")+"sans-serif"],["monospace",(t&&s?"Lucida Console, ":"")+"monospace"]]))}render(){this.#hr&&this.#Dt.append(this.#hr.render());const t=()=>{this.#dr.read().then((({value:s,done:e})=>{e?this.#nr.resolve():(this.#ar??=s.lang,Object.assign(this.#mr,s.styles),this.#Pr(s.items),t())}),this.#nr.reject)};return this.#dr=this.#wr.getReader(),ni.#Sr.add(this),t(),this.#nr.promise}update({viewport:t,onBefore:s=null}){const e=t.scale*pt.pixelRatio,i=t.rotation;if(i!==this.#pr&&(s?.(),this.#pr=i,ft(this.#fr,{rotation:i})),e!==this.#gr){s?.(),this.#gr=e;const t={div:null,properties:null,ctx:ni.#Er(this.#ar)};for(const s of this.#br)t.properties=this.#yr.get(s),t.div=s,this.#Dr(t)}}cancel(){const t=new F("TextLayer task cancelled.");this.#dr?.cancel(t).catch((()=>{})),this.#dr=null,this.#nr.reject(t)}get textDivs(){return this.#br}get textContentItemsStr(){return this.#Ar}#Pr(t){if(this.#rr)return;this.#lr.ctx??=ni.#Er(this.#ar);const s=this.#br,e=this.#Ar;for(const i of t){if(s.length>1e5)return y("Ignoring additional textDivs for performance reasons."),void(this.#rr=!0);if(void 0!==i.str)e.push(i.str),this.#Nr(i);else if("beginMarkedContentProps"===i.type||"beginMarkedContent"===i.type){const t=this.#Dt;this.#Dt=document.createElement("span"),this.#Dt.classList.add("markedContent"),i.id&&this.#Dt.setAttribute("id",i.id),"Artifact"===i.tag&&(this.#Dt.ariaHidden=!0),t.append(this.#Dt)}else"endMarkedContent"===i.type&&(this.#Dt=this.#Dt.parentNode)}}#Nr(t){const s=document.createElement("span"),e={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#br.push(s);const i=O.transform(this.#vr,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#mr[t.fontName];r.vertical&&(n+=Math.PI/2);let o=this.#or&&r.fontSubstitution||r.fontFamily;o=ni.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),a=h*ni.#Ir(o,r,this.#ar);let l,c;0===n?(l=i[4],c=i[5]-a):(l=i[4]+a*Math.sin(n),c=i[5]-a*Math.cos(n));const u=s.style;u.left=`${(100*l/this.#ur).toFixed(2)}%`,u.top=`${(100*c/this.#cr).toFixed(2)}%`,u.setProperty("--font-height",`${h.toFixed(2)}px`),u.fontFamily=o,e.fontSize=h,s.setAttribute("role","presentation"),s.textContent=t.str,s.dir=t.dir,this.#or&&(s.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),0!==n&&(e.angle=n*(180/Math.PI));let d=!1;if(t.str.length>1)d=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const s=Math.abs(t.transform[0]),e=Math.abs(t.transform[3]);s!==e&&Math.max(s,e)/Math.min(s,e)>1.5&&(d=!0)}if(d&&(e.canvasWidth=r.vertical?t.height:t.width),this.#yr.set(s,e),this.#lr.div=s,this.#lr.properties=e,this.#Dr(this.#lr),e.hasText&&this.#Dt.append(s),e.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#Dt.append(t)}}#Dr(t){const{div:s,properties:e,ctx:i}=t,{style:n}=s;if(0!==e.canvasWidth&&e.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=e;ni.#Fr(i,o*this.#gr,t);const{width:h}=i.measureText(s.textContent);h>0&&n.setProperty("--scale-x",r*this.#gr/h)}0!==e.angle&&n.setProperty("--rotate",`${e.angle}deg`)}static cleanup(){if(!(this.#Sr.size>0)){this.#xr.clear();for(const{canvas:t}of this.#Mr.values())t.remove();this.#Mr.clear()}}static#Er(t=null){let s=this.#Mr.get(t||="");if(!s){const e=document.createElement("canvas");e.style.cssText="position:absolute;top:0;left:0;width:0;height:0;display:none;letter-spacing:normal;word-spacing:normal",e.lang=t,document.body.append(e),s=e.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#Mr.set(t,s),this.#kr.set(s,{size:0,family:""})}return s}static#Fr(t,s,e){const i=this.#kr.get(t);s===i.size&&e===i.family||(t.font=`${s}px ${e}`,i.size=s,i.family=e)}static#Tr(){if(null!==this.#Cr)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.#Cr=t.getBoundingClientRect().height,t.remove()}static#Ir(t,s,e){const i=this.#xr.get(t);if(i)return i;const n=this.#Er(e);n.canvas.width=n.canvas.height=30,this.#Fr(n,30,t);const r=n.measureText(""),o=r.fontBoundingBoxAscent,h=Math.abs(r.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let a=.8;return o?a=o/(o+h):(R.platform.isFirefox&&y("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),s.ascent?a=s.ascent:s.descent&&(a=1+s.descent)),this.#xr.set(t,a),a}}function ri(s={}){const e=new oi,{docId:i}=e,n=s.url?function(s){if(s instanceof URL)return s;if("string"==typeof s){if(t){if(/^[a-z][a-z0-9\-+.]+:/i.test(s))return new URL(s);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(s))}const e=URL.parse(s,window.location);if(e)return e}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(s.url):null,r=s.data?function(s){if(t&&"undefined"!=typeof Buffer&&s instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(s instanceof Uint8Array&&s.byteLength===s.buffer.byteLength)return s;if("string"==typeof s)return _(s);if(s instanceof ArrayBuffer||ArrayBuffer.isView(s)||"object"==typeof s&&!isNaN(s?.length))return new Uint8Array(s);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(s.data):null,o=s.httpHeaders||null,h=!0===s.withCredentials,a=s.password??null,l=s.range instanceof hi?s.range:null,c=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:65536;let u=s.worker instanceof ci?s.worker:null;const d=s.verbosity,f="string"!=typeof s.docBaseUrl||tt(s.docBaseUrl)?null:s.docBaseUrl,p=Ns(s.cMapUrl),g=!1!==s.cMapPacked,m=Ns(s.iccUrl),w=Ns(s.standardFontDataUrl),b=Ns(s.wasmUrl),y=!0!==s.stopAtErrors,v=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,x="boolean"==typeof s.isOffscreenCanvasSupported?s.isOffscreenCanvasSupported:!t,M="boolean"==typeof s.isImageDecoderSupported?s.isImageDecoderSupported:!t,k=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,C="boolean"==typeof s.disableFontFace?s.disableFontFace:t,S=!0===s.fontExtraProperties,T=!0===s.enableXfa,P=s.ownerDocument||globalThis.document,E=!0===s.disableRange,D=!0===s.disableStream,N=!0===s.disableAutoFetch,I=!0===s.pdfBug,F=s.CanvasFactory||(t?Vs:js),R=s.FilterFactory||(t?Ws:zs),O=s.BinaryDataFactory||(t?Xs:Ls),B=!0===s.enableHWA,$=!0===s.enableWebGPU?qs.init():Promise.resolve(!1),L=!1!==s.useWasm,U=s.pagesMapper||new ti,j="boolean"==typeof s.useSystemFonts?s.useSystemFonts:!t&&!C,G="boolean"==typeof s.useWorkerFetch?s.useWorkerFetch:!!(O===Ls&&p&&g&&w&&b&&rt(p,document.baseURI)&&rt(w,document.baseURI)&&rt(b,document.baseURI));A(d);const z={canvasFactory:new F({ownerDocument:P,enableHWA:B}),filterFactory:new R({docId:i,ownerDocument:P}),binaryDataFactory:G?null:new O({cMapUrl:p,standardFontDataUrl:w,wasmUrl:b})};u||(u=ci.create({verbosity:d,port:Ke.workerPort}),e._worker=u);const H={docId:i,apiVersion:"6.3.289",data:r,password:a,disableAutoFetch:N,rangeChunkSize:c,docBaseUrl:f,enableXfa:T,evaluatorOptions:{maxImageSize:v,disableFontFace:C,ignoreErrors:y,isOffscreenCanvasSupported:x,isImageDecoderSupported:M,canvasMaxAreaInBytes:k,fontExtraProperties:S,useSystemFonts:j,useWasm:L,useWorkerFetch:G,cMapUrl:p,cMapPacked:g,iccUrl:m,standardFontDataUrl:w,wasmUrl:b,hasGPU:!1}},W={ownerDocument:P,pdfBug:I,styleElement:null,enableHWA:B,loadingParams:{disableAutoFetch:N,enableXfa:T}};return Promise.all([u.promise,$]).then((function([,s]){if(u.destroyed)throw new Error("Worker was destroyed");H.evaluatorOptions.hasGPU=s;const a=u.messageHandler.sendWithPromise("GetDocRequest",H,r?[r.buffer]:null);let d;if(r);else if(l)d=new Le({pdfDataRangeTransport:l,disableRange:E,disableStream:D});else{if(!n)throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");{const s=function(s){return rt(s)?_e:t?Ve:Ge}(n);d=new s({url:n,httpHeaders:o,withCredentials:h,rangeChunkSize:c,disableRange:E,disableStream:D})}}return a.then((t=>{if(u.destroyed)throw new Error("Worker was destroyed");const s=new Bs(i,t,u.port),n=new ui(s,e,d,W,z,U);if(e._transport=n,e.destroyed)throw new Error("Loading aborted");s.send("Ready",null)}))})).catch(e._capability.reject).finally(e._setupCapability.resolve),e}class oi{static#Ri=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+oi.#Ri++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,this._capability.promise.catch((()=>{}));try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._setupCapability.promise,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 hi{#nr=Promise.withResolvers();#_r=null;constructor(t,s,e=!1,i=null){this.length=t,this.initialData=s,this.progressiveDone=e,this.contentDispositionFilename=i}onDataRange(t,s){this.#_r({type:"range",begin:t,chunk:s})}onDataProgressiveRead(t){this.#nr.promise.then((()=>{this.#_r({type:"progressiveRead",chunk:t})}))}onDataProgressiveDone(){this.#nr.promise.then((()=>{this.#_r({type:"progressiveDone"})}))}transportReady(t){this.#_r=t,this.#nr.resolve()}requestDataRange(t,s){v("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class ai{constructor(t,s){this._pdfInfo=t,this._transport=s}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return S(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAttachmentContent(t){return this._transport.getAttachmentContent(t)}getAnnotationsByType(t,s){return this._transport.getAnnotationsByType(t,s)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:s}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(s)}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()}extractPages(t,s=null){return this._transport.extractPages(t,s)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}getSignatures(){return this._transport.getSignatures()}getSignatureData(t){return this._transport.getSignatureData(t)}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class li{#Rr=!1;#Or=null;constructor(t,s,e,i,n=!1){this._pageIndex=t,this._pageInfo=s,this._transport=e,this._stats=n?new nt:null,this._pdfBug=n,this.commonObjs=e.commonObjs,this.objs=new ii,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,this.#Or=i,this.imageCoordinates=null}clone(t){const s=new li(t,this._pageInfo,this._transport,this.#Or,this._pdfBug);return s.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(s),s}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1,this._transport.updatePage(this)}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:s=this.rotate,offsetX:e=0,offsetY:i=0,dontFlip:n=!1}={}){return new V({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:s,offsetX:e,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:s}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,s)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return S(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:s=t.canvas,viewport:e,intent:i="display",annotationMode:n=r.ENABLE,transform:o=null,background:h=null,optionalContentConfigPromise:a=null,annotationCanvasMap:l=null,pageColors:c=null,printAnnotationStorage:u=null,isEditing:d=!1,recordImages:f=!1,recordOperations:p=!1,operationsFilter:g=null}){this._stats?.time("Overall");const m=this._transport.getRenderingIntent(i,n,u,d),{renderingIntent:A,cacheKey:w}=m;this.#Rr=!1,a||=this._transport.getOptionalContentConfig(A);const b=this._intentStates.getOrInsertComputed(w,z);b.streamReaderCancelTimeout&&(clearTimeout(b.streamReaderCancelTimeout),b.streamReaderCancelTimeout=null);const y=!!(4&A);b.displayReadyCapability||(b.displayReadyCapability=Promise.withResolvers(),b.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(m));const v=!(!this._pdfBug||!globalThis.StepperManager?.enabled),x=!!s&&!this.recordedBBoxes&&(p||v),M=!!s&&!this.imageCoordinates&&f,k=t=>{if(b.renderTasks.delete(T),x){const t=T.gfx?.dependencyTracker.take();t&&(T.stepper?.setOperatorBBoxes(t,T.gfx.dependencyTracker.takeDebugMetadata()),p&&(this.recordedBBoxes=t))}M&&!t&&(this.imageCoordinates=T.gfx?.imagesTracker.take()),y&&(this.#Rr=!0),this.#Br(),t?(T.capability.reject(t),this._abortOperatorList({intentState:b,reason:t instanceof Error?t:new Error(t)})):T.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))};let C=null,S=null;(x||M)&&(S=new os(s,b.operatorList.length)),x&&(C=new hs(S,v));const T=new fi({callback:k,params:{canvas:s,canvasContext:t,dependencyTracker:C??S,imagesTracker:M?new ms(s):null,viewport:e,transform:o,background:h},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:b.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!y,pdfBug:this._pdfBug,pageColors:c,enableHWA:this._transport.enableHWA,operationsFilter:g});(b.renderTasks||=new Set).add(T);const P=T.task;return Promise.all([b.displayReadyCapability.promise,a]).then((([t,s])=>{if(this.destroyed)k();else{if(this._stats?.time("Rendering"),!(s.renderingIntent&A))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");T.initializeGraphics({transparency:t,optionalContentConfig:s}),T.operatorListChanged()}})).catch(k),P}getOperatorList({intent:t="display",annotationMode:s=r.ENABLE,printAnnotationStorage:e=null,isEditing:i=!1}={}){const n=this._transport.getRenderingIntent(t,s,e,i,!0),o=this._intentStates.getOrInsertComputed(n.cacheKey,z);let h;return o.opListReadCapability||(h=Object.create(null),h.operatorListChanged=function(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(h))},o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(h),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:s=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#Or.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===s},{highWaterMark:100,size:t=>t.items.length})}async getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>X.textContent(t)));const s=this.streamTextContent(t),e={items:[],styles:Object.create(null),lang:null};for await(const t of s)e.lang??=t.lang,Object.assign(e.styles,t.styles),e.items.push(...t.items);return e}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const s of this._intentStates.values())if(this._abortOperatorList({intentState:s,reason:new Error("Page was destroyed."),force:!0}),!s.opListReadCapability)for(const e of s.renderTasks)t.push(e.completed),e.cancel();return this.objs.clear(),this.#Rr=!1,Promise.all(t)}cleanup(t=!1){this.#Rr=!0;const s=this.#Br();return t&&s&&(this._stats&&=new nt),s}#Br(){if(!this.#Rr||this.destroyed)return!1;for(const{renderTasks:t,operatorList:s}of this._intentStates.values())if(t.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#Rr=!1,!0}_startRenderPage(t,s){const e=this._intentStates.get(s);e&&(this._stats?.timeEnd("Page Request"),e.displayReadyCapability?.resolve(t))}_renderPageChunk(t,s){for(let e=0,i=t.length;e<i;e++)s.operatorList.fnArray.push(t.fnArray[e]),s.operatorList.argsArray.push(t.argsArray[e]);s.operatorList.lastChunk=t.lastChunk,s.operatorList.separateAnnots=t.separateAnnots;for(const t of s.renderTasks)t.operatorListChanged();t.lastChunk&&this.#Br()}_pumpOperatorList({renderingIntent:t,cacheKey:s,annotationStorageSerializable:e,modifiedIds:i}){const{map:n,transfer:r}=e,o=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#Or.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:t,cacheKey:s,annotationStorage:n,modifiedIds:i},void 0,r).getReader(),h=this._intentStates.get(s);h.streamReader=o;const a=()=>{o.read().then((({value:t,done:s})=>{s?h.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,h),a())}),(t=>{if(h.streamReader=null,!this._transport.destroyed){if(h.operatorList){h.operatorList.lastChunk=!0;for(const t of h.renderTasks)t.operatorListChanged();this.#Br()}if(h.displayReadyCapability)h.displayReadyCapability.reject(t);else{if(!h.opListReadCapability)throw t;h.opListReadCapability.reject(t)}}}))};a()}_abortOperatorList({intentState:t,reason:s,force:e=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!e){if(t.renderTasks.size>0)return;if(s instanceof Z){let e=100;return s.extraDelay>0&&s.extraDelay<1e3&&(e+=s.extraDelay),void(t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:s,force:!0})}),e))}}if(t.streamReader.cancel(new F(s.message)).catch((()=>{})),t.streamReader=null,!this._transport.destroyed){for(const[s,e]of this._intentStates)if(e===t){this._intentStates.delete(s);break}this.cleanup()}}}get stats(){return this._stats}}class ci{#nr=Promise.withResolvers();#$r=null;#_n=null;#Lr=null;static#Ur=0;static#jr=!1;static#Gr=new WeakMap;static{t&&(this.#jr=!0,Ke.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,s)=>{const e=URL.parse(t);if(!e?.origin||"null"===e.origin)return!1;const i=new URL(s,e);return e.origin===i.origin},this._createCDNWrapper=t=>URL.createObjectURL(new Blob([`await import("${t}");`],{type:"text/javascript"}))}constructor({name:t=null,port:s=null,verbosity:e=w()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=e,s){if(ci.#Gr.has(s))throw new Error("Cannot use more than one PDFWorker per port.");ci.#Gr.set(s,this),this.#zr(s)}else this.#Hr()}get promise(){return this.#nr.promise}#Wr(){this.#nr.resolve(),this.#$r.send("configure",{verbosity:this.verbosity})}get port(){return this.#_n}get messageHandler(){return this.#$r}#zr(t){this.#_n=t,this.#$r=new Bs("main","worker",t),this.#$r.on("ready",(()=>{})),this.#Wr()}#Hr(){if(ci.#jr||ci.#Vr)return void this.#Xr();let{workerSrc:t}=ci;try{ci._isSameOrigin(window.location,t)||(t=ci._createCDNWrapper(new URL(t,window.location).href));const s=new Worker(t,{type:"module"}),e=new Bs("main","worker",s),i=()=>{n.abort(),e.destroy(),s.terminate(),this.destroyed?this.#nr.reject(new Error("Worker was destroyed")):this.#Xr()},n=new AbortController;s.addEventListener("error",(()=>{this.#Lr||i()}),{signal:n.signal}),e.on("test",(t=>{n.abort(),!this.destroyed&&t?(this.#$r=e,this.#_n=s,this.#Lr=s,this.#Wr()):i()})),e.on("ready",(()=>{if(n.abort(),this.destroyed)i();else try{r()}catch{this.#Xr()}}));const r=()=>{const t=new Uint8Array;e.send("test",t,[t.buffer])};return void r()}catch{b("The worker has been disabled.")}this.#Xr()}#Xr(){ci.#jr||(y("Setting up fake worker."),ci.#jr=!0),ci._setupFakeWorkerGlobal.then((t=>{if(this.destroyed)return void this.#nr.reject(new Error("Worker was destroyed"));const s=new _s;this.#_n=s;const e="fake"+ci.#Ur++,i=new Bs(e+"_worker",e,s);t.setup(i,s),this.#$r=new Bs(e,e+"_worker",s),this.#Wr()})).catch((t=>{this.#nr.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0,this.#Lr?.terminate(),this.#Lr=null,ci.#Gr.delete(this.#_n),this.#_n=null,this.#$r?.destroy(),this.#$r=null}static create(t){const s=this.#Gr.get(t?.port);if(s){if(s._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return s}return new ci(t)}static get workerSrc(){if(Ke.workerSrc)return Ke.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Vr(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return S(this,"_setupFakeWorkerGlobal",(async()=>this.#Vr?this.#Vr:(await import(this.workerSrc)).WorkerMessageHandler)())}}class ui{downloadInfoCapability=Promise.withResolvers();#Yr=null;#Kr=new Map;#qr=null;#Qr=new Map;#Jr=new Map;#Zr=new Map;#to=null;constructor(t,s,e,i,n,r){this.messageHandler=t,this.loadingTask=s,this.#qr=e,this.commonObjs=new ii,this.fontLoader=new bs({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.enableHWA=i.enableHWA,this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.binaryDataFactory=n.binaryDataFactory,this.pagesMapper=r,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(t){const{_pageIndex:s}=t;this.#Qr.set(s,t),this.#Jr.set(s,Promise.resolve(t))}#so(t,s=null){return this.#Kr.getOrInsertComputed(t,(()=>this.messageHandler.sendWithPromise(t,s)))}#Dn({loaded:t,total:s}){this.loadingTask.onProgress?.({loaded:t,total:s,percent:s?W(Math.round(t/s*100),0,100):NaN})}get annotationStorage(){return S(this,"annotationStorage",new Qt)}getRenderingIntent(t,s=r.ENABLE,e=null,i=!1,n=!1){let o=2,h=qt;switch(t){case"any":o=1;break;case"display":break;case"print":o=4;break;default:y(`getRenderingIntent - invalid intent: ${t}`)}const a=4&o&&e instanceof Jt?e:this.annotationStorage;switch(s){case r.DISABLE:o+=64;break;case r.ENABLE:break;case r.ENABLE_FORMS:o+=16;break;case r.ENABLE_STORAGE:o+=32,h=a.serializable;break;default:y(`getRenderingIntent - invalid annotationMode: ${s}`)}i&&(o+=128),n&&(o+=256);const{ids:l,hash:c}=a.modifiedIds;return{renderingIntent:o,cacheKey:[o,h.hash,c].join("_"),annotationStorageSerializable:h,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#to?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#Qr.values())t.push(s._destroy());this.#Qr.clear(),this.#Jr.clear(),this.#Zr.clear(),Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();const s=this.messageHandler.sendWithPromise("Terminate",null);return t.push(s),Promise.all(t).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#Kr.clear(),this.filterFactory.destroy(),ni.cleanup(),this.#qr?.cancelAllRequests(new F("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:s}=this;t.on("GetReader",((t,s)=>{x(this.#qr,"GetReader - no `BasePDFStream` instance available."),this.#Yr=this.#qr.getFullReader(),this.#Yr.onProgress=t=>this.#Dn(t),s.onPull=()=>{this.#Yr.read().then((function({value:t,done:e}){e?s.close():(x(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),s.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{s.error(t)}))},s.onCancel=t=>{this.#Yr.cancel(t),s.ready.catch((t=>{if(!this.destroyed)throw t}))}})),t.on("ReaderHeadersReady",(async()=>{await this.#Yr.headersReady;const{isStreamingSupported:t,isRangeSupported:s,contentLength:e}=this.#Yr;return t&&s&&(this.#Yr.onProgress=null),{isStreamingSupported:t,isRangeSupported:s,contentLength:e}})),t.on("GetRangeReader",((t,s)=>{x(this.#qr,"GetRangeReader - no `BasePDFStream` instance available.");const e=this.#qr.getRangeReader(t.begin,t.end);e?(s.onPull=()=>{e.read().then((function({value:t,done:e}){e?s.close():(x(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),s.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{s.error(t)}))},s.onCancel=t=>{e.cancel(t),s.ready.catch((t=>{if(!this.destroyed)throw t}))}):s.close()})),t.on("GetDoc",(({pdfInfo:t})=>{this.pagesMapper.pagesNumber=t.numPages,this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,s._capability.resolve(new ai(t,this))})),t.on("DocException",(t=>{s._capability.reject(Os(t))})),t.on("PasswordRequest",(t=>{this.#to=Promise.withResolvers();try{if(!s.onPassword)throw Os(t);s.onPassword((t=>{t instanceof Error?this.#to.reject(t):this.#to.resolve({password:t})}),t.code)}catch(t){this.#to.reject(t)}return this.#to.promise})),t.on("DataLoaded",(t=>{this.#Dn({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)})),t.on("StartRenderPage",(t=>{this.destroyed||this.#Qr.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)})),t.on("commonobj",(([s,e,i])=>{if(this.destroyed)return null;if(this.commonObjs.has(s))return null;switch(e){case"Font":if("error"in i){const t=i.error;y(`Error during font loading: ${t}`),this.commonObjs.resolve(s,t);break}const n=new Ps(i),r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,s)=>globalThis.FontInspector.fontAdded(t,s):null,o=new ys(n,r,i.charProcOperatorList,i.extra);this.fontLoader.bind(o).catch((()=>t.sendWithPromise("FontFallback",{id:s}))).finally((()=>{o.fontExtraProperties||o.clearData(),this.commonObjs.resolve(s,o)}));break;case"CopyLocalImage":const{imageRef:h}=i;x(h,"The imageRef must be defined.");for(const t of this.#Qr.values())for(const[,e]of t.objs){if(e?.ref!==h)continue;if(!e.dataLen)return null;const t=structuredClone(e);return this.commonObjs.resolve(s,t),e.dataLen}break;case"FontPath":this.commonObjs.resolve(s,new Ds(i));break;case"Image":this.commonObjs.resolve(s,i);break;case"Pattern":const a=new Es(i);this.commonObjs.resolve(s,a.getIR());break;default:throw new Error(`Got unknown common object type ${e}`)}return null})),t.on("obj",(([t,s,e,i])=>{if(this.destroyed)return;const n=this.#Qr.get(s);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(e){case"Image":case"Pattern":n.objs.resolve(t,i);break;default:throw new Error(`Got unknown object type ${e}`)}else i?.bitmap?.close()})),t.on("DocProgress",(t=>{this.destroyed||this.#Dn(t)})),t.on("FetchBinaryData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&y("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:s}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this.#Yr?.filename??null},s).finally((()=>{this.annotationStorage.resetModified()}))}extractPages(t,s=null){const e={pageInfos:t};let i;const n=globalThis.ImageBitmap;if("function"==typeof n){const s=Array.isArray(t)?t:[t];for(const t of s)t?.image instanceof n&&(i||=[]).push(t.image)}if(this.annotationStorage.size>0){const t=this.annotationStorage.serializable;let{map:n}=t;t.transfer?.length&&(i?i.push(...t.transfer):i=t.transfer);const r=this.pagesMapper.getMapping();if(r){const t=new Map;for(const[e,i]of n){if(void 0!==i?.pageIndex&&i.pageIndex>=0&&i.pageIndex<r.length){const n=s?.[i.pageIndex]??0,o=r[i.pageIndex]-1;if(o!==i.pageIndex||0!==n){t.set(e,{...i,pageIndex:o,copyLevel:n});continue}}t.set(e,i)}n=t}e.annotationStorage=n}return this.messageHandler.sendWithPromise("ExtractPages",e,i).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const s=t-1,e=this.pagesMapper.getPageId(t)-1,i=this.#Jr.get(s);if(i)return i;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#Zr.set(t.refStr,e);const i=new li(s,t,this,this.pagesMapper,this._params.pdfBug);return this.#Qr.set(s,i),i}));return this.#Jr.set(s,n),n}async getPageIndex(t){if(!Is(t))throw new Error("Invalid pageIndex request.");const s=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}),e=this.pagesMapper.getPageNumber(s+1);if(0===e)throw new Error("GetPageIndex: page has been removed.");return e-1}getAnnotations(t,s){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(t+1)-1,intent:s})}getFieldObjects(){return this.#so("GetFieldObjects")}getSignatures(){return this.#so("GetSignatures")}getSignatureData(t){return this.messageHandler.sendWithPromise("GetSignatureData",t)}hasJSActions(){return this.#so("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)}getAttachmentContent(t){return this.messageHandler.sendWithPromise("GetAttachmentContent",t)}getAnnotationsByType(t,s){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:s})}getDocJSActions(){return this.#so("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#so("GetOptionalContentConfig").then((s=>new Ze(s,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata";return this.#Kr.getOrInsertComputed(t,(()=>this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new qe(t[1]):null,contentDispositionFilename:this.#Yr?.filename??null,contentLength:this.#Yr?.contentLength??null,hasStructTree:t[2]})))))}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.#Qr.values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#Kr.clear(),this.filterFactory.destroy(!0),ni.cleanup()}}cachedPageNumber(t){if(!Is(t))return null;const s=this.#Zr.get(0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`);if(s>=0){const t=this.pagesMapper.getPageNumber(s+1);if(0!==t)return t}return null}}class di{_internalRenderTask=null;onContinue=null;onError=null;constructor(t){this._internalRenderTask=t}get promise(){return this._internalRenderTask.capability.promise}cancel(t=0){this._internalRenderTask.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this._internalRenderTask.operatorList;if(!t)return!1;const{annotationCanvasMap:s}=this._internalRenderTask;return t.form||t.canvas&&s?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}class fi{#eo=null;static#io=new WeakSet;constructor({callback:t,params:s,objs:e,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:o,canvasFactory:h,filterFactory:a,useRequestAnimationFrame:l=!1,pdfBug:c=!1,pageColors:u=null,enableHWA:d=!1,operationsFilter:f=null}){this.callback=t,this.params=s,this.objs=e,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=o,this.canvasFactory=h,this.filterFactory=a,this._pdfBug=c,this.pageColors=u,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===l&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new di(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=s.canvas,this._canvasContext=s.canvas?null:s.canvasContext,this._enableHWA=d,this._dependencyTracker=s.dependencyTracker,this._imagesTracker=s.imagesTracker,this._operationsFilter=f}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:s}){if(this.cancelled)return;if(this._canvas){if(fi.#io.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");fi.#io.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:e,transform:i,background:n,dependencyTracker:r,imagesTracker:o}=this.params,h=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new ve(h,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:s},this.annotationCanvasMap,this.pageColors,r,o),this.gfx.beginDrawing({transform:i,viewport:e,transparency:t,background:n}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,s=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#eo&&(window.cancelAnimationFrame(this.#eo),this.#eo=null),fi.#io.delete(this._canvas),t||=new Z(`Rendering cancelled, page ${this._pageIndex+1}`,s),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.#eo=window.requestAnimationFrame((()=>{this.#eo=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(),fi.#io.delete(this._canvas),this.callback())))}}const pi="6.3.289",gi="1c8020a7d";class mi{#no=null;#ro=null;#oo;#ho=null;#ao=!1;#lo=!1;#h=null;#co;#uo=null;#b=null;static#do=null;static get _keyboardManager(){return S(this,"_keyboardManager",new Rt([[["Escape"],mi.prototype._hideDropdownFromKeyboard],[["Space"],mi.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight"],mi.prototype._moveToNext],[["ArrowUp","ArrowLeft"],mi.prototype._moveToPrevious],[["Home"],mi.prototype._moveToBeginning],[["End"],mi.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:s=null}){t?(this.#lo=!1,this.#h=t):this.#lo=!0,this.#b=t?._uiManager||s,this.#co=this.#b._eventBus,this.#oo=t?.color?.toUpperCase()||this.#b?.highlightColors.values().next().value||"#FFFF98",mi.#do||=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.#no=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.ariaHasPopup="true",this.#h&&(t.ariaControls=`${this.#h.id}_colorpicker_dropdown`);const s=this.#b._signal;t.addEventListener("click",this.#fo.bind(this),{signal:s}),t.addEventListener("keydown",this.#po.bind(this),{signal:s});const e=this.#ro=document.createElement("span");return e.className="swatch",e.ariaHidden="true",e.style.backgroundColor=this.#oo,t.append(e),t}renderMainDropdown(){const t=this.#ho=this.#go();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#go(){const t=document.createElement("div"),s=this.#b._signal;t.addEventListener("contextmenu",ot,{signal:s}),t.className="dropdown",t.role="listbox",t.ariaMultiSelectable="false",t.ariaOrientation="vertical",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#h&&(t.id=`${this.#h.id}_colorpicker_dropdown`);for(const[e,i]of this.#b.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=e,n.setAttribute("data-l10n-id",mi.#do[e]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.ariaSelected=i===this.#oo,n.addEventListener("click",this.#mo.bind(this,i),{signal:s}),t.append(n)}return t.addEventListener("keydown",this.#po.bind(this),{signal:s}),t}#mo(t,s){s.stopPropagation(),this.#co.dispatch("switchannotationeditorparams",{source:this,type:l.HIGHLIGHT_COLOR,value:t}),this.update(t)}_colorSelectFromKeyboard(t){if(t.target===this.#no)return void this.#fo(t);const s=t.target.getAttribute("data-color");s&&this.#mo(s,t)}_moveToNext(t){this.#Ao?t.target!==this.#no?t.target.nextSibling?.focus():this.#ho.firstElementChild?.focus():this.#fo(t)}_moveToPrevious(t){t.target!==this.#ho?.firstElementChild&&t.target!==this.#no?(this.#Ao||this.#fo(t),t.target.previousSibling?.focus()):this.#Ao&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Ao?this.#ho.firstElementChild?.focus():this.#fo(t)}_moveToEnd(t){this.#Ao?this.#ho.lastElementChild?.focus():this.#fo(t)}#po(t){mi._keyboardManager.exec(this,t)}#fo(t){if(this.#Ao)return void this.hideDropdown();if(this.#ao=0===t.detail,this.#uo||(this.#uo=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#b.combinedSignal(this.#uo)})),this.#no.ariaExpanded="true",this.#ho)return void this.#ho.classList.remove("hidden");const s=this.#ho=this.#go();this.#no.append(s)}#p(t){this.#ho?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#ho?.classList.add("hidden"),this.#no.ariaExpanded="false",this.#uo?.abort(),this.#uo=null}get#Ao(){return this.#ho&&!this.#ho.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#lo||(this.#Ao?(this.hideDropdown(),this.#no.focus({preventScroll:!0,focusVisible:this.#ao})):this.#h?.unselect())}update(t){if(this.#ro&&(this.#ro.style.backgroundColor=t),!this.#ho)return;const s=this.#b.highlightColors.values();for(const e of this.#ho.children)e.ariaSelected=s.next().value===t.toUpperCase()}destroy(){this.#no?.remove(),this.#no=null,this.#ro=null,this.#ho?.remove(),this.#ho=null}}class Ai{#wo=null;#bo=!1;#h=null;#b=null;static#do=null;constructor(t){this.#h=t,this.#b=t._uiManager,Ai.#do||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#wo)return this.#wo;const{editorType:t,colorType:s,colorAndOpacityType:e,opacityType:i,color:n,opacity:r}=this.#h,o=this.#bo=R.isAlphaColorInputSupported&&void 0!==i,h=this.#wo=document.createElement("input");if(h.type="color",o){h.setAttribute("alpha","");const t=O.hexNums[Math.round(255*(r??1))];h.value=(n||"#000000")+t}else h.value=n||"#000000";return h.className="basicColorPicker",h.tabIndex=0,h.setAttribute("data-l10n-id",Ai.#do[t]),h.addEventListener("input",(()=>{if(o){const t=lt(h.value);if(!t)return;const[n,r,o,a]=t,l=O.makeHexColor(n,r,o);void 0!==e?this.#b.updateParams(e,{color:l,opacity:a}):(this.#b.updateParams(s,l),this.#b.updateParams(i,a))}else this.#b.updateParams(s,h.value)}),{signal:this.#b._signal}),h}update(t){if(this.#wo)if(this.#bo){const s=O.hexNums[Math.round(255*this.#h.opacity)];this.#wo.value=t+s}else this.#wo.value=t}updateOpacity(t){if(!this.#wo||!this.#bo)return;const s=O.hexNums[Math.round(255*t)];this.#wo.value=this.#h.color+s}destroy(){this.#wo?.remove(),this.#wo=null}hideDropdown(){}}function wi(t){return Math.floor(255*W(t,0,1)).toString(16).padStart(2,"0")}function bi(t){return 255*W(t,0,1)}class yi{static CMYK_G([t,s,e,i]){return["G",1-Math.min(1,.3*t+.59*e+.11*s+i)]}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=bi(t),t,t]}static G_HTML([t]){const s=wi(t);return`#${s}${s}${s}`}static RGB_G([t,s,e]){return["G",.3*t+.59*s+.11*e]}static RGB_rgb(t){return t.map(bi)}static RGB_HTML(t){return`#${t.map(wi).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,s,e,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,e+i),1-Math.min(1,s+i)]}static CMYK_rgb([t,s,e,i]){return[bi(1-Math.min(1,t+i)),bi(1-Math.min(1,e+i)),bi(1-Math.min(1,s+i))]}static CMYK_HTML(t){const s=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(s)}static RGB_CMYK([t,s,e]){const i=1-t,n=1-s,r=1-e;return["CMYK",i,n,r,Math.min(i,n,r)]}}class vi{create(t,s,e=!1){if(t<=0||s<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),e||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${s}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${s}`),i}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){v("Abstract method `_createSVG` called.")}}class xi extends vi{_createSVG(t){return document.createElementNS(n,t)}}const Mi=new WeakSet,ki=60*(new Date).getTimezoneOffset()*1e3;class Ci{static create(t){switch(t.data.annotationType){case d.LINK:return new Pi(t);case d.TEXT:return new Ei(t);case d.WIDGET:switch(t.data.fieldType){case"Tx":return new Ni(t);case"Btn":return t.data.radioButton?new _i(t):t.data.checkBox?new Fi(t):new Ri(t);case"Ch":return new Oi(t);case"Sig":return new Ii(t)}return new Di(t);case d.POPUP:return new Bi(t);case d.FREETEXT:return new Li(t);case d.LINE:return new Ui(t);case d.SQUARE:return new ji(t);case d.CIRCLE:return new Gi(t);case d.POLYLINE:return new zi(t);case d.CARET:return new Wi(t);case d.INK:return new Vi(t);case d.POLYGON:return new Hi(t);case d.HIGHLIGHT:return new Xi(t);case d.UNDERLINE:return new Yi(t);case d.SQUIGGLY:return new Ki(t);case d.STRIKEOUT:return new qi(t);case d.STAMP:return new Qi(t);case d.FILEATTACHMENT:return new Ji(t);case d.RICHMEDIA:case d.SCREEN:case d.SOUND:return new Zi(t);default:return new Si(t)}}}class Si{#yo=null;#vo=!1;#xo=null;constructor(t,{isRenderable:s=!1,ignoreBorder:e=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=s,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,this.hasOwnCommentButton=!1,s&&(this.contentElement=this.container=this._createContainer(e)),i&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:s}){return!(!t?.str&&!s?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Si._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,s=this.annotationStorage?.getEditor(t.id);return s?s.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:s,inkLists:e,rect:i}=this.data;let n=-1/0,r=-1/0;if(s?.length>=8){for(let t=0;t<s.length;t+=8)s[t+1]>r?(r=s[t+1],n=s[t+2]):s[t+1]===r&&(n=Math.max(n,s[t+2]));return[n,r]}if(e?.length>=1){for(const t of e)for(let s=0,e=t.length;s<e;s+=2)t[s+1]>r?(r=t[s+1],n=t[s]):t[s+1]===r&&(n=Math.max(n,t[s]));if(n!==1/0)return[n,r]}return i?[i[2],i[3]]:null}_normalizePoint(t){const{page:{view:s},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:n,pageY:r}}}=this.parent;return t[1]=s[3]-t[1]+s[1],t[0]=100*(t[0]-n)/e,t[1]=100*(t[1]-r)/i,t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${h}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:s}=this,e={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(s.id,{popup:e})||this.annotationStorage.setValue(`${h}${s.id}`,{id:s.id,annotationType:s.annotationType,page:this.parent.page,popup:e,popupRef:s.popupRef,modificationDate:new Date}),t||this.removePopup()}removePopup(){(this.#xo?.popup||this.popup)?.remove(),this.#xo=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#yo||={rect:this.data.rect.slice(0)});const{rect:s,popup:e}=t;s&&this.#Mo(s);let i=this.#xo?.popup||this.popup;!i&&e?.text&&(this._createPopup(e),i=this.#xo.popup),i&&(i.updateEdited(t),e?.deleted&&(i.remove(),this.#xo=null,this.popup=null))}resetEdited(){this.#yo&&(this.#Mo(this.#yo.rect),this.#xo?.popup.resetEdited(),this.#yo=null)}#Mo(t){const{container:{style:s},data:{rect:e,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:o,pageY:h}}}}=this;e?.splice(0,4,...t),s.left=100*(t[0]-o)/n+"%",s.top=100*(r-t[3]+h)/r+"%",0===i?(s.width=100*(t[2]-t[0])/n+"%",s.height=100*(t[3]-t[1])/r+"%"):this.setRotation(i)}_createContainer(t){const{data:s,parent:{page:e,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",s.id),this instanceof Di||this instanceof Pi||this instanceof Zi||(n.tabIndex=0);const{style:r}=n;if(r.zIndex=this.parent.zIndex,this.parent.zIndex+=2,s.alternativeText&&(n.title=s.alternativeText),s.noRotate&&n.classList.add("norotate"),!s.rect||this instanceof Bi){const{rotation:t}=s;return s.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:o,height:h}=this;if(!t&&s.borderStyle.width>0){r.borderWidth=`${s.borderStyle.width}px`;const t=s.borderStyle.horizontalCornerRadius,e=s.borderStyle.verticalCornerRadius;switch((t>0||e>0)&&(r.borderRadius=`calc(${t}px * var(--total-scale-factor)) / calc(${e}px * var(--total-scale-factor))`),s.borderStyle.style){case 1:r.borderStyle="solid";break;case 2:r.borderStyle="dashed";break;case 3:y("Unimplemented border style: beveled");break;case 4:y("Unimplemented border style: inset");break;case 5:r.borderBottomStyle="solid"}const i=s.borderColor||null;i?(this.#vo=!0,r.borderColor=O.makeHexColor(...i)):r.borderWidth=0}const a=O.normalizeRect([s.rect[0],e.view[3]-s.rect[1]+e.view[1],s.rect[2],e.view[3]-s.rect[3]+e.view[1]]),{pageWidth:l,pageHeight:c,pageX:u,pageY:d}=i.rawDims;r.left=100*(a[0]-u)/l+"%",r.top=100*(a[1]-d)/c+"%";const{rotation:f}=s;return s.hasOwnCanvas||0===f?(r.width=100*o/l+"%",r.height=100*h/c+"%"):this.setRotation(f,n),n}setRotation(t,s=this.container){if(!this.data.rect)return;const{pageWidth:e,pageHeight:i}=this.parent.viewport.rawDims;let{width:n,height:r}=this;t%180!=0&&([n,r]=[r,n]),s.style.width=100*n/e+"%",s.style.height=100*r/i+"%",s.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,s,e)=>{const i=e.detail[t],n=i[0],r=i.slice(1);e.target.style[s]=yi[`${n}_HTML`](r),this.annotationStorage.setValue(this.data.id,{[s]:yi[`${n}_rgb`](r)})};return S(this,"_commonActions",{display:t=>{const{display:s}=t.detail,e=s%2==1;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:e,noPrint:1===s||2===s})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:s}=t.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},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:s=>{t("bgColor","backgroundColor",s)},fillColor:s=>{t("fillColor","backgroundColor",s)},fgColor:s=>{t("fgColor","color",s)},textColor:s=>{t("textColor","color",s)},borderColor:s=>{t("borderColor","borderColor",s)},strokeColor:s=>{t("strokeColor","borderColor",s)},rotation:t=>{const s=t.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,s){const e=this._commonActions;for(const i of Object.keys(s.detail)){const n=t[i]||e[i];n?.(s)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const s=this.annotationStorage.getRawValue(this.data.id);if(!s)return;const e=this._commonActions;for(const[i,n]of Object.entries(s)){const r=e[i];r&&(r({detail:{[i]:n},target:t}),delete s[i])}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[s,e,i,r]=this.data.rect.map(Math.fround);if(8===t.length){const[n,o,h,a]=t.subarray(2,6);if(i===n&&r===o&&s===h&&e===a)return}const{style:o}=this.container;let h;if(this.#vo){const{borderColor:t,borderWidth:s}=o;o.borderWidth=0,h=["url('data:image/svg+xml;utf8,",`<svg xmlns="${n}" preserveAspectRatio="none" viewBox="0 0 1 1">`,`<g fill="transparent" stroke="${t}" stroke-width="${s}">`],this.container.classList.add("hasBorder")}const a=i-s,l=r-e,{svgFactory:c}=this,u=c.createElement("svg");u.classList.add("quadrilateralsContainer"),u.setAttribute("width",0),u.setAttribute("height",0),u.role="none";const d=c.createElement("defs");u.append(d);const f=c.createElement("clipPath"),p=`clippath_${this.data.id}`;f.setAttribute("id",p),f.setAttribute("clipPathUnits","objectBoundingBox"),d.append(f);for(let e=2,i=t.length;e<i;e+=8){const i=t[e],n=t[e+1],o=t[e+2],u=t[e+3],d=c.createElement("rect"),p=(o-s)/a,g=(r-n)/l,m=(i-o)/a,A=(n-u)/l;d.setAttribute("x",p),d.setAttribute("y",g),d.setAttribute("width",m),d.setAttribute("height",A),f.append(d),h?.push(`<rect vector-effect="non-scaling-stroke" x="${p}" y="${g}" width="${m}" height="${A}"/>`)}this.#vo&&(h.push("</g></svg>')"),o.backgroundImage=h.join("")),this.container.append(u),this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:s}=this;let e,i;t?(e={str:t.text},i=t.date):(e=s.contentsObj,i=s.modificationDate),this.#xo=new Bi({data:{color:s.color,titleObj:s.titleObj,modificationDate:i,contentsObj:e,richText:s.richText,parentRect:s.rect,borderStyle:0,id:`popup_${s.id}`,rotation:s.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#xo||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#xo}render(){v("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,s=null){const e=[];if(this._fieldObjects){const i=this._fieldObjects.get(t)||[];for(const{page:t,id:n,exportValues:r}of i){if(-1===t)continue;if(n===s)continue;const i="string"==typeof r?r:null,o=document.querySelector(`[data-element-id="${n}"]`);!o||Mi.has(o)?e.push({id:n,exportValue:i,domElement:o}):y(`_getElementsByName - element not allowed: ${n}`)}return e}for(const i of document.getElementsByName(t)){const{exportValue:t}=i,n=i.getAttribute("data-element-id");n!==s&&Mi.has(i)&&e.push({id:n,exportValue:t,domElement:i})}return e}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 s of t)s.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:s}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:s,mustEnterInEditMode:!0})}))}updateOC(t){this.data.oc&&t&&(t.isVisible(this.data.oc)?this.show():this.hide())}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}_setBackgroundColor(t){const s=this.data.backgroundColor||null;t.style.backgroundColor=null===s?"transparent":O.makeHexColor(...s)}}class Ti extends Si{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)}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.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}}class Pi extends Si{constructor(t,s=null){super(t,{isRenderable:!0,ignoreBorder:!!s?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:s}=this,e=document.createElement("a");e.setAttribute("data-element-id",t.id);let i=!1;return t.url?(s.addLinkAttributes(e,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(e,t.action,t.overlaidText),i=!0):t.attachment?(this.#ko(e,t.attachmentId,t.attachment,t.overlaidText,t.attachmentDest),i=!0):t.setOCGState?(this.#Co(e,t.setOCGState,t.overlaidText),i=!0):t.dest?(this._bindLink(e,t.dest,t.overlaidText),i=!0):(t.actions&&(t.actions.has("Action")||t.actions.has("Mouse Up")||t.actions.has("Mouse Down"))&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(e,t),i=!0),t.resetForm?(this._bindResetFormAction(e,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(e,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&(this.contentElement=e,this.container.append(e)),this.container}#So(){this.container.setAttribute("data-internal-link","")}_bindLink(t,s,e=""){t.href=this.linkService.getDestinationHash(s),t.onclick=()=>(s&&this.linkService.goToDestination(s),!1),(s||""===s)&&this.#So(),e&&(t.title=e)}_bindNamedAction(t,s,e=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(s),!1),e&&(t.title=e),this.#So()}#ko(t,s,e,i="",n=null){t.href=this.linkService.getAnchorUrl(""),e.description?t.title=e.description:i&&(t.title=i);const r=async()=>{const t=await this.linkService.getAttachmentContent(s);t&&this.downloadManager?.openOrDownloadData(t,e.filename,n)};t.onclick=()=>(r(),!1),this.#So()}#Co(t,s,e=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(s),!1),e&&(t.title=e),this.#So()}_bindJSAction(t,{actions:s,id:e,overlaidText:i}){t.href=this.linkService.getAnchorUrl("");const n=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of s.keys()){const s=n.get(i);s&&(t[s]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:i}}),!1))}i&&(t.title=i),t.onclick||=()=>!1,this.#So()}_bindResetFormAction(t,s){const e=t.onclick;if(e||(t.href=this.linkService.getAnchorUrl("")),this.#So(),!this._fieldObjects)return y('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(e||(t.onclick=()=>!1));t.onclick=()=>{e?.();const{fields:t,refs:i,include:n}=s,r=[];if(0!==t.length||0!==i.length){const s=new Set(i);for(const e of t){const t=this._fieldObjects.get(e)||[];for(const{id:e}of t)s.add(e)}for(const t of this._fieldObjects.values())for(const e of t)s.has(e.id)===n&&r.push(e)}else for(const t of this._fieldObjects.values())r.push(...t);const o=this.annotationStorage,h=[];for(const t of r){const{id:s}=t;switch(h.push(s),t.type){case"text":case"combobox":case"listbox":o.setValue(s,{value:t.defaultValue||""});break;case"checkbox":case"radiobutton":o.setValue(s,{value:t.defaultValue===t.exportValues});break;default:continue}const e=document.querySelector(`[data-element-id="${s}"]`);e&&(Mi.has(e)?e.dispatchEvent(new Event("resetform")):y(`_bindResetFormAction - element not allowed: ${s}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:h,name:"ResetForm"}}),!1}}}class Ei extends Si{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.hasOwnCommentButton=!0,this._createPopup()),this.container.append(t),this.container}}class Di extends Si{render(){return this.container}_getKeyModifier(t){return R.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,s,e,i,n){e.includes("mouse")?t.addEventListener(e,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(e,(t=>{if("blur"===e){if(!s.focused||!t.relatedTarget)return;s.focused=!1}else if("focus"===e){if(s.focused)return;s.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t)}})}))}_setEventListeners(t,s,e,i){const{actions:n}=this.data;for(const[r,o]of e)("Action"===o||n?.has(o))&&("Focus"!==o&&"Blur"!==o||(s||={focused:!1}),this._setEventListener(t,s,r,o,i),"Focus"!==o||n?.has("Blur")?"Blur"!==o||n?.has("Focus")||this._setEventListener(t,s,"focus","Focus",null):this._setEventListener(t,s,"blur","Blur",null))}_setTextStyle(t){const{fontColor:s}=this.data.defaultAppearanceData,e=this.data.defaultAppearanceData.fontSize||9,i=t.style;let n;const r=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),s=Math.round(t/(1.35*e))||1;n=Math.min(e,r(t/s/1.35))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);n=Math.min(e,r(t/1.35))}i.fontSize=`calc(${n}px * var(--total-scale-factor))`,i.color=O.makeHexColor(...s),null===this.data.textAlignment||this.data.comb||(i.textAlign=["left","center","right"][this.data.textAlignment])}_setRequired(t,s){s?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",s)}}class Ni extends Di{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,s,e,i){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[s]=e),n.setValue(r.id,{[i]:e})}render(){const t=this.annotationStorage,s=this.data.id;this.container.classList.add("textWidgetAnnotation");let e=null;if(this.renderForms){const i=t.getValue(s,{value:this.data.fieldValue});let n=i.value||"";const r=t.getValue(s,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let o=i.formattedValue||this.data.textContent?.join("\n")||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,""));const h={userValue:n,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(e=document.createElement("textarea"),e.textContent=o??n,this.data.doNotScroll&&(e.style.overflowY="hidden")):(e=document.createElement("input"),e.type=this.data.password?"password":"text",e.setAttribute("value",o??n),this.data.doNotScroll&&(e.style.overflowX="hidden")),this.data.hasOwnCanvas&&(this.container.classList.add("hasOwnCanvas"),t.has(s)&&this.container.classList.add("sandboxModified")),Mi.add(e),this.contentElement=e,e.setAttribute("data-element-id",s),e.disabled=this.data.readOnly,e.name=this.data.fieldName,e.tabIndex=0;const{datetimeFormat:a,datetimeType:l,timeStep:c}=this.data,u=!!l&&this.enableScripting;a&&(e.title=a),this._setRequired(e,this.data.required),r&&(e.maxLength=r),e.addEventListener("input",(i=>{t.setValue(s,{value:i.target.value}),this.setPropertyOnSiblings(e,"value",i.target.value,"value"),h.formattedValue=null})),e.addEventListener("resetform",(()=>{e.value=h.userValue=this.data.defaultFieldValue??"",h.formattedValue=null}));let d=t=>{const{formattedValue:s}=h;null!=s&&(t.target.value=s),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){e.addEventListener("focus",(t=>{if(h.focused)return;const{target:s}=t;if(u&&(s.type=l,c&&(s.step=c)),h.userValue){const t=h.userValue;if(u)if("time"===l){const e=new Date(t),i=[e.getHours(),e.getMinutes(),e.getSeconds()];s.value=i.map((t=>t.toString().padStart(2,"0"))).join(":")}else s.value=new Date(t-ki).toISOString().split("date"===l?"T":".",1)[0];else s.value=t}h.lastCommittedValue=s.value,h.commitKey=1,this.data.actions?.has("Focus")||(h.focused=!0)})),e.addEventListener("updatefromsandbox",(e=>{this.container.classList.add("sandboxModified"),this._dispatchEventFromSandbox({value(e){h.userValue=e.detail.value??"",u||t.setValue(s,{value:h.userValue.toString()}),e.target.value=h.userValue},formattedValue(e){const{formattedValue:i}=e.detail;h.formattedValue=i,null!=i&&e.target!==document.activeElement&&(e.target.value=i);const n={formattedValue:i};u&&(n.value=i),t.setValue(s,n)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:e=>{const{charLimit:i}=e.detail,{target:n}=e;if(0===i)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",i);let r=h.userValue;!r||r.length<=i||(r=r.slice(0,i),n.value=h.userValue=r,t.setValue(s,{value:r}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:s,name:"Keystroke",value:r,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}}))}},e)})),e.addEventListener("keydown",(t=>{h.commitKey=1;let e=-1;if("Escape"===t.key?e=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(h.commitKey=3):e=2,-1===e)return;const{value:i}=t.target;h.lastCommittedValue!==i&&(h.lastCommittedValue=i,h.userValue=i,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:s,name:"Keystroke",value:i,willCommit:!0,commitKey:e,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))}));const i=d;d=null,e.addEventListener("blur",(t=>{if(!h.focused||!t.relatedTarget)return;this.data.actions?.has("Blur")||(h.focused=!1);const{target:e}=t;let{value:n}=e;if(u){if(n&&"time"===l){const t=n.split(":").map((t=>parseInt(t,10)));n=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf(),e.step=""}else n.includes("T")||(n=`${n}T00:00`),n=new Date(n).valueOf();e.type="text"}h.userValue=n,h.lastCommittedValue!==n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:s,name:"Keystroke",value:n,willCommit:!0,commitKey:h.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),i(t)})),this.data.actions?.has("Keystroke")&&e.addEventListener("beforeinput",(t=>{h.lastCommittedValue=null;const{data:e,target:i}=t,{value:n,selectionStart:r,selectionEnd:o}=i;let a=r,l=o;switch(t.inputType){case"deleteWordBackward":{const t=/\w/;for(;a>0&&!t.test(n[a-1]);)a--;for(;a>0&&t.test(n[a-1]);)a--;break}case"deleteWordForward":{const t=n.substring(r).match(/^\W*\w*/);t&&(l+=t[0].length);break}case"deleteContentBackward":r===o&&(a-=1);break;case"deleteContentForward":r===o&&(l+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:s,name:"Keystroke",value:n,change:e||"",willCommit:!1,selStart:a,selEnd:l}})})),this._setEventListeners(e,h,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}if(d&&e.addEventListener("blur",d),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/r;e.classList.add("comb"),e.style.setProperty("--comb-width",`calc(${t}px * var(--total-scale-factor))`);const s=this.data.textAlignment;if(1===s||2===s){const t=()=>{const t=r-e.value.length;e.style.setProperty("--comb-offset",`${1===s?t>>1:t}`)};t();for(const s of["input","blur","resetform","updatefromsandbox"])e.addEventListener(s,t)}}}else e=document.createElement("div"),e.textContent=this.data.fieldValue,e.style.verticalAlign="middle",e.style.display="table-cell",this.data.hasOwnCanvas&&(e.hidden=!0);return this._setTextStyle(e),this._setBackgroundColor(e),this._setDefaultPropertiesFromJS(e),this.container.append(e),this.container}}class Ii extends Di{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Fi extends Di{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,s=this.data,e=s.id;let i=t.getValue(e,{value:s.exportValue===s.fieldValue}).value;"string"==typeof i&&(i="Off"!==i,t.setValue(e,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return Mi.add(n),n.setAttribute("data-element-id",e),n.disabled=s.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=s.fieldName,i&&n.setAttribute("checked",!0),n.setAttribute("exportValue",s.exportValue),n.tabIndex=0,n.addEventListener("change",(i=>{const{name:n,checked:r}=i.target;for(const i of this._getElementsByName(n,e)){const e=r&&i.exportValue===s.exportValue;i.domElement&&(i.domElement.checked=e),t.setValue(i.id,{value:e})}t.setValue(e,{value:r})})),n.addEventListener("resetform",(t=>{t.target.checked=(s.defaultFieldValue||"Off")===s.exportValue})),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",(s=>{this._dispatchEventFromSandbox({value(s){s.target.checked="Off"!==s.detail.value,t.setValue(e,{value:s.target.checked})}},s)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class _i extends Di{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,s=this.data,e=s.id;let i=t.getValue(e,{value:null!==s.buttonValue&&s.fieldValue===s.buttonValue}).value;if("string"==typeof i&&(i=i!==s.buttonValue,t.setValue(e,{value:i})),i)for(const i of this._getElementsByName(s.fieldName,e))t.setValue(i.id,{value:!1});const n=document.createElement("input");if(Mi.add(n),n.setAttribute("data-element-id",e),n.disabled=s.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=s.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=0,n.addEventListener("change",(s=>{const{name:i,checked:n}=s.target;for(const s of this._getElementsByName(i,e))t.setValue(s.id,{value:!1});t.setValue(e,{value:n})})),n.addEventListener("resetform",(t=>{const e=s.defaultFieldValue;t.target.checked=null!=e&&e===s.buttonValue})),this.enableScripting&&this.hasJSActions){const i=s.buttonValue;n.addEventListener("updatefromsandbox",(s=>{this._dispatchEventFromSandbox({value:s=>{const n=i===s.detail.value;for(const i of this._getElementsByName(s.target.name)){const s=n&&i.id===e;i.domElement&&(i.domElement.checked=s),t.setValue(i.id,{value:s})}}},s)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}return this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Ri extends Pi{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const s=t.lastChild;return this.enableScripting&&this.hasJSActions&&s&&(this._setDefaultPropertiesFromJS(s),s.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))),t}}class Oi extends Di{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,s=this.data.id,e=t.getValue(s,{value:this.data.fieldValue}),i=document.createElement("select");Mi.add(i),i.setAttribute("data-element-id",s),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=0;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",(()=>{const t=this.data.defaultFieldValue;for(const s of i.options)s.selected=s.value===t}));const r=(t,s)=>{const e=s.replaceAll(" "," ");t.textContent=e,e!==s&&t.setAttribute("display-value",s)};for(const t of this.data.options){const s=document.createElement("option");r(s,t.displayValue),s.value=t.exportValue,e.value.includes(t.exportValue)&&(s.setAttribute("selected",!0),n=!1),i.append(s)}let o=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),i.prepend(t),o=()=>{t.remove(),i.removeEventListener("input",o),o=null},i.addEventListener("input",o)}const h=t=>{const s=t?"value":"textContent",{options:e,multiple:n}=i;return n?Array.prototype.filter.call(e,(t=>t.selected)).map((t=>t[s])):-1===e.selectedIndex?null:e[e.selectedIndex][s]};let a=h(!1);const l=t=>Array.prototype.map.call(t.target.options,(t=>({displayValue:t.getAttribute("display-value")||t.textContent,exportValue:t.value})));return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",(e=>{this._dispatchEventFromSandbox({value(e){o?.();const n=e.detail.value,r=new Set(Array.isArray(n)?n:[n]);for(const t of i.options)t.selected=r.has(t.value);t.setValue(s,{value:h(!0)}),a=h(!1)},multipleSelection(t){i.multiple=!0},remove(e){const n=i.options,r=e.detail.remove;n[r].selected=!1,i.remove(r),n.length>0&&-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0),t.setValue(s,{value:h(!0),items:l(e)}),a=h(!1)},clear(e){for(;0!==i.length;)i.remove(0);t.setValue(s,{value:null,items:[]}),a=h(!1)},insert(e){const{index:n,displayValue:o,exportValue:c}=e.detail.insert,u=i.children[n],d=document.createElement("option");r(d,o),d.value=c,u?u.before(d):i.append(d),t.setValue(s,{value:h(!0),items:l(e)}),a=h(!1)},items(e){const{items:n}=e.detail;for(;0!==i.length;)i.remove(0);for(const t of n){const{displayValue:s,exportValue:e}=t,n=document.createElement("option");r(n,s),n.value=e,i.append(n)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(s,{value:h(!0),items:l(e)}),a=h(!1)},indices(e){const i=new Set(e.detail.indices);for(const t of e.target.options)t.selected=i.has(t.index);t.setValue(s,{value:h(!0)}),a=h(!1)},editable(t){t.target.disabled=!t.detail.editable}},e)})),i.addEventListener("input",(e=>{const i=h(!0),n=h(!1);t.setValue(s,{value:i}),e.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:s,name:"Keystroke",value:a,change:n,changeEx:i,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(i,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))):i.addEventListener("input",(function(){t.setValue(s,{value:h(!0)})})),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Bi extends Si{constructor(t){const{data:s,elements:e,parent:i}=t,n=!!i._commentManager;if(super(t,{isRenderable:!n&&Si._hasPopupData(s)}),this.elements=e,n&&Si._hasPopupData(s)){const t=this.popup=this.#To();for(const s of e)s.popup=t}else this.popup=null}#To(){return new $i({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 s=this.popup=this.#To(),e=[];for(const t of this.elements)t.popup=s,t.container.ariaHasPopup="dialog",e.push(t.data.id),t.addHighlightArea();return this.container.setAttribute("aria-controls",e.map((t=>`${o}${t}`)).join(",")),this.container}}class $i{#Y=null;#Po=this.#po.bind(this);#Eo=this.#Do.bind(this);#No=this.#Io.bind(this);#Fo=this.#_o.bind(this);#Ro=null;#Dt=null;#Oo=null;#Bo=null;#$o=null;#Lo=null;#Uo=null;#jo=!1;#Go=null;#zo=null;#_=null;#Ho=null;#Wo=null;#xs=null;#Vo=null;#ws=null;#Xo=null;#yo=null;#Yo=!1;#Ko=null;#qo=null;constructor({container:t,color:s,elements:e,titleObj:i,modificationDate:n,contentsObj:r,richText:o,parent:h,rect:a,parentRect:l,open:c,commentManager:u=null}){this.#Dt=t,this.#Xo=i,this.#Oo=r,this.#ws=o,this.#Lo=h,this.#Ro=s,this.#Vo=a,this.#Uo=l,this.#$o=e,this.#Y=u,this.#Ko=e[0],this.#Bo=at.toDateObject(n),this.trigger=e.flatMap((t=>t.getElementsToTriggerPopup())),u||(this.#Qo(),this.#Dt.hidden=!0,c&&this.#_o())}#Qo(){if(this.#zo)return;this.#zo=new AbortController;const{signal:t}=this.#zo;for(const s of this.trigger)s.addEventListener("click",this.#Fo,{signal:t}),s.addEventListener("pointerenter",this.#No,{signal:t}),s.addEventListener("pointerleave",this.#Eo,{signal:t}),s.classList.add("popupTriggerArea");for(const s of this.#$o)s.container?.addEventListener("keydown",this.#Po,{signal:t})}#Jo(){const t=this.#$o.find((t=>t.hasCommentButton));t&&(this.#Wo=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#Ho)return void(this.#Ho.parentNode||this.#Ko.container.after(this.#Ho));if(this.#Wo||this.#Jo(),!this.#Wo)return;const{signal:t}=this.#zo=new AbortController,s=this.#Ko.hasOwnCommentButton,e=()=>{this.#Y.toggleCommentPopup(this,!0,void 0,!s)},i=()=>{this.#Y.toggleCommentPopup(this,!1,!0,!s)},n=()=>{this.#Y.toggleCommentPopup(this,!1,!1)};if(s){this.#Ho=this.#Ko.container;for(const s of this.trigger)s.ariaHasPopup="dialog",s.ariaControls="commentPopup",s.addEventListener("keydown",this.#Po,{signal:t}),s.addEventListener("click",e,{signal:t}),s.addEventListener("pointerenter",i,{signal:t}),s.addEventListener("pointerleave",n,{signal:t}),s.classList.add("popupTriggerArea")}else{const s=this.#Ho=document.createElement("button");s.className="annotationCommentButton";const r=this.#Ko.container;s.style.zIndex=parseInt(r.style.zIndex,10)+1,s.tabIndex=0,s.ariaHasPopup="dialog",s.ariaControls="commentPopup",s.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#Zo(),this.#th(),s.addEventListener("keydown",this.#Po,{signal:t}),s.addEventListener("click",e,{signal:t}),s.addEventListener("pointerenter",i,{signal:t}),s.addEventListener("pointerleave",n,{signal:t}),r.after(s)}}#th(){if(this.#Ko.extraPopupElement&&!this.#Ko.editor)return;this.#Ho||this.renderCommentButton();const[t,s]=this.#Wo,{style:e}=this.#Ho;e.left=`calc(${t}%)`,e.top=`calc(${s}% - var(--comment-button-dim))`}#Zo(){this.#Ko.extraPopupElement||(this.#Ho||this.renderCommentButton(),this.#Ho.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){const{color:t,opacity:s}=this.#Ko.commentData;return t?this.#Lo._commentManager.makeCommentColor(t,s):null}focusCommentButton(){setTimeout((()=>{this.#Ho?.focus()}),0)}getData(){const{richText:t,color:s,opacity:e,creationDate:i,modificationDate:n}=this.#Ko.commentData;return{contentsObj:{str:this.comment},richText:t,color:s,opacity:e,creationDate:i,modificationDate:n}}get elementBeforePopup(){return this.#Ho}get comment(){return this.#qo||=this.#Ko.commentText,this.#qo}set comment(t){t!==this.comment&&(this.#Ko.commentText=this.#qo=t)}focus(){this.#Ko.container?.focus()}get parentBoundingClientRect(){return this.#Ko.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:s}){this.#Ho&&(this.#Ho.classList.toggle("selected",t),this.#Ho.ariaExpanded=s)}setSelectedCommentButton(t){this.#Ho.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#xs)return this.#xs;const{x:t,y:s,height:e}=this.#Ho.getBoundingClientRect(),{x:i,y:n,width:r,height:o}=this.#Ko.layer.getBoundingClientRect();return[(t-i)/r,(s+e-n)/o]}set commentPopupPosition(t){this.#xs=t}hasDefaultPopupPosition(){return null===this.#xs}get commentButtonPosition(){return this.#Wo}get commentButtonWidth(){return this.#Ho.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[s,e]=this.#xs||this.commentButtonPosition.map((t=>t/100)),i=this.parentBoundingClientRect,{x:n,y:r,width:o,height:h}=i;this.#Y.showDialog(null,this,n+s*o,r+e*h,{...t,parentDimensions:i})}render(){if(this.#Go)return;const t=this.#Go=document.createElement("div");if(t.className="popup",this.#Ro){const s=t.style.outlineColor=O.makeHexColor(...this.#Ro);t.style.backgroundColor=`color-mix(in srgb, ${s} 30%, white)`}const s=document.createElement("span");if(s.className="header",this.#Xo?.str){const t=document.createElement("span");t.className="title",s.append(t),({dir:t.dir,str:t.textContent}=this.#Xo)}if(t.append(s),this.#Bo){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.#Bo.valueOf()})),t.dateTime=this.#Bo.toISOString(),s.append(t)}Ct({html:this.#sh||this.#Oo.str,dir:this.#Oo?.dir,className:"popupContent"},t),this.#Dt.append(t)}get#sh(){const t=this.#ws,s=this.#Oo;return!t?.str||s?.str&&s.str!==t.str?null:this.#ws.html||null}get#eh(){return this.#sh?.attributes?.style?.fontSize||0}get#ih(){return this.#sh?.attributes?.style?.color||null}#nh(t){const s=[],e={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:s}]}},i={style:{color:this.#ih,fontSize:this.#eh?`calc(${this.#eh}px * var(--total-scale-factor))`:""}};for(const e of t.split("\n"))s.push({name:"span",value:e,attributes:i});return e}#po(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#jo)&&this.#_o()}updateEdited({rect:t,popup:s,deleted:e}){if(this.#Y)return e?(this.remove(),this.#qo=null):s&&(s.deleted?this.remove():(this.#Zo(),this.#qo=s.text)),void(t&&(this.#Wo=null,this.#Jo(),this.#th()));e||s?.deleted?this.remove():(this.#Qo(),this.#yo||={contentsObj:this.#Oo,richText:this.#ws},t&&(this.#_=null),s&&s.text&&(this.#ws=this.#nh(s.text),this.#Bo=at.toDateObject(s.date),this.#Oo=null),this.#Go?.remove(),this.#Go=null)}resetEdited(){this.#yo&&(({contentsObj:this.#Oo,richText:this.#ws}=this.#yo),this.#yo=null,this.#Go?.remove(),this.#Go=null,this.#_=null)}remove(){if(this.#zo?.abort(),this.#zo=null,this.#Go?.remove(),this.#Go=null,this.#Yo=!1,this.#jo=!1,this.#Ho?.remove(),this.#Ho=null,this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#rh(){if(null!==this.#_)return;const{page:{view:t},viewport:{rawDims:{pageWidth:s,pageHeight:e,pageX:i,pageY:n}}}=this.#Lo;let r=!!this.#Uo,o=r?this.#Uo:this.#Vo;for(const t of this.#$o)if(!o||null!==O.intersect(t.data.rect,o)){o=t.data.rect,r=!0;break}const h=O.normalizeRect([o[0],t[3]-o[1]+t[1],o[2],t[3]-o[3]+t[1]]);this.#_=[100*(h[0]+(r?o[2]-o[0]+5:0)-i)/s,100*(h[1]-n)/e];const{style:a}=this.#Dt;a.left=`${this.#_[0]}%`,a.top=`${this.#_[1]}%`}#_o(){this.#Y?this.#Y.toggleCommentPopup(this,!1):(this.#jo=!this.#jo,this.#jo?(this.#Io(),this.#Dt.addEventListener("click",this.#Fo),this.#Dt.addEventListener("keydown",this.#Po)):(this.#Do(),this.#Dt.removeEventListener("click",this.#Fo),this.#Dt.removeEventListener("keydown",this.#Po)))}#Io(){this.#Go||this.render(),this.isVisible?this.#jo&&this.#Dt.classList.add("focused"):(this.#rh(),this.#Dt.hidden=!1,this.#Dt.style.zIndex=parseInt(this.#Dt.style.zIndex,10)+1e3)}#Do(){this.#Dt.classList.remove("focused"),!this.#jo&&this.isVisible&&(this.#Dt.hidden=!0,this.#Dt.style.zIndex=parseInt(this.#Dt.style.zIndex,10)-1e3)}forceHide(){this.#Yo=this.isVisible,this.#Yo&&(this.#Dt.hidden=!0)}maybeShow(){this.#Y||(this.#Qo(),this.#Yo&&(this.#Go||this.#Io(),this.#Yo=!1,this.#Dt.hidden=!1))}get isVisible(){return!this.#Y&&!1===this.#Dt.hidden}}class Li extends Si{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=a.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const s of this.textContent){const e=document.createElement("span");e.textContent=s,t.append(e)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class Ui extends Si{#oh=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:s,height:e}=this,i=this.svgFactory.create(s,e,!0),n=this.#oh=this.svgFactory.createElement("svg:line");return n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),i.append(n),this.container.append(i),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#oh}addHighlightArea(){this.container.classList.add("highlightArea")}}class ji extends Si{#hh=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:s,height:e}=this,i=this.svgFactory.create(s,e,!0),n=t.borderStyle.width,r=this.#hh=this.svgFactory.createElement("svg:rect");return r.setAttribute("x",n/2),r.setAttribute("y",n/2),r.setAttribute("width",s-n),r.setAttribute("height",e-n),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#hh}addHighlightArea(){this.container.classList.add("highlightArea")}}class Gi extends Si{#ah=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:s,height:e}=this,i=this.svgFactory.create(s,e,!0),n=t.borderStyle.width,r=this.#ah=this.svgFactory.createElement("svg:ellipse");return r.setAttribute("cx",s/2),r.setAttribute("cy",e/2),r.setAttribute("rx",s/2-n/2),r.setAttribute("ry",e/2-n/2),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#ah}addHighlightArea(){this.container.classList.add("highlightArea")}}class zi extends Si{#lh=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:s,borderStyle:e,popupRef:i},width:n,height:r}=this;if(!s)return this.container;const o=this.svgFactory.create(n,r,!0);let h=[];for(let e=0,i=s.length;e<i;e+=2)h.push(`${s[e]-t[0]},${t[3]-s[e+1]}`);h=h.join(" ");const a=this.#lh=this.svgFactory.createElement(this.svgElementName);return a.setAttribute("points",h),a.setAttribute("stroke-width",e.width||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),o.append(a),this.container.append(o),!i&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#lh}addHighlightArea(){this.container.classList.add("highlightArea")}}class Hi extends zi{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Wi extends Si{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}}class Vi extends Si{#ch=null;#uh=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?a.HIGHLIGHT:a.INK}#dh(t,s){switch(t){case 90:return{transform:`rotate(90) translate(${-s[0]},${s[1]}) scale(1,-1)`,width:s[3]-s[1],height:s[2]-s[0]};case 180:return{transform:`rotate(180) translate(${-s[2]},${s[1]}) scale(1,-1)`,width:s[2]-s[0],height:s[3]-s[1]};case 270:return{transform:`rotate(270) translate(${-s[2]},${s[3]}) scale(1,-1)`,width:s[3]-s[1],height:s[2]-s[0]};default:return{transform:`translate(${-s[0]},${s[3]}) scale(1,-1)`,width:s[2]-s[0],height:s[3]-s[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:s,inkLists:e,borderStyle:i,popupRef:n}}=this,{transform:r,width:o,height:h}=this.#dh(s,t),a=this.svgFactory.create(o,h,!0),l=this.#ch=this.svgFactory.createElement("svg:g");a.append(l),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("stroke-miterlimit",10),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),l.setAttribute("transform",r);for(const t of e){const s=this.svgFactory.createElement(this.svgElementName);this.#uh.push(s),s.setAttribute("points",t.join(",")),l.append(s)}return!n&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(a),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:s,points:e,rect:i}=t,n=this.#ch;if(s>=0&&n.setAttribute("stroke-width",s||1),e)for(let t=0,s=this.#uh.length;t<s;t++)this.#uh[t].setAttribute("points",e[t].join(","));if(i){const{transform:t,width:s,height:e}=this.#dh(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${s} ${e}`),n.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#uh}addHighlightArea(){this.container.classList.add("highlightArea")}}class Xi extends Si{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=a.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:s}}=this;if(!s&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){const s=document.createElement("mark");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Yi extends Si{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:s}}=this;if(!s&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("underlineAnnotation"),t){const s=document.createElement("u");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Ki extends Si{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:s}}=this;if(!s&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("squigglyAnnotation"),t){const s=document.createElement("u");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class qi extends Si{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:s}}=this;if(!s&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("strikeoutAnnotation"),t){const s=document.createElement("s");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Qi extends Si{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=a.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class Ji extends Si{#fh=null;constructor(t){super(t,{isRenderable:!0});const{fileId:s,file:e}=this.data;this.filename=e.filename,this.content=e.content,this.fileId=s,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,attachmentId:this.fileId,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:s}=this;let e;s.hasAppearance||0===s.fillAlpha?e=document.createElement("div"):(e=document.createElement("img"),e.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(s.name)?"paperclip":"pushpin"}.svg`,s.fillAlpha&&s.fillAlpha<1&&(e.style=`filter: opacity(${Math.round(100*s.fillAlpha)}%);`)),e.addEventListener("dblclick",this.#ph.bind(this)),this.#fh=e;const{isMac:i}=R.platform;return t.addEventListener("keydown",(t=>{"Enter"===t.key&&(i?t.metaKey:t.ctrlKey)&&this.#ph()})),!s.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):e.classList.add("popupTriggerArea"),t.append(e),t}getElementsToTriggerPopup(){return this.#fh}addHighlightArea(){this.container.classList.add("highlightArea")}async#ph(){const{fileId:t,filename:s,content:e}=this,i=await this.linkService.getAttachmentContent(t)||e;i&&this.downloadManager?.openOrDownloadData(i,s)}}class Zi extends Si{#B=new AbortController;#gh=null;#mh=null;constructor(t){super(t,{isRenderable:!!t.data.richMedia})}render(){this.container.classList.add("mediaAnnotation");const{filename:t}=this.data.richMedia,s=document.createElement("button");return s.className="mediaPlayButton",s.type="button",s.title=s.ariaLabel=t,s.addEventListener("click",(()=>this.#Ah(s)),{signal:this.#B.signal}),this.container.append(s),this.container}async#Ah(t){const{fileId:s,filename:e,contentType:i}=this.data.richMedia;let n;t.disabled=!0;try{n=await this.linkService.getAttachmentContent(s)}catch{return}finally{t.disabled=!1}if(!n||!t.isConnected)return;const{signal:r}=this.#B,o=URL.createObjectURL(new Blob([n],{type:i}));this.#gh=o;const h=i.startsWith("audio/"),a=document.createElement(h?"audio":"video");if(this.#mh=a,a.className="mediaContent",this._setBackgroundColor(a),a.src=o,a.title=e,a.controls=!0,a.autoplay=!0,a.tabIndex=0,h){let t=!1,s=!1;const e=()=>{a.controls=t||s};this.container.addEventListener("pointerenter",(()=>{t=!0,e()}),{signal:r}),this.container.addEventListener("pointerleave",(()=>{t=!1,e()}),{signal:r}),this.container.addEventListener("focusin",(()=>{s=!0,e()}),{signal:r}),this.container.addEventListener("focusout",(()=>{s=!1,e()}),{signal:r})}a.addEventListener("emptied",(()=>this.#wh(o)),{once:!0,signal:r}),t.replaceWith(a),a.play().catch((()=>{}))}#wh(t=this.#gh){t&&t===this.#gh&&(URL.revokeObjectURL(t),this.#gh=null)}destroy(){this.#B.abort(),this.#mh&&(this.#mh.pause(),this.#mh.removeAttribute("src"),this.#mh.load(),this.#mh=null),this.#wh()}}class tn{#bh=null;#yh=null;#W=null;#vh=new Map;#xh=null;#Mh=null;#$o=[];#kh=!1;zIndex=0;constructor({div:t,accessibilityManager:s,annotationCanvasMap:e,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:o,commentManager:h,linkService:a,annotationStorage:l}){this.div=t,this.#bh=s,this.#yh=e,this.#xh=o||null,this.#Mh=a||null,this.#W=l||new Qt,this.page=n,this.viewport=r,this._annotationEditorUIManager=i,this._commentManager=h||null}hasEditableAnnotations(){return this.#vh.size>0}async render(t){const{annotations:s,optionalContentConfig:e}=t,i=this.div;ft(i,this.viewport);const n=new Map,r=[],h={data:null,layer:i,linkService:this.#Mh,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new xi,annotationStorage:this.#W,enableComment:!0===t.enableComment,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of s){if(t.noHTML)continue;const s=t.annotationType===d.POPUP;if(s){const s=n.get(t.id);if(!s)continue;if(!this._commentManager){r.push(t);continue}h.elements=s}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;h.data=t;const i=Ci.create(h);if(!i.isRenderable)continue;s||(this.#$o.push(i),t.popupRef&&n.getOrInsertComputed(t.popupRef,j).push(i));const o=i.render();t.hidden&&(o.style.visibility="hidden"),i.updateOC(e),i._isEditable&&(this.#vh.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}await this.#Ch();for(const t of r){const s=h.elements=n.get(t.id);h.data=t;const e=Ci.create(h);if(!e.isRenderable)continue;const i=e.render();e.contentElement.id=`${o}${t.id}`,t.hidden&&(i.style.visibility="hidden"),s.at(-1).container.after(i)}this.#Sh()}async#Ch(){if(0===this.#$o.length)return;this.div.replaceChildren();const t=[];if(!this.#kh){this.#kh=!0;for(const{contentElement:s,data:{hidden:e,id:i,oc:n}}of this.#$o){const r=s.id=`${o}${i}`,h="a"===s.localName&&!e&&!n;t.push(this.#xh?.getAriaAttributes(r,{enableLinkOwnership:h}).then((t=>{if(t)for(const[e,i]of t)s.setAttribute(e,i)})))}}this.#$o.sort((({data:{rect:[t,s,e,i]}},{data:{rect:[n,r,o,h]}})=>{if(t===e&&s===i)return 1;if(n===o&&r===h)return-1;const a=(s+i)/2,l=(r+h)/2;return a>=h&&l<=s?-1:l>=i&&a<=r?1:(t+e)/2-(n+o)/2}));const s=document.createDocumentFragment();for(const t of this.#$o)s.append(t.container),this._commentManager?(t.extraPopupElement?.popup||t.popup)?.renderCommentButton():t.extraPopupElement&&s.append(t.extraPopupElement.render());if(this.div.append(s),await Promise.all(t),this.#bh){const t=await(this.#xh?.getAnnotationIds());for(const{contentElement:s}of this.#$o)t?.has(s.id)||this.#bh.addPointerInTextLayer(s,!1)}}async addLinkAnnotations(t){const s={data:null,layer:this.div,linkService:this.#Mh,svgFactory:new xi,parent:this};for(const e of t){e.borderStyle||=tn._defaultBorderStyle,s.data=e;const t=Ci.create(s);t.isRenderable&&(t.render(),t.contentElement.id=`${o}${e.id}`,this.#$o.push(t))}await this.#Ch()}update({viewport:t,optionalContentConfig:s}){const e=this.div;this.viewport=t,ft(e,{rotation:t.rotation});for(const t of this.#$o)t.updateOC(s);this.#Sh(),e.hidden=!1}destroy(){for(const t of this.#$o)t.destroy?.(),this.#bh?.removePointerInTextLayer(t.contentElement);this.#$o.length=0,this.#vh.clear(),this.div.replaceChildren()}#Sh(){if(!this.#yh)return;const t=this.div;for(const[s,e]of this.#yh){const i=t.querySelector(`[data-annotation-id="${s}"]`);if(!i)continue;if(Array.isArray(e))for(const t of e)t.className="annotationContent",t.ariaHidden=!0;else e.className="annotationContent",e.ariaHidden=!0;const n=[];for(const t of i.children)"CANVAS"===t.nodeName&&n.push(t);for(const t of n)t.remove();const r=Array.isArray(e)?e[0]:e,{firstChild:o}=i;if(o?o.classList.contains("annotationContent")?o.after(r):o.before(r):i.append(r),Array.isArray(e)){let t=r;for(let s=1,i=e.length;s<i;s++)t.after(e[s]),t=e[s]}this.#yh.delete(s);const h=this.#vh.get(s);h&&(h._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(s,i.id,e),h._hasNoCanvas=!1):h.canvas=e)}}refreshCanvases(){this.#Sh()}getEditableAnnotations(){return this.#vh.values()}getEditableAnnotation(t){return this.#vh.get(t)}addFakeAnnotation(t){const{div:s}=this,{id:e,rotation:i}=t,n=new Ti({data:{id:e,rect:t.getPDFRect(),rotation:i},editor:t,layer:s,parent:this,enableComment:!!this._commentManager,linkService:this.#Mh,annotationStorage:this.#W});return n.render(),n.contentElement.id=`${o}${e}`,n.createOrUpdatePopup(),this.#$o.push(n),n}removeAnnotation(t){const s=this.#$o.findIndex((s=>s.data.id===t));if(s<0)return;const[e]=this.#$o.splice(s,1);this.#bh?.removePointerInTextLayer(e.contentElement)}updateFakeAnnotations(t){if(0!==t.length){for(const s of t)s.updateFakeAnnotationElement(this);this.#Ch()}}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}static get _defaultBorderStyle(){return S(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:1,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const sn=/\r\n?|\n/g;class en extends Ht{#Th="";#Ph=`${this.id}-editor`;#Eh=null;#eh;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=en.prototype,s=t=>t.isEmpty(),e=Bt.TRANSLATE_SMALL,i=Bt.TRANSLATE_BIG;return S(this,"_keyboardManager",new Rt([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter"],t.commitOrRemove],[["Escape"],t.commitOrRemove],[["ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:s}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:s}],[["ArrowRight"],t._translateEmpty,{args:[e,0],checker:s}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:s}],[["ArrowUp"],t._translateEmpty,{args:[0,-e],checker:s}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:s}],[["ArrowDown"],t._translateEmpty,{args:[0,e],checker:s}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:s}]]))}static _type="freetext";static _editorType=a.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.color=t.color||en._defaultColor||Ht._defaultLineColor,this.#eh=t.fontSize||en._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert(Ht._l10nAlert.freetext),this.canAddComment=!1}static initialize(t,s){Ht.initialize(t,s);const e=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(e.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,s){switch(t){case l.FREETEXT_SIZE:en._defaultFontSize=s;break;case l.FREETEXT_COLOR:en._defaultColor=s}}updateParams(t,s){switch(t){case l.FREETEXT_SIZE:this.#Dh(s);break;case l.FREETEXT_COLOR:this.#Zo(s)}}static get defaultPropertiesToUpdate(){return[[l.FREETEXT_SIZE,en._defaultFontSize],[l.FREETEXT_COLOR,en._defaultColor||Ht._defaultLineColor]]}get propertiesToUpdate(){return[[l.FREETEXT_SIZE,this.#eh],[l.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new Ai(this),[["colorPicker",this._colorPicker]]}get colorType(){return l.FREETEXT_COLOR}#Dh(t){const s=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#eh)*this.parentScale),this.#eh=t,this.#Nh()},e=this.#eh;this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:l.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#Zo(t){const s=t=>{this.color=t,this.onUpdatedColor()},e=this.color;this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:l.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,s){this._uiManager.translateSelectedEditors(t,s,!0)}getInitialTranslation(){const t=this.parentScale;return[-en._internalPadding*t,-(en._internalPadding+this.#eh)*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.#Eh=new AbortController;const t=this._uiManager.combinedSignal(this.#Eh);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.#Ph),this._isDraggable=!0,this.#Eh?.abort(),this.#Eh=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()}#Ih(){const t=[];this.editorDiv.normalize();let s=null;for(const e of this.editorDiv.childNodes)s?.nodeType===Node.TEXT_NODE&&"BR"===e.nodeName||(t.push(en.#Fh(e)),s=e);return t.join("\n")}#Nh(){const[t,s]=this.parentDimensions;let e;if(this.isAttachedToDOM)e=this.div.getBoundingClientRect();else{const{currentLayer:t,div:s}=this,i=s.style.display,n=s.classList.contains("hidden");s.classList.remove("hidden"),s.style.display="hidden",t.div.append(this.div),e=s.getBoundingClientRect(),s.remove(),s.style.display=i,s.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=e.width/t,this.height=e.height/s):(this.width=e.height/t,this.height=e.width/s),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#Th,s=this.#Th=this.#Ih().trimEnd();if(t===s)return;const e=t=>{this.#Th=t,t?(this.#_h(),this._uiManager.rebuild(this),this.#Nh()):this.remove()};this.addCommands({cmd:()=>{e(s)},undo:()=>{e(t)},mustExec:!1}),this.#Nh()}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){en._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,s;(this._isCopy||this.annotationElementId)&&(t=this.x,s=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#Ph),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:e}=this.editorDiv;if(e.fontSize=`calc(${this.#eh}px * var(--total-scale-factor))`,e.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[e,i]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[r,o]=this.getInitialTranslation();[r,o]=this.pageTranslationToScreen(r,o);const[h,a]=this.pageDimensions,[l,c]=this.pageTranslation;let u,d;switch(this.rotation){case 0:u=t+(n[0]-l)/h,d=s+this.height-(n[1]-c)/a;break;case 90:u=t+(n[0]-l)/h,d=s-(n[1]-c)/a,[r,o]=[o,-r];break;case 180:u=t-this.width+(n[0]-l)/h,d=s-(n[1]-c)/a,[r,o]=[-r,-o];break;case 270:u=t+(n[0]-l-this.height*a)/h,d=s+(n[1]-c-this.width*h)/a,[r,o]=[-o,r]}this.setAt(u*e,d*i,r,o)}else this._moveAfterPaste(t,s);this.#_h(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#Fh(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(sn,"")}editorDivPaste(t){const s=t.clipboardData||window.clipboardData,{types:e}=s;if(1===e.length&&"text/plain"===e[0])return;t.preventDefault();const i=en.#Rh(s.getData("text")||"").replaceAll(sn,"\n");if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const r=n.getRangeAt(0);if(!i.includes("\n"))return r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:o,startOffset:h}=r,a=[],l=[];if(o.nodeType===Node.TEXT_NODE){const t=o.parentElement;if(l.push(o.nodeValue.slice(h).replaceAll(sn,"")),t!==this.editorDiv){let s=a;for(const e of this.editorDiv.childNodes)e!==t?s.push(en.#Fh(e)):s=l}a.push(o.nodeValue.slice(0,h).replaceAll(sn,""))}else if(o===this.editorDiv){let t=a,s=0;for(const e of this.editorDiv.childNodes)s++===h&&(t=l),t.push(en.#Fh(e))}this.#Th=`${a.join("\n")}${i}${l.join("\n")}`,this.#_h();const c=new Range;let u=Math.sumPrecise(a.map((t=>t.length)));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const s=t.nodeValue.length;if(u<=s){c.setStart(t,u),c.setEnd(t,u);break}u-=s}n.removeAllRanges(),n.addRange(c)}#_h(){if(this.editorDiv.replaceChildren(),this.#Th)for(const t of this.#Th.split("\n")){const s=document.createElement("div");s.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(s)}}#Oh(){return this.#Th.replaceAll(" "," ")}static#Rh(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=en._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,s,e){let i=null;if(t instanceof Li){const{data:{defaultAppearanceData:{fontSize:s,fontColor:e},rect:n,rotation:r,id:o,popupRef:h,richText:l,contentsObj:c,creationDate:u,modificationDate:d},textContent:f,textPosition:p,parent:{page:{pageNumber:g}}}=t;if(!f?.length)return null;i=t={annotationType:a.FREETEXT,color:Array.from(e),fontSize:s,value:f.join("\n"),position:p,pageIndex:g-1,rect:n.slice(0),rotation:r,annotationElementId:o,id:o,deleted:!1,popupRef:h,comment:c?.str||null,richText:l,creationDate:u,modificationDate:d}}const n=await super.deserialize(t,s,e);return n.#eh=t.fontSize,n.color=O.makeHexColor(...t.color),n.#Th=en.#Rh(t.value),n._initialData=i,t.comment&&n.setCommentData(t),n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s=Ht._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),e=Object.assign(super.serialize(t),{color:s,fontSize:this.#eh,value:this.#Oh()});return this.addComment(e),t?(e.isCopy=!0,e):this.annotationElementId&&!this.#Bh(e)?null:(e.id=this.annotationElementId,e)}#Bh(t){const{value:s,fontSize:e,color:i,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==s||t.fontSize!==e||t.color.some(((t,s)=>t!==i[s]))||t.pageIndex!==n}renderAnnotationElement(t){const s=super.renderAnnotationElement(t);if(!s)return null;const{style:e}=s;e.fontSize=`calc(${this.#eh}px * var(--total-scale-factor))`,e.color=this.color,s.replaceChildren();for(const t of this.#Th.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),s.append(e)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#Th}}),s}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class nn{#$h=Object.create(null);updateProperty(t,s){this[t]=s,this.updateSVGProperty(t,s)}updateProperties(t){if(t)for(const[s,e]of Object.entries(t))s.startsWith("_")||this.updateProperty(s,e)}updateSVGProperty(t,s){this.#$h[t]=s}toSVGProperties(){const t=this.#$h;return this.#$h=Object.create(null),{root:t}}reset(){this.#$h=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){v("Not implemented")}}class rn extends Ht{#Lh=null;#Uh;_clipPathId=null;_colorPicker=null;_drawId=null;_drawOutlines=null;_focusDrawId=null;static _currentDrawId=-1;static _currentParent=null;static#jh=null;static#Gh=null;static#zh=null;static#Hh=null;static _INNER_MARGIN=3;constructor(t){super(t),this.#Uh=t.mustBeCommitted||!1,this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(t){t.drawOutlines&&(this.#Wh(t),this.#Vh())}#Wh({drawOutlines:t,drawId:s,drawingOptions:e,clipPathId:i}){this._drawOutlines=t,this._drawingOptions||=e,this.annotationElementId||this._uiManager.a11yAlert(Ht._l10nAlert[this.editorType]),s>=0?(this._drawId=s,this._clipPathId=i??null,this.parent.drawLayer.finalizeDraw(s,t.defaultProperties),this.#Xh(this.parent)):this._drawId=this.#Yh(t,this.parent),this.#Kh(t.box)}#Yh(t,s){const{id:e,clipPathId:i}=s.drawLayer.draw(rn._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,this.constructor._hasClipPath);return this.constructor._hasClipPath&&(this._clipPathId=i),this.#Xh(s),e}#Xh(t){const s=this._drawOutlines.getFocusSVGProperties(this.#qh);s&&(this._focusDrawId=t.drawLayer.drawOutline(s,this._drawOutlines.focusMustRemoveSelfIntersections))}#Qh(t=this.#qh){null!==this._focusDrawId&&this.parent?.drawLayer.updateProperties(this._focusDrawId,this._drawOutlines.getFocusSVGProperties(t))}#Jh(t){null!==this._focusDrawId&&this.parent?.drawLayer.updateProperties(this._focusDrawId,{rootClass:t})}#Zh(){const{parent:t,_drawId:s,_focusDrawId:e,_isVisible:i}=this;if(!t||null===s)return;const n={hidden:!i};t.drawLayer.updateProperties(s,{rootClass:n}),null!==e&&t.drawLayer.updateProperties(e,{rootClass:n})}static _mergeSVGProperties(t,s){const e=new Set(Object.keys(t));for(const[i,n]of Object.entries(s))e.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){v("Not implemented")}static get typesMap(){v("Not implemented")}static get isDrawer(){return!0}static get _hasClipPath(){return!1}static get _hasDrawClass(){return!0}static get supportMultipleDrawings(){return!1}get _drawRotation(){return this.rotation}get _opacityName(){return this.constructor.typesMap.get(this.opacityType)}get#qh(){return(this.parentRotation-this._drawRotation+360)%360}static updateDefaultParams(t,s){const e=this.typesMap.get(t);e&&this._defaultDrawingOptions.updateProperty(e,s),this._currentParent&&(rn.#jh.updateProperty(e,s),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,s){const e=this.constructor.typesMap.get(t);e&&this._updateProperty(t,e,s)}static get defaultPropertiesToUpdate(){const t=[],s=this._defaultDrawingOptions;for(const[e,i]of this.typesMap)t.push([e,s[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:s}=this;for(const[e,i]of this.constructor.typesMap)t.push([e,s[i]]);return t}_updateProperty(t,s,e){const i=this._drawingOptions,n=i[s],r=e=>{i.updateProperty(s,e);const n=this._drawOutlines.updateProperty(s,e);n&&this.#Kh(n),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties()),t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:r.bind(this,e),undo:r.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,s,e=this.colorAndOpacityType){const i=this.constructor.typesMap.get(this.colorType),n=this._opacityName,r=this._drawingOptions,o=r[i],h=r[n],a=(t,s)=>{r.updateProperty(i,t),r.updateProperty(n,s),this._drawOutlines.updateProperty(i,t),this._drawOutlines.updateProperty(n,s),this.parent?.drawLayer.updateProperties(this._drawId,r.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:a.bind(this,t,s),undo:a.bind(this,o,h),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:e,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,rn._mergeSVGProperties(this._drawOutlines.getPathResizingSVGProperties(this.#ta()),{bbox:this.#sa()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,rn._mergeSVGProperties(this._drawOutlines.getPathResizedSVGProperties(this.#ta()),{bbox:this.#sa()})),this.#Qh()}_onTranslating(t,s){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#sa()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,rn._mergeSVGProperties(this._drawOutlines.getPathTranslatedSVGProperties(this.#ta(),this.parentDimensions),{bbox:this.#sa()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}get _mustBeDisabledOnCommit(){return!0}commit(){super.commit(),this._mustBeDisabledOnCommit&&(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.#Uh&&(this.#Uh=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this._uiManager.removeShouldRescale(this),this.#ea(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#Vh(),this.#Kh(this._drawOutlines.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let s=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#ea()):t&&(this._uiManager.addShouldRescale(this),this.#Vh(t),s=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.#Zh(),s&&this.select()}#ea(){if(null===this._drawId||!this.parent)return;const{drawLayer:t}=this.parent;t.remove(this._drawId),this._drawId=null,null!==this._focusDrawId&&(t.remove(this._focusDrawId),this._focusDrawId=null),this._drawingOptions.reset()}#Vh(t=this.parent){if(null===this._drawId||this.parent!==t){if(null!==this._drawId){const{drawLayer:s}=this.parent;return s.updateParent(this._drawId,t.drawLayer),void(null!==this._focusDrawId&&s.updateParent(this._focusDrawId,t.drawLayer))}this._drawingOptions.updateAll(),this._drawId=this.#Yh(this._drawOutlines,t),this._clipPathId&&this.#Lh&&(this.#Lh.style.clipPath=this._clipPathId)}}#ia([t,s,e,i]){const{parentDimensions:[n,r],_drawRotation:o}=this;switch(o){case 90:return[s,1-t,e*(r/n),i*(n/r)];case 180:return[1-t,1-s,e,i];case 270:return[1-s,t,e*(r/n),i*(n/r)];default:return[t,s,e,i]}}#ta(){const{x:t,y:s,width:e,height:i,parentDimensions:[n,r],_drawRotation:o}=this;switch(o){case 90:return[1-s,t,e*(n/r),i*(r/n)];case 180:return[1-t,1-s,e,i];case 270:return[s,1-t,e*(n/r),i*(r/n)];default:return[t,s,e,i]}}#Kh(t){[this.x,this.y,this.width,this.height]=this.#ia(t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#sa(t=this.parentRotation){const{x:s,y:e,width:i,height:n,_drawRotation:r,parentDimensions:[o,h]}=this;switch((4*r+t)/90){case 1:return[1-e-n,s,n,i];case 2:return[1-s-i,1-e-n,i,n];case 3:return[e,1-s-i,n,i];case 4:return[s,e-i*(o/h),n*(h/o),i*(o/h)];case 5:return[1-e,s,i*(o/h),n*(h/o)];case 6:return[1-s-n*(h/o),1-e,n*(h/o),i*(o/h)];case 7:return[e-i*(o/h),1-s-n*(h/o),i*(o/h),n*(h/o)];case 8:return[s-i,e-n,i,n];case 9:return[1-e,s-i,n,i];case 10:return[1-s,1-e,i,n];case 11:return[e-n,1-s,n,i];case 12:return[s-n*(h/o),e,n*(h/o),i*(o/h)];case 13:return[1-e-i*(o/h),s-n*(h/o),i*(o/h),n*(h/o)];case 14:return[1-s,1-e-i*(o/h),n*(h/o),i*(o/h)];case 15:return[e,1-s,i*(o/h),n*(h/o)];default:return[s,e,i,n]}}rotate(t=this.parentRotation){if(!this.parent||null===this._drawId)return;const s=(t-this._drawRotation+360)%360;this.parent.drawLayer.updateProperties(this._drawId,rn._mergeSVGProperties({bbox:this.#sa(t)},this._drawOutlines.updateRotation(s))),this.#Qh(s)}show(t=this._isVisible){super.show(t),this.#Zh()}select(){super.select(),this.#Jh({hovered:!1,selected:!0})}unselect(){super.unselect(),this.#Jh({selected:!1})}pointerover(){this.isSelected||this.#Jh({hovered:!0})}pointerleave(){this.isSelected||this.#Jh({hovered:!1})}onScaleChanging(){if(!this.parent)return;const t=this._drawOutlines.updateParentDimensions(this.parentDimensions,this.parent.scale);t&&this.#Kh(t)}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,s;this._isCopy&&(t=this.x,s=this.y);const e=super.render();this.constructor._hasDrawClass&&e.classList.add("draw");const i=this.#Lh=document.createElement("div");return e.append(i),i.setAttribute("aria-hidden","true"),i.className="internal",this._clipPathId&&(i.style.clipPath=this._clipPathId),Dt(this,i,["pointerover","pointerleave"]),this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,s),e}static createDrawerInstance(t){v("Not implemented")}static _getDrawingTarget(t,{target:s}){return s}static _getPointerCoords({offsetX:t,offsetY:s,clientX:e,clientY:i},n=null){if(!n)return[t,s];let r=e-n.clientX,o=i-n.clientY;switch(this._currentParent.viewport.rotation){case 90:[r,o]=[o,-r];break;case 180:[r,o]=[-r,-o];break;case 270:[r,o]=[-o,r]}return[n.offsetX+r,n.offsetY+o]}static _addDrawingListeners(t,s){}static _endDrawingSession(t=!1){return this._currentParent.endDrawingSession(t)}static startDrawing(t,s,e,i){const{pointerId:n,pointerType:r}=i;if(Nt.isInitializedAndDifferentPointerType(r))return;const o=this._getDrawingTarget(t,i),[h,a]=this._getPointerCoords(i),{viewport:{rotation:l}}=t,{x:c,y:u,width:d,height:f}=o.getBoundingClientRect(),p=rn.#Gh=new AbortController,g=t.combinedSignal(p);if(Nt.setPointer(r,n),window.addEventListener("pointerup",(t=>{Nt.isSamePointerIdOrRemove(t.pointerId)&&this._endDraw(t)}),{signal:g}),window.addEventListener("pointercancel",(t=>{Nt.isSamePointerIdOrRemove(t.pointerId)&&this._endDrawingSession()}),{signal:g}),window.addEventListener("pointerdown",(t=>{Nt.isSamePointerType(t.pointerType)&&(Nt.initializeAndAddPointerId(t.pointerId),rn.#jh.isCancellable()&&(rn.#jh.removeLastElement(),rn.#jh.isEmpty()?this._endDrawingSession(!0):this._endDraw(null)))}),{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",ot,{signal:g}),o.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),o.addEventListener("touchmove",(t=>{Nt.isSameTimeStamp(t.timeStamp)&&ht(t)}),{signal:g}),this._addDrawingListeners(o,g),t.toggleDrawing(),s._editorUndoBar?.hide(),rn.#jh)return void t.drawLayer.updateProperties(this._currentDrawId,rn.#jh.startNew(h,a,d,f,l));s.updateUIForDefaultProperties(this),rn.#jh=this.createDrawerInstance({x:h,y:a,box:[c,u,d,f],rotation:l,parent:t,isLTR:e}),rn.#zh=this.getDefaultDrawingOptions(),this._currentParent=t;const{id:m,clipPathId:A}=t.drawLayer.draw(this._mergeSVGProperties(rn.#zh.toSVGProperties(),rn.#jh.defaultSVGProperties),!0,this._hasClipPath);this._currentDrawId=m,rn.#Hh=this._hasClipPath?A:null}static _drawMove(t){if(!rn.#jh)return;if(!Nt.isSamePointerId(t.pointerId))return;if(Nt.isUsingMultiplePointers())return void this._endDraw(t);let s;const e=t.getCoalescedEvents?.();if(e?.length){const i=[];for(const s of e)i.push(...this._getPointerCoords(s,t));s=rn.#jh.addPoints(i)}else s=rn.#jh.add(...this._getPointerCoords(t));this._currentParent.drawLayer.updateProperties(this._currentDrawId,s),Nt.setTimeStamp(t.timeStamp),ht(t)}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,rn.#jh=null,rn.#zh=null,rn.#Hh=null,Nt.clearTimeStamp()),rn.#Gh&&(rn.#Gh.abort(),rn.#Gh=null,Nt.clearPointerIds())}static _endDraw(t){const s=this._currentParent;if(s)if(s.toggleDrawing(!0),this._cleanup(!1),s.drawLayer.updateProperties(this._currentDrawId,t?.target===s.div?rn.#jh.end(...this._getPointerCoords(t)):rn.#jh.end()),this.supportMultipleDrawings){const t=rn.#jh,e=this._currentDrawId,i=t.getLastElement();s.addCommands({cmd:()=>{s.drawLayer.updateProperties(e,t.setLastElement(i))},undo:()=>{s.drawLayer.updateProperties(e,t.removeLastElement())},mustExec:!1,type:l.DRAW_STEP})}else this.endDrawing(!1)}static endDrawing(t){const s=this._currentParent;if(!s)return null;if(s.toggleDrawing(!0),s.cleanUndoStack(l.DRAW_STEP),!rn.#jh.isEmpty()){const{pageDimensions:[e,i],scale:n}=s,r=s.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,clipPathId:rn.#Hh,drawOutlines:rn.#jh.getOutlines(e*n,i*n,n,this._INNER_MARGIN),drawingOptions:rn.#zh,mustBeCommitted:!t});return this._cleanup(!0),r}return s.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,s,e,i,n,r,o){v("Not implemented")}static async deserialize(t,s,e){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:o}}=s.viewport,h=this.deserializeDraw(r,o,i,n,this._INNER_MARGIN,t,e),a=await super.deserialize(t,s,e);return a.createDrawingOptions(t),a.#Wh({drawOutlines:h}),a.#Vh(),a.onScaleChanging(),a.rotate(),a}serializeDraw(t){const[s,e]=this.pageTranslation,[i,n]=this.pageDimensions;return this._drawOutlines.serialize([s,e,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class on{static PRECISION=1e-4;focusOutline=null;toSVGPath(){v("Abstract method `toSVGPath` must be implemented.")}get box(){v("Abstract getter `box` must be implemented.")}serialize(t,s){v("Abstract method `serialize` must be implemented.")}get defaultSVGProperties(){v("Abstract getter `defaultSVGProperties` must be implemented.")}get defaultProperties(){return this.defaultSVGProperties}getFocusSVGProperties(t){return null}get focusMustRemoveSelfIntersections(){return!1}updateProperty(t,s){return null}updateParentDimensions(t,s){return null}serializeQuadPoints(t,s){return null}updateRotation(t){return{}}getPathResizingSVGProperties(t){return{}}getPathResizedSVGProperties(t){return{}}getPathTranslatedSVGProperties(t,s){return{}}static _rotateBox([t,s,e,i],n){switch(n){case 90:return[1-s-i,t,i,e];case 180:return[1-t-e,1-s-i,e,i];case 270:return[s,1-t-e,i,e]}return[t,s,e,i]}static _rescale(t,s,e,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=s+t[o]*i,r[o+1]=e+t[o+1]*n;return r}static _rescaleAndSwap(t,s,e,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=s+t[o+1]*i,r[o+1]=e+t[o]*n;return r}static _translate(t,s,e,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=s+t[n],i[n+1]=e+t[n+1];return i}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,s,e,i,n){switch(n){case 90:return[1-s/e,t/i];case 180:return[1-t/e,1-s/i];case 270:return[s/e,1-t/i];default:return[t/e,s/i]}}static createBezierPoints(t,s,e,i,n,r){return[(t+5*e)/6,(s+5*i)/6,(5*e+n)/6,(5*i+r)/6,(e+n)/2,(i+r)/2]}}class hn{#na;#ra=[];#oa;#ha;#aa=[];#la=new Float32Array(18);#ca;#ua;#da;#fa;#pa;#ga;#ma=[];static#Aa=8;static#wa=2;static#ba=hn.#Aa+hn.#wa;constructor(t,s,e,i,n,r,o=0){this.#na=e,this.#ga=n*i,this.#ha=r,this.#la.set([NaN,NaN,NaN,NaN,t,s],6),this.#oa=o,this.#fa=hn.#Aa*i,this.#da=hn.#ba*i,this.#pa=i,this.#ma.push(t,s)}isEmpty(){return isNaN(this.#la[8])}isCancellable(){return this.#ma.length<=10}removeLastElement(){return this.#la.fill(NaN),this.#aa.length=this.#ra.length=this.#ma.length=0,{path:{d:""}}}#ya(){const t=this.#la.subarray(4,6),s=this.#la.subarray(16,18),[e,i,n,r]=this.#na;return[(this.#ca+(t[0]-s[0])/2-e)/n,(this.#ua+(t[1]-s[1])/2-i)/r,(this.#ca+(s[0]-t[0])/2-e)/n,(this.#ua+(s[1]-t[1])/2-i)/r]}add(t,s){this.#ca=t,this.#ua=s;const[e,i,n,r]=this.#na;let[o,h,a,l]=this.#la.subarray(8,12);const c=t-a,u=s-l,d=Math.hypot(c,u);if(d<this.#da)return!1;const f=d-this.#fa,p=f/d,g=p*c,m=p*u;let A=o,w=h;o=a,h=l,a+=g,l+=m,this.#ma?.push(t,s);const b=-m/f*this.#ga,y=g/f*this.#ga;return this.#la.set(this.#la.subarray(2,8),0),this.#la.set([a+b,l+y],4),this.#la.set(this.#la.subarray(14,18),12),this.#la.set([a-b,l-y],16),isNaN(this.#la[6])?(0===this.#aa.length&&(this.#la.set([o+b,h+y],2),this.#aa.push(NaN,NaN,NaN,NaN,(o+b-e)/n,(h+y-i)/r),this.#la.set([o-b,h-y],14),this.#ra.push(NaN,NaN,NaN,NaN,(o-b-e)/n,(h-y-i)/r)),this.#la.set([A,w,o,h,a,l],6),!this.isEmpty()):(this.#la.set([A,w,o,h,a,l],6),Math.abs(Math.atan2(w-h,A-o)-Math.atan2(m,g))<Math.PI/2?([o,h,a,l]=this.#la.subarray(2,6),this.#aa.push(NaN,NaN,NaN,NaN,((o+a)/2-e)/n,((h+l)/2-i)/r),[o,h,A,w]=this.#la.subarray(14,18),this.#ra.push(NaN,NaN,NaN,NaN,((A+o)/2-e)/n,((w+h)/2-i)/r),!0):([A,w,o,h,a,l]=this.#la.subarray(0,6),this.#aa.push(((A+5*o)/6-e)/n,((w+5*h)/6-i)/r,((5*o+a)/6-e)/n,((5*h+l)/6-i)/r,((o+a)/2-e)/n,((h+l)/2-i)/r),[a,l,o,h,A,w]=this.#la.subarray(12,18),this.#ra.push(((A+5*o)/6-e)/n,((w+5*h)/6-i)/r,((5*o+a)/6-e)/n,((5*h+l)/6-i)/r,((o+a)/2-e)/n,((h+l)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#aa,s=this.#ra;if(isNaN(this.#la[6])&&!this.isEmpty())return this.#va();const e=[];e.push(`M${t[4]} ${t[5]}`);for(let s=6;s<t.length;s+=6)isNaN(t[s])?e.push(`L${t[s+4]} ${t[s+5]}`):e.push(`C${t[s]} ${t[s+1]} ${t[s+2]} ${t[s+3]} ${t[s+4]} ${t[s+5]}`);this.#xa(e);for(let t=s.length-6;t>=6;t-=6)isNaN(s[t])?e.push(`L${s[t+4]} ${s[t+5]}`):e.push(`C${s[t]} ${s[t+1]} ${s[t+2]} ${s[t+3]} ${s[t+4]} ${s[t+5]}`);return this.#Ma(e),e.join(" ")}#va(){const[t,s,e,i]=this.#na,[n,r,o,h]=this.#ya();return`M${(this.#la[2]-t)/e} ${(this.#la[3]-s)/i} L${(this.#la[4]-t)/e} ${(this.#la[5]-s)/i} L${n} ${r} L${o} ${h} L${(this.#la[16]-t)/e} ${(this.#la[17]-s)/i} L${(this.#la[14]-t)/e} ${(this.#la[15]-s)/i} Z`}#Ma(t){const s=this.#ra;t.push(`L${s[4]} ${s[5]} Z`)}#xa(t){const[s,e,i,n]=this.#na,r=this.#la.subarray(4,6),o=this.#la.subarray(16,18),[h,a,l,c]=this.#ya();t.push(`L${(r[0]-s)/i} ${(r[1]-e)/n} L${h} ${a} L${l} ${c} L${(o[0]-s)/i} ${(o[1]-e)/n}`)}newFreeDrawOutline(t,s,e,i,n,r){return new an(t,s,e,i,n,r)}getOutlines(){const t=this.#aa,s=this.#ra,e=this.#la,[i,n,r,o]=this.#na,h=new Float32Array((this.#ma?.length??0)+2);for(let t=0,s=h.length-2;t<s;t+=2)h[t]=(this.#ma[t]-i)/r,h[t+1]=(this.#ma[t+1]-n)/o;if(h[h.length-2]=(this.#ca-i)/r,h[h.length-1]=(this.#ua-n)/o,isNaN(e[6])&&!this.isEmpty())return this.#ka(h);const a=new Float32Array(this.#aa.length+24+this.#ra.length);let l=t.length;for(let s=0;s<l;s+=2)isNaN(t[s])?a[s]=a[s+1]=NaN:(a[s]=t[s],a[s+1]=t[s+1]);l=this.#Ca(a,l);for(let t=s.length-6;t>=6;t-=6)for(let e=0;e<6;e+=2)isNaN(s[t+e])?(a[l]=a[l+1]=NaN,l+=2):(a[l]=s[t+e],a[l+1]=s[t+e+1],l+=2);return this.#Sa(a,l),this.newFreeDrawOutline(a,h,this.#na,this.#pa,this.#oa,this.#ha)}#ka(t){const s=this.#la,[e,i,n,r]=this.#na,[o,h,a,l]=this.#ya(),c=new Float32Array(36);return c.set([NaN,NaN,NaN,NaN,(s[2]-e)/n,(s[3]-i)/r,NaN,NaN,NaN,NaN,(s[4]-e)/n,(s[5]-i)/r,NaN,NaN,NaN,NaN,o,h,NaN,NaN,NaN,NaN,a,l,NaN,NaN,NaN,NaN,(s[16]-e)/n,(s[17]-i)/r,NaN,NaN,NaN,NaN,(s[14]-e)/n,(s[15]-i)/r],0),this.newFreeDrawOutline(c,t,this.#na,this.#pa,this.#oa,this.#ha)}#Sa(t,s){const e=this.#ra;return t.set([NaN,NaN,NaN,NaN,e[4],e[5]],s),s+6}#Ca(t,s){const e=this.#la.subarray(4,6),i=this.#la.subarray(16,18),[n,r,o,h]=this.#na,[a,l,c,u]=this.#ya();return t.set([NaN,NaN,NaN,NaN,(e[0]-n)/o,(e[1]-r)/h,NaN,NaN,NaN,NaN,a,l,NaN,NaN,NaN,NaN,c,u,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],s),s+24}}class an extends on{#na;#Ta=new Float32Array(4);#oa;#ha;#ma;#pa;#Pa;constructor(t,s,e,i,n,r){super(),this.#Pa=t,this.#ma=s,this.#na=e,this.#pa=i,this.#oa=n,this.#ha=r,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#Ea(r);const[o,h,a,l]=this.#Ta;for(let s=0,e=t.length;s<e;s+=2)t[s]=(t[s]-o)/a,t[s+1]=(t[s+1]-h)/l;for(let t=0,e=s.length;t<e;t+=2)s[t]=(s[t]-o)/a,s[t+1]=(s[t+1]-h)/l}toSVGPath(){const t=[`M${this.#Pa[4]} ${this.#Pa[5]}`];for(let s=6,e=this.#Pa.length;s<e;s+=6)isNaN(this.#Pa[s])?t.push(`L${this.#Pa[s+4]} ${this.#Pa[s+5]}`):t.push(`C${this.#Pa[s]} ${this.#Pa[s+1]} ${this.#Pa[s+2]} ${this.#Pa[s+3]} ${this.#Pa[s+4]} ${this.#Pa[s+5]}`);return t.push("Z"),t.join(" ")}serialize([t,s,e,i],n){const r=e-t,o=i-s;let h,a;switch(n){case 0:h=on._rescale(this.#Pa,t,i,r,-o),a=on._rescale(this.#ma,t,i,r,-o);break;case 90:h=on._rescaleAndSwap(this.#Pa,t,s,r,o),a=on._rescaleAndSwap(this.#ma,t,s,r,o);break;case 180:h=on._rescale(this.#Pa,e,s,-r,o),a=on._rescale(this.#ma,e,s,-r,o);break;case 270:h=on._rescaleAndSwap(this.#Pa,e,i,-r,-o),a=on._rescaleAndSwap(this.#ma,e,i,-r,-o)}return{outline:Array.from(h),points:[Array.from(a)]}}#Ea(t){const e=this.#Pa;let i=e[4],n=e[5];const r=[i,n,i,n];let o=i,h=n,a=i,l=n;const c=t?Math.max:Math.min,u=new Float32Array(4);for(let t=6,d=e.length;t<d;t+=6){const d=e[t+4],f=e[t+5];isNaN(e[t])?(O.pointBoundingBox(d,f,r),h>f?(o=d,h=f):h===f&&(o=c(o,d)),l<f?(a=d,l=f):l===f&&(a=c(a,d))):(u.set(s,0),O.bezierBoundingBox(i,n,...e.slice(t,t+6),u),O.rectBoundingBox(...u,r),h>u[1]?(o=u[0],h=u[1]):h===u[1]&&(o=c(o,u[0])),l<u[3]?(a=u[2],l=u[3]):l===u[3]&&(a=c(a,u[2]))),i=d,n=f}const d=this.#Ta;d[0]=r[0]-this.#oa,d[1]=r[1]-this.#oa,d[2]=r[2]-r[0]+2*this.#oa,d[3]=r[3]-r[1]+2*this.#oa,this.firstPoint=[o,h],this.lastPoint=[a,l]}get box(){return this.#Ta}newOutliner(t,s,e,i,n,r,o=0){return new hn(t,s,e,i,n,r,o)}updateThickness(t){const s=this.getNewOutline(t);return this.#Pa=s.#Pa,this.#ma=s.#ma,this.#Ta.set(s.#Ta),this.firstPoint=s.firstPoint,this.lastPoint=s.lastPoint,this.#Ta}getNewOutline(t,s){const[e,i,n,r]=this.#Ta,[o,h,a,l]=this.#na,c=n*a,u=r*l,d=e*a+o,f=i*l+h,p=this.#ma,g=this.newOutliner(p[0]*c+d,p[1]*u+f,this.#na,this.#pa,t,this.#ha,s??this.#oa);for(let t=2,s=p.length;t<s;t+=2)g.add(p[t]*c+d,p[t+1]*u+f);return g.getOutlines()}}function ln(t){return{bbox:t.box,root:{viewBox:"0 0 1 1"},rootClass:{highlight:!0,free:t.isFree},path:{d:t.toSVGPath()}}}function cn(t,s){const{focusOutline:e}=t;return{bbox:on._rotateBox(e.box,s),root:{"data-main-rotation":s},rootClass:{highlightOutline:!0,free:t.isFree},path:{d:e.toSVGPath()}}}class un{#na;#Da;#Na;#Ia=[];#Fa=[];constructor(t,e=0,i=0,n=!0){const r=s.slice(),o=1e-4;for(const{x:s,y:i,width:n,height:h}of t){const t=Math.floor((s-e)/o)*o,a=Math.ceil((s+n+e)/o)*o,l=Math.floor((i-e)/o)*o,c=Math.ceil((i+h+e)/o)*o;this.#Ia.push([t,l,c,!0],[a,l,c,!1]),O.rectBoundingBox(t,l,a,c,r)}const h=r[2]-r[0]+2*i,a=r[3]-r[1]+2*i,l=r[0]-i,c=r[1]-i;let u=n?-1/0:1/0,d=1/0;const f=this.#Ia.at(n?-1:-2),p=[f[0],f[2]];for(const t of this.#Ia){const[s,e,i,r]=t;!r&&n?e<d?(d=e,u=s):e===d&&(u=Math.max(u,s)):r&&!n&&(e<d?(d=e,u=s):e===d&&(u=Math.min(u,s))),t[0]=(s-l)/h,t[1]=(e-c)/a,t[2]=(i-c)/a}this.#na=new Float32Array([l,c,h,a]),this.#Da=[u,d],this.#Na=p}getOutlines(){this.#Ia.sort(((t,s)=>t[0]-s[0]||t[1]-s[1]||t[2]-s[2]));const t=[];for(const s of this.#Ia)s[3]?(t.push(...this.#_a(s)),this.#Ra(s)):(this.#Oa(s),t.push(...this.#_a(s)));return this.#Ba(t)}#Ba(t){const s=[],e=new Set;for(const e of t){const[t,i,n]=e;s.push([t,i,e],[t,n,e])}s.sort(((t,s)=>t[1]-s[1]||t[0]-s[0]));for(let t=0,i=s.length;t<i;t+=2){const i=s[t][2],n=s[t+1][2];i.push(n),n.push(i),e.add(i),e.add(n)}const i=[];let n;for(;e.size>0;){const t=e.values().next().value;let[s,r,o,h,a]=t;e.delete(t);let l=s,c=r;for(n=[s,o],i.push(n);;){let t;if(e.has(h))t=h;else{if(!e.has(a))break;t=a}e.delete(t),[s,r,o,h,a]=t,l!==s&&(n.push(l,c,s,c===r?r:o),l=s),c=c===r?o:r}n.push(l,c)}return new dn(i,this.#na,this.#Da,this.#Na)}#$a(t){const s=this.#Fa;let e=0,i=s.length-1;for(;e<=i;){const n=e+i>>1,r=s[n][0];if(r===t)return n;r<t?e=n+1:i=n-1}return i+1}#Ra([,t,s]){const e=this.#$a(t);this.#Fa.splice(e,0,[t,s])}#Oa([,t,s]){const e=this.#$a(t);for(let i=e;i<this.#Fa.length;i++){const[e,n]=this.#Fa[i];if(e!==t)break;if(e===t&&n===s)return void this.#Fa.splice(i,1)}for(let i=e-1;i>=0;i--){const[e,n]=this.#Fa[i];if(e!==t)break;if(e===t&&n===s)return void this.#Fa.splice(i,1)}}#_a(t){const[s,e,i]=t,n=[[s,e,i]],r=this.#$a(i);for(let t=0;t<r;t++){const[e,i]=this.#Fa[t];for(let t=0,r=n.length;t<r;t++){const[,o,h]=n[t];if(!(i<=o||h<=e))if(o>=e)if(h>i)n[t][1]=i;else{if(1===r)return[];n.splice(t,1),t--,r--}else n[t][2]=e,h>i&&n.push([s,i,h])}}return n}}class dn extends on{#na;#La=null;#Ua;constructor(t,s,e,i){super(),this.#Ua=t,this.#na=s,this.firstPoint=e,this.lastPoint=i}static build(t,s){const e=new un(t,.001).getOutlines();return e.#La=t,e.focusOutline=new un(t,.0025,.001,s).getOutlines(),e}get isFree(){return!1}get defaultSVGProperties(){return ln(this)}getFocusSVGProperties(t){return cn(this,t)}updateRotation(t){return{root:{"data-main-rotation":t}}}serializeQuadPoints([t,s],[e,i]){const n=this.#La,r=new Float32Array(8*n.length);let o=0;for(const{x:h,y:a,width:l,height:c}of n){const n=h*e+t,u=(1-a)*i+s;r[o]=r[o+4]=n,r[o+1]=r[o+3]=u,r[o+2]=r[o+6]=n+l*e,r[o+5]=r[o+7]=u-c*i,o+=8}return r}toSVGPath(){const t=[];for(const s of this.#Ua){let[e,i]=s;t.push(`M${e} ${i}`);for(let n=2;n<s.length;n+=2){const r=s[n],o=s[n+1];r===e?(t.push(`V${o}`),i=o):o===i&&(t.push(`H${r}`),e=r)}t.push("Z")}return t.join(" ")}serialize([t,s,e,i],n){const r=[],o=e-t,h=i-s;for(const s of this.#Ua){const e=new Array(s.length);for(let n=0;n<s.length;n+=2)e[n]=t+s[n]*o,e[n+1]=i-s[n+1]*h;r.push(e)}return r}get box(){return this.#na}}class fn extends hn{newFreeDrawOutline(t,s,e,i,n,r){return new gn(t,s,e,i,n,r)}}class pn{#ja;#ga;constructor(t,s,e,i,n,r,o){this.#ja=new fn(t,s,e,i,n,r,o),this.#ga=n}add(t,s){return this.#ja.add(t,s)?{path:{d:this.#ja.toSVGPath()}}:null}addPoints(t){let s=!1;for(let e=0,i=t.length;e<i;e+=2)s=this.#ja.add(t[e],t[e+1])||s;return s?{path:{d:this.#ja.toSVGPath()}}:null}end(t,s){return void 0===t?null:this.add(t,s)}isEmpty(){return this.#ja.isEmpty()}isCancellable(){return this.#ja.isCancellable()}removeLastElement(){return this.#ja.removeLastElement()}updateProperty(t,s){return null}getOutlines(){const t=this.#ja.getOutlines();return t.buildFocusOutline(2*this.#ga),t}get defaultSVGProperties(){return{bbox:[0,0,1,1],root:{viewBox:"0 0 1 1"},rootClass:{highlight:!0,free:!0},path:{d:this.#ja.toSVGPath()}}}}class gn extends an{static#Ga=1.5;newOutliner(t,s,e,i,n,r,o=0){return new fn(t,s,e,i,n,r,o)}get isFree(){return!0}buildFocusOutline(t){this.focusOutline=this.getNewOutline(t/2+gn.#Ga,.0025)}get defaultSVGProperties(){return ln(this)}getFocusSVGProperties(t){return cn(this,t)}get focusMustRemoveSelfIntersections(){return!0}updateRotation(t){return{root:{"data-main-rotation":t}}}updateProperty(t,s){if("thickness"!==t)return null;const e=this.updateThickness(s/2);return this.buildFocusOutline(s),e}getPathResizedSVGProperties(){return{path:{d:this.toSVGPath()}}}}class mn extends nn{constructor(t=null){super(),super.updateProperties(t)}updateSVGProperty(t,s){"thickness"!==t&&super.updateSVGProperty(t,s)}clone(){const t=new mn;return t.updateAll(this),t}}class An extends rn{#za=null;#Ha=0;#Wa=null;#Va=0;#Xa="";#bs="";static _DEFAULT_OPACITY=1;static _DEFAULT_THICKNESS=12;static _defaultDrawingOptions=null;static _type="highlight";static _editorType=a.HIGHLIGHT;static get _keyboardManager(){const t=An.prototype;return S(this,"_keyboardManager",new Rt([[["ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.#za=t.anchorNode||null,this.#Ha=t.anchorOffset||0,this.#Wa=t.focusNode||null,this.#Va=t.focusOffset||0,this.#Xa=t.methodOfCreation||(this._drawOutlines?.isFree?"main_toolbar":""),this.#bs=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",this.rotate()}static initialize(t,s){Ht.initialize(t,s),this._defaultDrawingOptions||=new mn({fill:s.highlightColors?.values().next().value||"#fff066","fill-opacity":An._DEFAULT_OPACITY,thickness:An._DEFAULT_THICKNESS})}static getDefaultDrawingOptions(t){const s=this._defaultDrawingOptions.clone();return s.updateProperties(t),s}static get typesMap(){return S(this,"typesMap",new Map([[l.HIGHLIGHT_COLOR,"fill"],[l.HIGHLIGHT_THICKNESS,"thickness"]]))}static get isDrawer(){return!1}static get _hasClipPath(){return!0}static get _hasDrawClass(){return!1}_addOutlines(t){const{boxes:s,drawOutlines:e}=t;(s||e)&&(this._drawingOptions||=t.drawingOptions||An.getDefaultDrawingOptions(),s&&(t={...t,drawOutlines:dn.build(s,"ltr"===this._uiManager.direction)}),super._addOutlines(t))}get colorType(){return l.HIGHLIGHT_COLOR}get color(){return this._drawingOptions.fill}get opacity(){return this._drawingOptions["fill-opacity"]}get _opacityName(){return"fill-opacity"}get _drawRotation(){return this._drawOutlines?.isFree?this.rotation:0}get isResizable(){return!1}get _mustBeDisabledOnCommit(){return!1}get _mustFixPosition(){return!this._drawOutlines?.isFree}get telemetryInitialData(){return{action:"added",type:this._drawOutlines.isFree?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this._drawingOptions.thickness,methodOfCreation:this.#Xa}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}translateInPage(t,s){}get toolbarPosition(){return this.#Ya(this._drawOutlines.focusOutline.lastPoint)}get commentButtonPosition(){return this.#Ya(this._drawOutlines.firstPoint)}#Ya([t,s]){const[e,i,n,r]=this._drawOutlines.box;return[(t-e)/n,(s-i)/r]}updateParams(t,s){switch(t){case l.HIGHLIGHT_COLOR:this._updateColorAndOpacity(s,An._DEFAULT_OPACITY,t),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(s)},!0);break;case l.HIGHLIGHT_THICKNESS:super.updateParams(t,s),this._reportTelemetry({action:"thickness_changed",thickness:s},!0)}}get propertiesToUpdate(){const t=super.propertiesToUpdate;return t.push([l.HIGHLIGHT_FREE,this._drawOutlines.isFree]),t}get toolbarButtons(){return this._uiManager.highlightColors?(this._colorPicker=new mi({editor:this}),[["colorPicker",this._colorPicker]]):super.toolbarButtons}fixAndSetPosition(){return super.fixAndSetPosition(this._drawRotation)}getRect(t,s){return super.getRect(t,s,this._drawRotation)}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this._reportTelemetry({action:"deleted"}),super.remove()}render(){if(this.div)return this.div;const t=super.render();return this.#bs&&(t.setAttribute("aria-label",this.#bs),t.setAttribute("role","mark")),this._drawOutlines.isFree?t.classList.add("free"):t.addEventListener("keydown",this.#Ka.bind(this),{signal:this._uiManager._signal}),this.enableEditing(),t}#Ka(t){An._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#qa(!0);break;case 1:case 3:this.#qa(!1)}}#qa(t){if(!this.#za)return;const s=window.getSelection();t?s.setPosition(this.#za,this.#Ha):s.setPosition(this.#Wa,this.#Va)}unselect(){super.unselect(),this._drawOutlines.isFree||this.#qa(!1)}static createDrawerInstance({x:t,y:s,box:e,parent:i,isLTR:n}){return new pn(t,s,e,i.scale,this._defaultDrawingOptions.thickness/2,n,.001)}static _getDrawingTarget(t,{target:s}){return s.closest(".textLayer")}static _getPointerCoords({x:t,y:s}){return[t,s]}static _addDrawingListeners(t,s){t.classList.add("free"),s.addEventListener("abort",(()=>t.classList.remove("free")),{once:!0}),window.addEventListener("blur",(()=>this._endDraw(null)),{signal:s}),window.addEventListener("pointerdown",ht,{capture:!0,passive:!1,signal:s})}static _endDrawingSession(t=!1){return this.endDrawing(t)}createDrawingOptions({color:t,opacity:s,thickness:e}){const{_defaultDrawingOptions:i,_DEFAULT_OPACITY:n}=An;this._drawingOptions=An.getDefaultDrawingOptions({fill:O.makeHexColor(...t),"fill-opacity":s||n,thickness:e||i.thickness})}static deserializeDraw(t,s,e,i,n,r,o){const{quadPoints:h}=r;if(h){const n=[];for(let r=0,o=h.length;r<o;r+=8)n.push({x:(h[r]-t)/e,y:1-(h[r+1]-s)/i,width:(h[r+2]-h[r])/e,height:(h[r+1]-h[r+5])/i});return dn.build(n,"ltr"===o.direction)}const a=r.thickness||this._defaultDrawingOptions.thickness,l=(r.inkLists||r.outlines.points)[0],c=new fn(l[0]-t,i-(l[1]-s),[0,0,e,i],1,a/2,!0,.001);for(let e=0,n=l.length;e<n;e+=2)c.add(l[e]-t,i-(l[e+1]-s));const u=c.getOutlines();return u.buildFocusOutline(a),u}static async deserialize(t,s,e){let i=null;if(t instanceof Xi){const{data:{quadPoints:s,rect:e,rotation:n,id:r,color:o,opacity:h,popupRef:l,richText:c,contentsObj:u,creationDate:d,modificationDate:f},parent:{page:{pageNumber:p}}}=t;i=t={annotationType:a.HIGHLIGHT,color:Array.from(o),opacity:h,quadPoints:s,pageIndex:p-1,rect:e.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:c,comment:u?.str||null,creationDate:d,modificationDate:f}}else if(t instanceof Vi){const{data:{inkLists:s,rect:e,rotation:n,id:r,color:o,borderStyle:{rawWidth:h},popupRef:l,richText:c,contentsObj:u,creationDate:d,modificationDate:f},parent:{page:{pageNumber:p}}}=t;i=t={annotationType:a.HIGHLIGHT,color:Array.from(o),thickness:h,inkLists:s,pageIndex:p-1,rect:e.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:c,comment:u?.str||null,creationDate:d,modificationDate:f}}const n=await super.deserialize(t,s,e);return n._initialData=i,t.comment&&n.setCommentData(t),n}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const s=super.serialize(t);return Object.assign(s,{color:Ht._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),opacity:this.opacity,thickness:this._drawingOptions.thickness,quadPoints:this._drawOutlines.serializeQuadPoints(this.pageTranslation,this.pageDimensions),outlines:this._drawOutlines.serialize(s.rect,this._drawRotation)}),this.addComment(s),this.annotationElementId&&!this.#Bh(s)?null:(s.id=this.annotationElementId,s)}#Bh(t){const{color:s}=this._initialData;return this.hasEditedComment||t.color.some(((t,e)=>t!==s[e]))}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}class wn{#la=new Float64Array(6);#Qa=new Float64Array(2);#oh;#Ja;#pr;#ga;#ma;#Za="";#tl=0;#Ua=new bn;#sl;#el;constructor(t,s,e,i,n,r){this.#sl=e,this.#el=i,this.#pr=n,this.#ga=r,[t,s]=this.#il(t,s);const o=this.#oh=[NaN,NaN,NaN,NaN,t,s];this.#ma=[t,s],this.#Ja=[{line:o,points:this.#ma}],this.#la.set(o,0),this.#Qa.set([t,s],0)}updateProperty(t,s){"stroke-width"===t&&(this.#ga=s)}#il(t,s){return on._normalizePoint(t,s,this.#sl,this.#el,this.#pr)}isEmpty(){return!this.#Ja?.length}isCancellable(){return this.#ma.length<=10}add(t,s){return this.#nl(t,s)&&this.toSVGPath(),{path:{d:this.#rl()}}}addPoints(t){let s=!1;for(let e=0,i=t.length;e<i;e+=2)this.#nl(t[e],t[e+1])&&(s=!0,this.#ma.length<=6&&(this.toSVGPath(),s=!1));return s&&this.toSVGPath(),{path:{d:this.#rl()}}}#nl(t,s){[t,s]=this.#il(t,s),this.#Qa.set([t,s],0);const[e,i,n,r]=this.#la.subarray(2,6);return!(Math.hypot(this.#sl*(t-n),this.#el*(s-r))<=2||(this.#ma.push(t,s),isNaN(e)?(this.#la.set([n,r,t,s],2),this.#oh.push(NaN,NaN,NaN,NaN,t,s),0):(isNaN(this.#la[0])&&this.#oh.splice(6,6),this.#la.set([e,i,n,r,t,s],0),this.#oh.push(...on.createBezierPoints(e,i,n,r,t,s)),0)))}end(t,s){return void 0!==t&&this.#nl(t,s)||2===this.#ma.length?{path:{d:this.toSVGPath()}}:{path:{d:this.#Za}}}startNew(t,s,e,i,n){this.#sl=e,this.#el=i,this.#pr=n,[t,s]=this.#il(t,s);const r=this.#oh=[NaN,NaN,NaN,NaN,t,s];this.#ma=[t,s],this.#Qa.set([t,s],0);const o=this.#Ja.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#Ja.push({line:r,points:this.#ma}),this.#la.set(r,0),this.#tl=0,this.toSVGPath(),null}getLastElement(){return this.#Ja.at(-1)}setLastElement(t){return this.#Ja?(this.#Ja.push(t),this.#oh=t.line,this.#ma=t.points,this.#tl=0,{path:{d:this.toSVGPath()}}):this.#Ua.setLastElement(t)}removeLastElement(){if(!this.#Ja)return this.#Ua.removeLastElement();this.#Ja.pop(),this.#Za="";for(let t=0,s=this.#Ja.length;t<s;t++){const{line:s,points:e}=this.#Ja[t];this.#oh=s,this.#ma=e,this.#tl=0,this.toSVGPath()}return{path:{d:this.#Za}}}#rl(){const t=on.svgRound(this.#Qa[0]),s=on.svgRound(this.#Qa[1]);if(2===this.#ma.length){const e=on.svgRound(this.#oh[4]),i=on.svgRound(this.#oh[5]);return`${this.#Za} M ${e} ${i} L ${t} ${s}`}return`${this.#Za} L ${t} ${s}`}toSVGPath(){const t=on.svgRound(this.#oh[4]),s=on.svgRound(this.#oh[5]);if(2===this.#ma.length)return this.#Za=`${this.#Za} M ${t} ${s} Z`,this.#Za;if(this.#ma.length<=6){const e=this.#Za.lastIndexOf("M");this.#Za=`${this.#Za.slice(0,e)} M ${t} ${s}`,this.#tl=6}if(4===this.#ma.length){const t=on.svgRound(this.#oh[10]),s=on.svgRound(this.#oh[11]);return this.#Za=`${this.#Za} L ${t} ${s}`,this.#tl=12,this.#Za}const e=[];0===this.#tl&&(e.push(`M ${t} ${s}`),this.#tl=6);for(let t=this.#tl,s=this.#oh.length;t<s;t+=6){const[s,i,n,r,o,h]=this.#oh.slice(t,t+6).map(on.svgRound);e.push(`C${s} ${i} ${n} ${r} ${o} ${h}`)}return this.#Za+=e.join(" "),this.#tl=this.#oh.length,this.#Za}getOutlines(t,s,e,i){const n=this.#Ja.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#Ua.build(this.#Ja,t,s,e,this.#pr,this.#ga,i),this.#la=null,this.#oh=null,this.#Ja=null,this.#Za=null,this.#Ua}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class bn extends on{#Ta;#ol=0;#oa;#Ja;#sl;#el;#hl;#pr;#ga;build(t,s,e,i,n,r,o){this.#sl=s,this.#el=e,this.#hl=i,this.#pr=n,this.#ga=r,this.#oa=o??0,this.#Ja=t,this.#al()}get thickness(){return this.#ga}setLastElement(t){return this.#Ja.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#Ja.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:s}of this.#Ja)if(t.push(`M${on.svgRound(s[4])} ${on.svgRound(s[5])}`),6!==s.length)if(12===s.length&&isNaN(s[6]))t.push(`L${on.svgRound(s[10])} ${on.svgRound(s[11])}`);else for(let e=6,i=s.length;e<i;e+=6){const[i,n,r,o,h,a]=s.subarray(e,e+6).map(on.svgRound);t.push(`C${i} ${n} ${r} ${o} ${h} ${a}`)}else t.push("Z");return t.join("")}serialize([t,s,e,i],n){const r=[],o=[],[h,a,l,c]=this.#ll();let u,d,f,p,g,m,A,w,b;switch(this.#pr){case 0:b=on._rescale,u=t,d=s+i,f=e,p=-i,g=t+h*e,m=s+(1-a-c)*i,A=t+(h+l)*e,w=s+(1-a)*i;break;case 90:b=on._rescaleAndSwap,u=t,d=s,f=e,p=i,g=t+a*e,m=s+h*i,A=t+(a+c)*e,w=s+(h+l)*i;break;case 180:b=on._rescale,u=t+e,d=s,f=-e,p=i,g=t+(1-h-l)*e,m=s+a*i,A=t+(1-h)*e,w=s+(a+c)*i;break;case 270:b=on._rescaleAndSwap,u=t+e,d=s+i,f=-e,p=-i,g=t+(1-a-c)*e,m=s+(1-h-l)*i,A=t+(1-a)*e,w=s+(1-h)*i}for(const{line:t,points:s}of this.#Ja)r.push(b(t,u,d,f,p,n?new Array(t.length):null)),o.push(b(s,u,d,f,p,n?new Array(s.length):null));return{lines:r,points:o,rect:[g,m,A,w]}}static deserialize(t,s,e,i,n,{paths:{lines:r,points:o},rotation:h,thickness:a}){const l=[];let c,u,d,f,p;switch(h){case 0:p=on._rescale,c=-t/e,u=s/i+1,d=1/e,f=-1/i;break;case 90:p=on._rescaleAndSwap,c=-s/i,u=-t/e,d=1/i,f=1/e;break;case 180:p=on._rescale,c=t/e+1,u=-s/i,d=-1/e,f=1/i;break;case 270:p=on._rescaleAndSwap,c=s/i+1,u=t/e+1,d=-1/i,f=-1/e}if(!r){r=[];for(const t of o){const s=t.length;if(2===s){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===s){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const e=new Float32Array(3*(s-2));r.push(e);let[i,n,o,h]=t.subarray(0,4);e.set([NaN,NaN,NaN,NaN,i,n],0);for(let r=4;r<s;r+=2){const s=t[r],a=t[r+1];e.set(on.createBezierPoints(i,n,o,h,s,a),3*(r-2)),[i,n,o,h]=[o,h,s,a]}}}for(let t=0,s=r.length;t<s;t++)l.push({line:p(r[t].map((t=>t??NaN)),c,u,d,f),points:p(o[t].map((t=>t??NaN)),c,u,d,f)});const g=new this.prototype.constructor;return g.build(l,e,i,1,h,a,n),g}#cl(t=this.#ga){const s=this.#oa+t/2*this.#hl;return this.#pr%180==0?[s/this.#sl,s/this.#el]:[s/this.#el,s/this.#sl]}#ll(){const[t,s,e,i]=this.#Ta,[n,r]=this.#cl(0);return[t+n,s+r,e-2*n,i-2*r]}#al(){const t=this.#Ta=e.slice();for(const{line:s}of this.#Ja){if(s.length<=12){for(let e=4,i=s.length;e<i;e+=6)O.pointBoundingBox(s[e],s[e+1],t);continue}let e=s[4],i=s[5];for(let n=6,r=s.length;n<r;n+=6){const[r,o,h,a,l,c]=s.subarray(n,n+6);O.bezierBoundingBox(e,i,r,o,h,a,l,c,t),e=l,i=c}}const[s,i]=this.#cl();t[0]=W(t[0]-s,0,1),t[1]=W(t[1]-i,0,1),t[2]=W(t[2]+s,0,1),t[3]=W(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#Ta}updateProperty(t,s){return"stroke-width"===t?this.#ul(s):null}#ul(t){const[s,e]=this.#cl();this.#ga=t;const[i,n]=this.#cl(),[r,o]=[i-s,n-e],h=this.#Ta;return h[0]-=r,h[1]-=o,h[2]+=2*r,h[3]+=2*o,h}updateParentDimensions([t,s],e){const[i,n]=this.#cl();this.#sl=t,this.#el=s,this.#hl=e;const[r,o]=this.#cl(),h=r-i,a=o-n,l=this.#Ta;return l[0]-=h,l[1]-=a,l[2]+=2*h,l[3]+=2*a,l}updateRotation(t){return this.#ol=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#Ta.map(on.svgRound).join(" ")}get defaultProperties(){const[t,s]=this.#Ta;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${on.svgRound(t)} ${on.svgRound(s)}`}}}get rotationTransform(){const[,,t,s]=this.#Ta;let e=0,i=0,n=0,r=0,o=0,h=0;switch(this.#ol){case 90:i=s/t,n=-t/s,o=t;break;case 180:e=-1,r=-1,o=t,h=s;break;case 270:i=-s/t,n=t/s,h=s;break;default:return""}return`matrix(${e} ${i} ${n} ${r} ${on.svgRound(o)} ${on.svgRound(h)})`}getPathResizingSVGProperties([t,s,e,i]){const[n,r]=this.#cl(),[o,h,a,l]=this.#Ta;if(Math.abs(a-n)<=on.PRECISION||Math.abs(l-r)<=on.PRECISION){const n=t+e/2-(o+a/2),r=s+i/2-(h+l/2);return{path:{"transform-origin":`${on.svgRound(t)} ${on.svgRound(s)}`,transform:`${this.rotationTransform} translate(${n} ${r})`}}}const c=(e-2*n)/(a-2*n),u=(i-2*r)/(l-2*r),d=a/e,f=l/i;return{path:{"transform-origin":`${on.svgRound(o)} ${on.svgRound(h)}`,transform:`${this.rotationTransform} scale(${d} ${f}) translate(${on.svgRound(n)} ${on.svgRound(r)}) scale(${c} ${u}) translate(${on.svgRound(-n)} ${on.svgRound(-r)})`}}}getPathResizedSVGProperties([t,s,e,i]){const[n,r]=this.#cl(),o=this.#Ta,[h,a,l,c]=o;if(o[0]=t,o[1]=s,o[2]=e,o[3]=i,Math.abs(l-n)<=on.PRECISION||Math.abs(c-r)<=on.PRECISION){const n=t+e/2-(h+l/2),r=s+i/2-(a+c/2);for(const{line:t,points:s}of this.#Ja)on._translate(t,n,r,t),on._translate(s,n,r,s);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${on.svgRound(t)} ${on.svgRound(s)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const u=(e-2*n)/(l-2*n),d=(i-2*r)/(c-2*r),f=-u*(h+n)+t+n,p=-d*(a+r)+s+r;if(1!==u||1!==d||0!==f||0!==p)for(const{line:t,points:s}of this.#Ja)on._rescale(t,f,p,u,d,t),on._rescale(s,f,p,u,d,s);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${on.svgRound(t)} ${on.svgRound(s)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,s],e){const[i,n]=e,r=this.#Ta,o=t-r[0],h=s-r[1];if(this.#sl===i&&this.#el===n)for(const{line:t,points:s}of this.#Ja)on._translate(t,o,h,t),on._translate(s,o,h,s);else{const t=this.#sl/i,s=this.#el/n;this.#sl=i,this.#el=n;for(const{line:e,points:i}of this.#Ja)on._rescale(e,o,h,t,s,e),on._rescale(i,o,h,t,s,i);r[2]*=t,r[3]*=s}return r[0]=t,r[1]=s,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${on.svgRound(t)} ${on.svgRound(s)}`}}}get defaultSVGProperties(){const t=this.#Ta;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${on.svgRound(t[0])} ${on.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class yn extends nn{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:Ht._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,s){"stroke-width"===t&&(s??=this["stroke-width"],s*=this._viewParameters.realScale),super.updateSVGProperty(t,s)}clone(){const t=new yn(this._viewParameters);return t.updateAll(this),t}}class vn extends rn{static _type="ink";static _editorType=a.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,s){Ht.initialize(t,s),this._defaultDrawingOptions=new yn(s.viewParameters)}static getDefaultDrawingOptions(t){const s=this._defaultDrawingOptions.clone();return s.updateProperties(t),s}static get supportMultipleDrawings(){return!0}static get typesMap(){return S(this,"typesMap",new Map([[l.INK_THICKNESS,"stroke-width"],[l.INK_COLOR,"stroke"],[l.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance({x:t,y:s,box:[,,e,i],rotation:n}){return new wn(t,s,e,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,s,e,i,n,r){return bn.deserialize(t,s,e,i,n,r)}static async deserialize(t,s,e){let i=null;if(t instanceof Vi){const{data:{inkLists:s,rect:e,rotation:n,id:r,color:o,opacity:h,borderStyle:{rawWidth:l},popupRef:c,richText:u,contentsObj:d,creationDate:f,modificationDate:p},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:a.INK,color:Array.from(o),thickness:l,opacity:h,paths:{points:s},boxes:null,pageIndex:g-1,rect:e.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:c,richText:u,comment:d?.str||null,creationDate:f,modificationDate:p}}const n=await super.deserialize(t,s,e);return n._initialData=i,t.comment&&n.setCommentData(t),n}get toolbarButtons(){return this._colorPicker||=new Ai(this),[["colorPicker",this._colorPicker]]}get colorType(){return l.INK_COLOR}get colorAndOpacityType(){return l.INK_COLOR_AND_OPACITY}get opacityType(){return l.INK_OPACITY}updateParams(t,s){t!==l.INK_COLOR_AND_OPACITY?super.updateParams(t,s):this._updateColorAndOpacity(s.color,s.opacity)}static updateDefaultParams(t,s){if(t===l.INK_COLOR_AND_OPACITY)return super.updateDefaultParams(l.INK_COLOR,s.color),void super.updateDefaultParams(l.INK_OPACITY,s.opacity);super.updateDefaultParams(t,s)}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:s,parent:e}=this;s.updateSVGProperty("stroke-width"),e.drawLayer.updateProperties(t,s.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:s,opacity:e}){this._drawingOptions=vn.getDefaultDrawingOptions({stroke:O.makeHexColor(...t),"stroke-width":s,"stroke-opacity":e})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:s,points:e}=this.serializeDraw(t),{_drawingOptions:{stroke:i,"stroke-opacity":n,"stroke-width":r}}=this,o=Object.assign(super.serialize(t),{color:Ht._colorManager.convert(i),opacity:n,thickness:r,paths:{lines:s,points:e}});return this.addComment(o),t?(o.isCopy=!0,o):this.annotationElementId&&!this.#Bh(o)?null:(o.id=this.annotationElementId,o)}#Bh(t){const{color:s,thickness:e,opacity:i,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some(((t,e)=>t!==s[e]))||t.thickness!==e||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:s,rect:e}=this.serializeDraw(!1);return t.updateEdited({rect:e,thickness:this._drawingOptions["stroke-width"],points:s,popup:this.comment}),null}}class xn extends bn{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}class Mn{static#dl={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#fl(t,s,e,i){return i-=s,0==(e-=t)?i>0?0:4:1===e?i+6:2-i}static#pl=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#gl(t,s,e,i,n,r,o){const h=this.#fl(e,i,n,r);for(let n=0;n<8;n++){const r=(-n+h-o+16)%8;if(0!==t[(e+this.#pl[2*r])*s+(i+this.#pl[2*r+1])])return r}return-1}static#ml(t,s,e,i,n,r,o){const h=this.#fl(e,i,n,r);for(let n=0;n<8;n++){const r=(n+h+o+16)%8;if(0!==t[(e+this.#pl[2*r])*s+(i+this.#pl[2*r+1])])return r}return-1}static#Al(t,s,e,i){const n=t.length,r=new Int32Array(n);for(let s=0;s<n;s++)r[s]=t[s]<=i?1:0;for(let t=1;t<e-1;t++)r[t*s]=r[t*s+s-1]=0;for(let t=0;t<s;t++)r[t]=r[s*e-1-t]=0;let o,h=1;const a=[];for(let t=1;t<e-1;t++){o=1;for(let e=1;e<s-1;e++){const i=t*s+e,n=r[i];if(0===n)continue;let l=t,c=e;if(1===n&&0===r[i-1])h+=1,c-=1;else{if(!(n>=1&&0===r[i+1])){1!==n&&(o=Math.abs(n));continue}h+=1,c+=1,n>1&&(o=n)}const u=[e,t],d=c===e+1,f={isHole:d,points:u,id:h,parent:0};let p;a.push(f);for(const t of a)if(t.id===o){p=t;break}f.parent=p?p.isHole?d?p.parent:o:d?o:p.parent:d?o:0;const g=this.#gl(r,s,t,e,l,c,0);if(-1===g){r[i]=-h,1!==r[i]&&(o=Math.abs(r[i]));continue}let m=this.#pl[2*g],A=this.#pl[2*g+1];const w=t+m,b=e+A;l=w,c=b;let y=t,v=e;for(;;){const n=this.#ml(r,s,y,v,l,c,1);m=this.#pl[2*n],A=this.#pl[2*n+1];const a=y+m,d=v+A;u.push(d,a);const f=y*s+v;if(0===r[f+1]?r[f]=-h:1===r[f]&&(r[f]=h),a===t&&d===e&&y===w&&v===b){1!==r[i]&&(o=Math.abs(r[i]));break}l=y,c=v,y=a,v=d}}}return a}static#wl(t,s,e,i){if(e-s<=4){for(let n=s;n<e-2;n+=2)i.push(t[n],t[n+1]);return}const n=t[s],r=t[s+1],o=t[e-4]-n,h=t[e-3]-r,a=Math.hypot(o,h),l=o/a,c=h/a,u=l*r-c*n,d=1/a,f=Math.atan(h/o),p=Math.cos(f),g=Math.sin(f),m=d*(Math.abs(p)+Math.abs(g)),A=d*(1-m+m**2),w=Math.max(Math.atan(Math.abs(g+p)*A),Math.atan(Math.abs(g-p)*A));let b=0,y=s;for(let i=s+2;i<e-2;i+=2){const s=Math.abs(u-l*t[i+1]+c*t[i]);s>b&&(y=i,b=s)}b>(a*w)**2?(this.#wl(t,s,y+2,i),this.#wl(t,y,e,i)):i.push(n,r)}static#bl(t){const s=[],e=t.length;return this.#wl(t,0,e,s),s.push(t[e-2],t[e-1]),s.length<=4?null:s}static#yl(t,s,e,i,n,r){const o=new Float32Array(r**2),h=-2*i**2,a=r>>1;for(let t=0;t<r;t++){const s=(t-a)**2;for(let e=0;e<r;e++)o[t*r+e]=Math.exp((s+(e-a)**2)/h)}const l=new Float32Array(256),c=-2*n**2;for(let t=0;t<256;t++)l[t]=Math.exp(t**2/c);const u=new Uint8Array(t.length),d=new Uint32Array(256);for(let i=0;i<e;i++)for(let n=0;n<s;n++){const h=i*s+n,c=t[h];let f=0,p=0;for(let h=0;h<r;h++){const u=i+h-a;if(!(u<0||u>=e))for(let e=0;e<r;e++){const i=n+e-a;if(i<0||i>=s)continue;const d=t[u*s+i],g=o[h*r+e]*l[Math.abs(d-c)];f+=d*g,p+=g}}d[u[h]=Math.round(f/p)]++}return[u,d]}static#vl(t){const s=new Uint32Array(256);for(const e of t)s[e]++;return s}static#xl(t){const s=new Uint8ClampedArray(t.length>>2);let e=-1/0,i=1/0;for(let n=0,r=s.length;n<r;n++){const r=s[n]=t[n<<2];e=Math.max(e,r),i=Math.min(i,r)}const n=255/(e-i);for(let t=0,e=s.length;t<e;t++)s[t]=(s[t]-i)*n;return s}static#Ml(t){let s,e=-1/0,i=-1/0;const n=t.findIndex((t=>0!==t));let r=n,o=n;for(s=n;s<256;s++){const n=t[s];n>e&&(s-r>i&&(i=s-r,o=s-1),e=n,r=s)}for(s=o-1;s>=0&&!(t[s]>t[s+1]);s--);return s}static#kl(t){const s=t,{width:e,height:i}=t,{maxDim:n}=this.#dl;let r=e,o=i;if(e>n||i>n){let h=e,a=i,l=Math.log2(Math.max(e,i)/n);const c=Math.floor(l);l=l===c?c-1:c;for(let e=0;e<l;e++){r=Math.ceil(h/2),o=Math.ceil(a/2);const e=new OffscreenCanvas(r,o);e.getContext("2d").drawImage(t,0,0,h,a,0,0,r,o),h=r,a=o,t!==s&&t.close(),t=e.transferToImageBitmap()}const u=Math.min(n/r,n/o);r=Math.round(r*u),o=Math.round(o*u)}const h=new OffscreenCanvas(r,o).getContext("2d",{willReadFrequently:!0});h.fillStyle="white",h.fillRect(0,0,r,o),h.filter="grayscale(1)",h.drawImage(t,0,0,t.width,t.height,0,0,r,o);const a=h.getImageData(0,0,r,o).data;return[this.#xl(a),r,o]}static extractContoursFromText(t,{fontFamily:s,fontStyle:e,fontWeight:i},n,r,o,h){let a=new OffscreenCanvas(1,1),l=a.getContext("2d",{alpha:!1});const c=l.font=`${e} ${i} 200px ${s}`,{actualBoundingBoxLeft:u,actualBoundingBoxRight:d,actualBoundingBoxAscent:f,actualBoundingBoxDescent:p,fontBoundingBoxAscent:g,fontBoundingBoxDescent:m,width:A}=l.measureText(t),w=Math.ceil(1.5*Math.max(Math.abs(u)+Math.abs(d)||0,A)),b=Math.ceil(1.5*Math.max(Math.abs(f)+Math.abs(p)||200,Math.abs(g)+Math.abs(m)||200));a=new OffscreenCanvas(w,b),l=a.getContext("2d",{alpha:!0,willReadFrequently:!0}),l.font=c,l.filter="grayscale(1)",l.fillStyle="white",l.fillRect(0,0,w,b),l.fillStyle="black",l.fillText(t,.5*w/2,1.5*b/2);const y=this.#xl(l.getImageData(0,0,w,b).data),v=this.#vl(y),x=this.#Ml(v),M=this.#Al(y,w,b,x);return this.processDrawnLines({lines:{curves:M,width:w,height:b},pageWidth:n,pageHeight:r,rotation:o,innerMargin:h,mustSmooth:!0,areContours:!0})}static process(t,s,e,i,n){const[r,o,h]=this.#kl(t),[a,l]=this.#yl(r,o,h,Math.hypot(o,h)*this.#dl.sigmaSFactor,this.#dl.sigmaR,this.#dl.kernelSize),c=this.#Ml(l),u=this.#Al(a,o,h,c);return this.processDrawnLines({lines:{curves:u,width:o,height:h},pageWidth:s,pageHeight:e,rotation:i,innerMargin:n,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:s,pageHeight:e,rotation:i,innerMargin:n,mustSmooth:r,areContours:o}){i%180!=0&&([s,e]=[e,s]);const{curves:h,width:a,height:l}=t,c=t.thickness??0,u=[],d=Math.min(s/a,e/l),f=d/s,p=d/e,g=[];for(const{points:t}of h){const s=r?this.#bl(t):t;if(!s)continue;g.push(s);const e=s.length,i=new Float32Array(e),n=new Float32Array(3*(2===e?2:e-2));if(u.push({line:n,points:i}),2===e){i[0]=s[0]*f,i[1]=s[1]*p,n.set([NaN,NaN,NaN,NaN,i[0],i[1]],0);continue}let[o,h,a,l]=s;o*=f,h*=p,a*=f,l*=p,i.set([o,h,a,l],0),n.set([NaN,NaN,NaN,NaN,o,h],0);for(let t=4;t<e;t+=2){const e=i[t]=s[t]*f,r=i[t+1]=s[t+1]*p;n.set(on.createBezierPoints(o,h,a,l,e,r),3*(t-2)),[o,h,a,l]=[a,l,e,r]}}if(0===u.length)return null;const m=o?new xn:new bn;return m.build(u,s,e,1,i,o?0:c,n),{outline:m,newCurves:g,areContours:o,thickness:c,width:a,height:l}}static async compressSignature({outlines:t,areContours:s,thickness:e,width:i,height:n}){let r,o=1/0,h=-1/0,a=0;for(const s of t){a+=s.length;for(let t=2,e=s.length;t<e;t++){const e=s[t]-s[t-2];o=Math.min(o,e),h=Math.max(h,e)}}r=o>=-128&&h<=127?Int8Array:o>=-32768&&h<=32767?Int16Array:Int32Array;const l=t.length,c=8+3*l,u=new Uint32Array(c);let d=0;u[d++]=c*Uint32Array.BYTES_PER_ELEMENT+(a-2*l)*r.BYTES_PER_ELEMENT,u[d++]=0,u[d++]=i,u[d++]=n,u[d++]=s?0:1,u[d++]=Math.max(0,Math.floor(e??0)),u[d++]=l,u[d++]=r.BYTES_PER_ELEMENT;for(const s of t)u[d++]=s.length-2,u[d++]=s[0],u[d++]=s[1];const f=new CompressionStream("deflate-raw"),p=f.writable.getWriter();await p.ready,p.write(u);const g=r.prototype.constructor;for(const s of t){const t=new g(s.length-2);for(let e=2,i=s.length;e<i;e++)t[e-2]=s[e]-s[e-2];p.write(t)}return p.close(),(await new Response(f.readable).bytes()).toBase64()}static async decompressSignature(t){try{const s=Uint8Array.fromBase64(t),{readable:e,writable:i}=new DecompressionStream("deflate-raw"),n=i.getWriter();await n.ready,n.write(s).then((async()=>{await n.ready,await n.close()})).catch((()=>{}));let r=null,o=0;for await(const t of e)r||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),r.set(t,o),o+=t.length;const h=new Uint32Array(r.buffer,0,r.length>>2),a=h[1];if(0!==a)throw new Error(`Invalid version: ${a}`);const l=h[2],c=h[3],u=0===h[4],d=h[5],f=h[6],p=[],g=(8+3*f)*Uint32Array.BYTES_PER_ELEMENT;let m;switch(h[7]){case Int8Array.BYTES_PER_ELEMENT:m=new Int8Array(r.buffer,g);break;case Int16Array.BYTES_PER_ELEMENT:m=new Int16Array(r.buffer,g);break;case Int32Array.BYTES_PER_ELEMENT:m=new Int32Array(r.buffer,g)}o=0;for(let t=0;t<f;t++){const s=h[3*t+8],e=new Float32Array(s+2);p.push(e);for(let s=0;s<2;s++)e[s]=h[3*t+8+s+1];for(let t=0;t<s;t++)e[t+2]=e[t]+m[o++]}return{areContours:u,thickness:d,outlines:p,width:l,height:c}}catch(t){return y(`decompressSignature: ${t}`),null}}}class kn extends nn{constructor(){super(),super.updateProperties({fill:Ht._defaultLineColor,"stroke-width":0})}clone(){const t=new kn;return t.updateAll(this),t}}class Cn extends yn{constructor(t){super(t),super.updateProperties({stroke:Ht._defaultLineColor,"stroke-width":1})}clone(){const t=new Cn(this._viewParameters);return t.updateAll(this),t}}class Sn extends rn{#Cl=!1;#Sl=null;#Tl=null;#Pl=null;static _type="signature";static _editorType=a.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#Tl=t.signatureData||null,this.#Sl=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,s){Ht.initialize(t,s),this._defaultDrawingOptions=new kn,this._defaultDrawnSignatureOptions=new Cn(s.viewParameters)}static getDefaultDrawingOptions(t){const s=this._defaultDrawingOptions.clone();return s.updateProperties(t),s}static get supportMultipleDrawings(){return!1}static get typesMap(){return S(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#Sl}}static computeTelemetryFinalData(t){const s=t.get("hasDescription");return{hasAltText:s.get(!0)??0,hasNoAltText:s.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,s;const{_isCopy:e}=this;if(e&&(this._isCopy=!1,t=this.x,s=this.y),super.render(),null===this._drawId)if(this.#Tl){const{lines:t,mustSmooth:s,areContours:e,description:i,uuid:n,heightInPage:r}=this.#Tl,{rawDims:{pageWidth:o,pageHeight:h},rotation:a}=this.parent.viewport,l=Mn.processDrawnLines({lines:t,pageWidth:o,pageHeight:h,rotation:a,innerMargin:Sn._INNER_MARGIN,mustSmooth:s,areContours:e});this.addSignature(l,r,i,n)}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.#Sl||""}));return e&&(this._isCopy=!0,this._moveAfterPaste(t,s)),this.div}setUuid(t){this.#Pl=t,this.addEditToolbar()}getUuid(){return this.#Pl}get description(){return this.#Sl}set description(t){this.#Sl=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then((s=>{s?.updateEditSignatureButton(t)})))}getSignaturePreview(){const{newCurves:t,areContours:s,thickness:e,width:i,height:n}=this.#Tl,r=Math.max(i,n);return{areContours:s,outline:Mn.processDrawnLines({lines:{curves:t.map((t=>({points:t}))),thickness:e,width:i,height:n},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:s}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,s,e,i){const{x:n,y:r}=this,{outline:o}=this.#Tl=t;let h;this.#Cl=o instanceof xn,this.description=e,this.#Cl?h=Sn.getDefaultDrawingOptions():(h=Sn._defaultDrawnSignatureOptions.clone(),h.updateProperties({"stroke-width":o.thickness})),this._addOutlines({drawOutlines:o,drawingOptions:h});const[,a]=this.pageDimensions;let l=s/a;l=l>=1?.5:l,this.width*=l/this.height,this.width>=1&&(l*=.9/this.width,this.width=.9),this.height=l,this.setDims(),this.x=n,this.y=r,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(i),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!i,hasDescription:!!e}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:s,pageHeight:e},rotation:i}=this.parent.viewport;return Mn.process(t,s,e,i,Sn._INNER_MARGIN)}getFromText(t,s){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return Mn.extractContoursFromText(t,s,e,i,n,Sn._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:s,pageHeight:e},rotation:i}=this.parent.viewport;return Mn.processDrawnLines({lines:t,pageWidth:s,pageHeight:e,rotation:i,innerMargin:Sn._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:s}){t?this._drawingOptions=Sn.getDefaultDrawingOptions():(this._drawingOptions=Sn._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":s}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:s,points:e}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":i}}=this,n=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#Cl,color:[0,0,0],thickness:this.#Cl?0:i});return this.addComment(n),t?(n.paths={lines:s,points:e},n.uuid=this.#Pl,n.isCopy=!0):n.lines=s,this.#Sl&&(n.accessibilityData={type:"Figure",alt:this.#Sl}),n}static deserializeDraw(t,s,e,i,n,r){return r.areContours?xn.deserialize(t,s,e,i,n,r):bn.deserialize(t,s,e,i,n,r)}static async deserialize(t,s,e){const i=await super.deserialize(t,s,e);return i.#Cl=t.areContours,i.description=t.accessibilityData?.alt||"",i.#Pl=t.uuid,i}}class Tn extends Ht{#El=null;#Dl=null;#Nl=null;#Il=null;#Fl=null;#_l="";#Rl=null;#Ol=!1;#Bl=null;#$l=!1;#Ll=!1;static _type="stamp";static _editorType=a.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#Il=t.bitmapUrl,this.#Fl=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,s){Ht.initialize(t,s)}static isHandlingMimeForPasting(t){return gt.includes(t)}static paste(t,s){s.pasteEditor({mode:a.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 s=t.get("hasAltText");return{hasAltText:s.get(!0)??0,hasNoAltText:s.get(!1)??0}}#Ul(t,s=!1){t?(this.#El=t.bitmap,s||(this.#Dl=t.id,this.#$l=t.isSvg),t.file&&(this.#_l=t.file.name),this.#jl()):this.remove()}#Gl(){if(this.#Nl=null,this._uiManager.enableWaiting(!1),this.#Rl)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#El)this.addEditToolbar().then((()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)}));else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#El){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,s=!0){if(this.hasAltTextData())return null;const{mlManager:e}=this._uiManager;if(!e)throw new Error("No ML.");if(!await e.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,o=await e.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!o)throw new Error("No response from the AI service.");if(o.error)throw new Error("Error from the AI service.");if(o.cancel)return null;if(!o.output)throw new Error("No valid response from the AI service.");const h=o.output;return await this.setGuessedAltText(h),s&&!this.hasAltTextData()&&(this.altTextData={alt:h,decorative:!1}),h}#zl(){if(this.#Dl)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#Dl).then((t=>this.#Ul(t,!0))).finally((()=>this.#Gl()));if(this.#Il){const t=this.#Il;return this.#Il=null,this._uiManager.enableWaiting(!0),void(this.#Nl=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#Ul(t))).finally((()=>this.#Gl())))}if(this.#Fl){const t=this.#Fl;return this.#Fl=null,this._uiManager.enableWaiting(!0),void(this.#Nl=this._uiManager.imageManager.getFromFile(t).then((t=>this.#Ul(t))).finally((()=>this.#Gl())))}const t=document.createElement("input");t.type="file",t.accept=gt.join(",");const s=this._uiManager._signal;this.#Nl=new Promise((e=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const s=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#Ul(s)}else this.remove();e()}),{signal:s}),t.addEventListener("cancel",(()=>{this.remove(),e()}),{signal:s})})).finally((()=>this.#Gl())),t.click()}remove(){this.#Dl&&(this.#El=null,this._uiManager.imageManager.deleteId(this.#Dl),this.#Rl?.remove(),this.#Rl=null,this.#Bl&&(clearTimeout(this.#Bl),this.#Bl=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#Dl&&null===this.#Rl&&this.#zl(),this.isAttachedToDOM||this.parent.add(this))):this.#Dl&&this.#zl()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#Nl||this.#El||this.#Il||this.#Fl||this.#Dl||this.#Ol)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,s;return this._isCopy&&(t=this.x,s=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#Ol||(this.#El?this.#jl():this.#zl()),this._isCopy&&this._moveAfterPaste(t,s),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,s){const{id:e,bitmap:i}=this._uiManager.imageManager.getFromCanvas(t,s);s.remove(),e&&this._uiManager.imageManager.isValidId(e)&&(this.#Dl=e,i&&(this.#El=i),this.#Ol=!1,this.#jl())}_onResized(){this.onScaleChanging()}onScaleChanging(){this.parent&&(null!==this.#Bl&&clearTimeout(this.#Bl),this.#Bl=setTimeout((()=>{this.#Bl=null,this.#Hl()}),200))}#jl(){const{div:t}=this;let{width:s,height:e}=this.#El;const[i,n]=this.pageDimensions,r=.75;if(this.width)s=this.width*i,e=this.height*n;else if(s>r*i||e>r*n){const t=Math.min(r*i/s,r*n/e);s*=t,e*=t}this._uiManager.enableWaiting(!1);const o=this.#Rl=document.createElement("canvas");o.setAttribute("role","img"),this.addContainer(o),this.width=s/i,this.height=e/n,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Hl(),this.#Ll||(this.parent.addUndoableEditor(this),this.#Ll=!0),this._reportTelemetry({action:"inserted_image"}),this.#_l&&this.div.setAttribute("aria-description",this.#_l),this.annotationElementId||this._uiManager.a11yAlert(Ht._l10nAlert.stamp)}copyCanvas(t,s,e=!1){t||=224;const{width:i,height:n}=this.#El,r=new pt;let o=this.#El,h=i,a=n,l=null;if(s){if(i>s||n>s){const t=Math.min(s/i,s/n);h=Math.floor(i*t),a=Math.floor(n*t)}l=document.createElement("canvas");const t=l.width=Math.ceil(h*r.sx),e=l.height=Math.ceil(a*r.sy);this.#$l||(o=this.#Wl(t,e));const c=l.getContext("2d");c.filter=this._uiManager.hcmFilter;let u="white",d="#cfcfd8";"none"!==this._uiManager.hcmFilter?d="black":mt.isDarkMode&&(u="#8f8f9d",d="#42414d");const f=15,p=f*r.sx,g=f*r.sy,m=new OffscreenCanvas(2*p,2*g),A=m.getContext("2d");A.fillStyle=u,A.fillRect(0,0,2*p,2*g),A.fillStyle=d,A.fillRect(0,0,p,g),A.fillRect(p,g,p,g),c.fillStyle=c.createPattern(m,"repeat"),c.fillRect(0,0,t,e),c.drawImage(o,0,0,o.width,o.height,0,0,t,e)}let c=null;if(e){let s,e;if(r.symmetric&&o.width<t&&o.height<t)s=o.width,e=o.height;else if(o=this.#El,i>t||n>t){const r=Math.min(t/i,t/n);s=Math.floor(i*r),e=Math.floor(n*r),this.#$l||(o=this.#Wl(s,e))}const h=new OffscreenCanvas(s,e).getContext("2d",{willReadFrequently:!0});h.drawImage(o,0,0,o.width,o.height,0,0,s,e),c={width:s,height:e,data:h.getImageData(0,0,s,e).data}}return{canvas:l,width:h,height:a,imageData:c}}#Wl(t,s){const{width:e,height:i}=this.#El;let n=e,r=i,o=this.#El;for(;n>2*t||r>2*s;){const e=n,i=r;n>2*t&&(n=Math.ceil(n/2)),r>2*s&&(r=Math.ceil(r/2));const h=new OffscreenCanvas(n,r);h.getContext("2d").drawImage(o,0,0,e,i,0,0,n,r),o=h.transferToImageBitmap()}return o}#Hl(){const[t,s]=this.parentDimensions,{width:e,height:i}=this,n=new pt,r=Math.ceil(e*t*n.sx),o=Math.ceil(i*s*n.sy),h=this.#Rl;if(!h||h.width===r&&h.height===o)return;h.width=r,h.height=o;const a=this.#$l?this.#El:this.#Wl(r,o),l=h.getContext("2d");l.filter=this._uiManager.hcmFilter,l.drawImage(a,0,0,a.width,a.height,0,0,r,o)}#Vl(t){if(t){if(this.#$l){const t=this._uiManager.imageManager.getSvgUrl(this.#Dl);if(t)return t}const t=document.createElement("canvas");return({width:t.width,height:t.height}=this.#El),t.getContext("2d").drawImage(this.#El,0,0),t.toDataURL()}if(this.#$l){const[t,s]=this.pageDimensions,e=Math.round(this.width*t*Q.PDF_TO_CSS_UNITS),i=Math.round(this.height*s*Q.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(e,i);return n.getContext("2d").drawImage(this.#El,0,0,this.#El.width,this.#El.height,0,0,e,i),n.transferToImageBitmap()}return structuredClone(this.#El)}static async deserialize(t,s,e){let i=null,n=!1;if(t instanceof Qi){const{data:{rect:r,rotation:h,id:l,structParent:c,popupRef:u,richText:d,contentsObj:f,creationDate:p,modificationDate:g},container:m,parent:{page:{pageNumber:A}},canvas:w}=t;let b,y;w?(delete t.canvas,({id:b,bitmap:y}=e.imageManager.getFromCanvas(m.id,w)),w.remove()):(n=!0,t._hasNoCanvas=!0);const v=(await s._structTree.getAriaAttributes(`${o}${l}`))?.get("aria-label")||"";i=t={annotationType:a.STAMP,bitmapId:b,bitmap:y,pageIndex:A-1,rect:r.slice(0),rotation:h,annotationElementId:l,id:l,deleted:!1,accessibilityData:{decorative:!1,altText:v},isSvg:!1,structParent:c,popupRef:u,richText:d,comment:f?.str||null,creationDate:p,modificationDate:g}}const r=await super.deserialize(t,s,e),{rect:h,bitmap:l,bitmapUrl:c,bitmapId:u,isSvg:d,accessibilityData:f}=t;n?(e.addMissingCanvas(t.id,r),r.#Ol=!0):u&&e.imageManager.isValidId(u)?(r.#Dl=u,l&&(r.#El=l)):r.#Il=c,r.#$l=d;const[p,g]=r.pageDimensions;return r.width=(h[2]-h[0])/p,r.height=(h[3]-h[1])/g,f&&(r.altTextData=f),r._initialData=i,t.comment&&r.setCommentData(t),r.#Ll=!!i,r}serialize(t=!1,s=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=Object.assign(super.serialize(t),{bitmapId:this.#Dl,isSvg:this.#$l});if(this.addComment(e),t)return e.bitmapUrl=this.#Vl(!0),e.accessibilityData=this.serializeAltText(!0),e.isCopy=!0,e;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(e.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#Bh(e);return t.isSame?null:(t.isSameAltText?delete e.accessibilityData:e.accessibilityData.structParent=this._initialData.structParent??-1,e.id=this.annotationElementId,delete e.bitmapId,e)}if(null===s)return e;s.stamps||=new Map;const r=this.#$l?(e.rect[2]-e.rect[0])*(e.rect[3]-e.rect[1]):null;if(s.stamps.has(this.#Dl)){if(this.#$l){const t=s.stamps.get(this.#Dl);r>t.area&&(t.area=r,t.serialized.bitmap.close(),t.serialized.bitmap=this.#Vl(!1))}}else s.stamps.set(this.#Dl,{area:r,serialized:e}),e.bitmap=this.#Vl(!1);return e}#Bh(t){const{pageIndex:s,accessibilityData:{altText:e}}=this._initialData,i=t.pageIndex===s,n=(t.accessibilityData?.alt||"")===e;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}class Pn{#bh;#Xl=!1;#Yl=null;#Kl=null;#ql=null;#Ql=new Map;#Jl=!1;#Zl=!1;#tc=!1;#sc=null;#ec=null;#ic=null;#nc=null;#rc=null;#oc=-1;#b;static _initialized=!1;static#tt=new Map([en,vn,Tn,An,Sn].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:s,div:e,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:a,l10n:l}){const c=[...Pn.#tt.values()];if(!Pn._initialized){Pn._initialized=!0;for(const s of c)s.initialize(l,t)}t.registerEditorTypes(c),this.#b=t,this.pageIndex=s,this.div=e,this.#bh=n,this.#Yl=r,this.viewport=a,this.#ic=h,this.drawLayer=o,this._structTree=i,this.#b.addLayer(this)}get isEmpty(){return 0===this.#Ql.size}get isInvisible(){return this.isEmpty&&this.#b.getMode()===a.NONE}updateToolbar(t){this.#b.updateToolbar(t)}updateMode(t=this.#b.getMode()){switch(this.#hc(),t){case a.NONE:return this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case a.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case a.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:s}=this.div;if(s.toggle("nonEditing",!1),t===a.POPUP)s.toggle("commentEditing",!0);else{s.toggle("commentEditing",!1);for(const e of Pn.#tt.values())s.toggle(`${e._type}Editing`,t===e._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#ic?.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.#Yl?.togglePointerEvents(t)}get#ac(){return 0!==this.#Ql.size?this.#Ql.values():this.#b.getEditors(this.pageIndex)}async enable(){this.#tc=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),this.#rc?.abort(),this.#rc=null;const t=new Set;for(const s of this.#ac)s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#b.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));const s=this.#Yl;if(s)for(const e of s.getEditableAnnotations()){if(e.hide(),this.#b.isDeletedAnnotationElement(e.data.id))continue;if(t.has(e.data.id))continue;const s=await this.deserialize(e);s&&(this.addOrRebuild(s),s.enableEditing())}this.#tc=!1,this.#b._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#Zl=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),this.#ic&&!this.#rc){this.#rc=new AbortController;const t=this.#b.combinedSignal(this.#rc);this.#ic.div.addEventListener("pointerdown",(t=>{const{clientX:s,clientY:e,timeStamp:i}=t;if(i-this.#oc>500)return void(this.#oc=i);this.#oc=-1;const{classList:n}=this.div;n.toggle("getElements",!0);const r=document.elementsFromPoint(s,e);if(n.toggle("getElements",!1),!this.div.contains(r[0]))return;let o;const a=new RegExp(`^${h}[0-9]+$`);for(const t of r)if(a.test(t.id)){o=t.id;break}if(!o)return;const l=this.#Ql.get(o);null===l?.annotationElementId&&(ht(t),l.dblclick(t))}),{signal:t,capture:!0})}const t=this.#Yl,s=[];if(t){const e=new Map,i=new Map;for(const t of this.#ac)t.disableEditing(),t.annotationElementId?null===t.serialize()?(i.set(t.annotationElementId,t),this.getEditableAnnotation(t.annotationElementId)?.show(),t.remove()):e.set(t.annotationElementId,t):s.push(t);for(const s of t.getEditableAnnotations()){const{id:t}=s.data;if(this.#b.isDeletedAnnotationElement(t)){s.updateEdited({deleted:!0});continue}let n=i.get(t);n?(n.resetAnnotationElement(s),n.show(!1),s.show()):(n=e.get(t),n&&(this.#b.addChangedExistingAnnotation(n),n.renderAnnotationElement(s)&&n.show(!1)),s.show())}}this.#hc(),this.isEmpty&&(this.div.hidden=!0);const{classList:e}=this.div;for(const t of Pn.#tt.values())e.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),t?.updateFakeAnnotations(s),this.#Zl=!1}getEditableAnnotation(t){return this.#Yl?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#b.getActive()!==t&&this.#b.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#ic?.div&&!this.#nc){this.#nc=new AbortController;const t=this.#b.combinedSignal(this.#nc);this.#ic.div.addEventListener("pointerdown",this.#lc.bind(this),{signal:t}),this.#ic.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#ic?.div&&this.#nc&&(this.#nc.abort(),this.#nc=null,this.#ic.div.classList.remove("highlighting"))}#lc(t){this.#b.unselectAll();const{target:s}=t;if(s===this.#ic.div||("img"===s.getAttribute("role")||s.classList.contains("endOfContent")||s.classList.contains("textLayerImages")||s.classList.contains("textLayerImagePlaceholder"))&&this.#ic.div.contains(s)){const{isMac:s}=R.platform;if(0!==t.button||t.ctrlKey&&s)return;this.#b.showAllEditors("highlight",!0,!0),An.startDrawing(this,this.#b,"ltr"===this.#b.direction,t),t.preventDefault()}}enableClick(){if(this.#Kl)return;this.#Kl=new AbortController;const t=this.#b.combinedSignal(this.#Kl);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const s=this.pointerup.bind(this);this.div.addEventListener("pointerup",s,{signal:t}),this.div.addEventListener("pointercancel",s,{signal:t})}disableClick(){this.#Kl?.abort(),this.#Kl=null}attach(t){this.#Ql.set(t.id,t);const{annotationElementId:s}=t;s&&this.#b.isDeletedAnnotationElement(s)&&this.#b.removeDeletedAnnotationElement(t)}detach(t){this.#Ql.delete(t.id),this.#bh?.removePointerInTextLayer(t.contentDiv),!this.#Zl&&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),Ht.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 s=t.render();this.div.append(s),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#tc),this.#b.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:s}=document;t.div.contains(s)&&!this.#ql&&(t._focusEventsAllowed=!1,this.#ql=setTimeout((()=>{this.#ql=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#b._signal}),s.focus())}),0)),t._structTreeParentId=this.#bh?.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 s of this.#Ql.values())if(s.uid===t)return s;return null}get#cc(){return Pn.#tt.get(this.#b.getMode())}combinedSignal(t){return this.#b.combinedSignal(t)}#uc(t){const s=this.#cc;return s?new s.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#cc?.canCreateNewEmptyEditor()}async pasteEditor(t,s){this.updateToolbar(t),await this.#b.updateMode(t.mode);const{offsetX:e,offsetY:i}=this.#dc(),n=this.#b.getId(),r=this.#uc({parent:this,id:n,x:e,y:i,uiManager:this.#b,isCentered:!0,...s});r&&this.add(r)}async deserialize(t){return await(Pn.#tt.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#b))||null}createAndAddNewEditor(t,s,e={}){const i=this.#b.getId(),n=this.#uc({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#b,isCentered:s,...e});return n&&this.add(n),n}get boundingClientRect(){return this.div.getBoundingClientRect()}#dc(){const{x:t,y:s,width:e,height:i}=this.boundingClientRect,n=Math.max(0,t),r=Math.max(0,s),o=(n+Math.min(window.innerWidth,t+e))/2-t,h=(r+Math.min(window.innerHeight,s+i))/2-s,[a,l]=this.viewport.rotation%180==0?[o,h]:[h,o];return{offsetX:a,offsetY:l}}addNewEditor(t={}){this.createAndAddNewEditor(this.#dc(),!0,t)}setSelected(t){this.#b.setSelected(t)}toggleSelected(t){this.#b.toggleSelected(t)}unselect(t){this.#b.unselect(t)}pointerup(t){const{isMac:s}=R.platform;if(0!==t.button||t.ctrlKey&&s)return;if(t.target!==this.div)return;if(!this.#Jl)return;if(this.#Jl=!1,this.#cc?.isDrawer&&this.#cc.supportMultipleDrawings)return;if(!this.#Xl)return void(this.#Xl=!0);const e=this.#b.getMode();e!==a.STAMP&&e!==a.POPUP&&e!==a.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#b.unselectAll()}pointerdown(t){if(this.#b.getMode()===a.HIGHLIGHT&&this.enableTextSelection(),this.#Jl)return void(this.#Jl=!1);const{isMac:s}=R.platform;if(0!==t.button||t.ctrlKey&&s)return;if(t.target!==this.div)return;if(this.#Jl=!0,this.#cc?.isDrawer)return void this.startDrawingSession(t);const e=this.#b.getActive();this.#Xl=!e||e.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#sc)return void this.#cc.startDrawing(this,this.#b,!1,t);this.#b.setCurrentDrawingSession(this),this.#sc=new AbortController;const s=this.#b.combinedSignal(this.#sc);this.div.addEventListener("blur",(({relatedTarget:t})=>{t&&!this.div.contains(t)&&(this.#ec=null,this.commitOrRemove())}),{signal:s}),this.#cc.startDrawing(this,this.#b,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#ec=t)}else this.#ec&&setTimeout((()=>{this.#ec?.focus(),this.#ec=null}),0)}endDrawingSession(t=!1){return this.#sc?(this.#b.setCurrentDrawingSession(null),this.#sc.abort(),this.#sc=null,this.#ec=null,this.#cc.endDrawing(t)):null}findNewParent(t,s,e){const i=this.#b.findParent(s,e);return null!==i&&i!==this&&(i.changeParent(t),!0)}commitOrRemove(){return!!this.#sc&&(this.endDrawingSession(),!0)}onScaleChanging(){this.#sc&&this.#cc.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#b.getActive()?.parent===this&&(this.#b.commitOrRemove(),this.#b.setActiveEditor(null)),this.#ql&&(clearTimeout(this.#ql),this.#ql=null);for(const t of this.#Ql.values())this.#bh?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Ql.clear(),this.#b.removeLayer(this)}#hc(){for(const t of this.#Ql.values())t.isEmpty()&&t.remove()}async render({viewport:t}){this.viewport=t,ft(this.div,t);for(const t of this.#b.getEditors(this.pageIndex))this.add(t),t.rebuild();await this.#b.findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:t}){this.#b.commitOrRemove(),this.#hc();const s=this.viewport.rotation,e=t.rotation;if(this.viewport=t,ft(this.div,{rotation:e}),s!==e)for(const t of this.#Ql.values())t.rotate(e)}get pageDimensions(){const{pageWidth:t,pageHeight:s}=this.viewport.rawDims;return[t,s]}get scale(){return this.#b.viewParameters.realScale}}function En(t,s){return t===s?0:t.compareDocumentPosition(s)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function Dn(t){return t?t.nodeType===Node.ELEMENT_NODE?t.closest(".textLayer"):t.parentElement?.closest(".textLayer")||null:null}function Nn(t,s,e,i){if(t===e)return s<=i;const n=t.compareDocumentPosition(e);return!!(n&Node.DOCUMENT_POSITION_FOLLOWING)||!(n&Node.DOCUMENT_POSITION_PRECEDING)&&null}function In(t,s,e){if(t.nodeType!==Node.ELEMENT_NODE||!t.classList.contains("textLayer")||s!==t.childNodes.length)return{container:t,offset:s};let i=t.lastChild;return i?.nodeType===Node.ELEMENT_NODE&&i.classList.contains("endOfContent")&&(i=i.previousSibling),i&&e.contains(i)?i.nodeType===Node.TEXT_NODE?{container:i,offset:i.textContent.length}:{container:i,offset:i.childNodes.length}:null}class Fn{#Lo=null;#fc=new Map;#ic=null;#rt=null;#kt=null;#pc=null;#gc=new Map;static#T=0;static#mc=0;static#Ac=null;static#wc=new Set;static#bc=!1;static#yc=new Set;static#vc=new WeakMap;constructor({filterFactory:t=null,pageColors:s=null,pageIndex:e,textLayer:i=null}){if(this.pageIndex=e,this.#rt=t,this.#kt=s,i){const t=Fn.#vc.get(i);if(t?.selectionDiv&&(t.selectionDiv.remove(),Fn.#wc.delete(t.selectionDiv)),Fn.#vc.set(i,{drawLayer:this}),Fn.#yc.add(i),this.#ic=i,this.#pc=new MutationObserver((t=>{if(this.#Lo&&this.#ic?.isConnected&&Fn.#xc())for(const{addedNodes:s}of t)for(const t of s)if(t.nodeType===Node.ELEMENT_NODE&&t.classList.contains("endOfContent"))return void Fn.#Ut()})),this.#pc.observe(i,{childList:!0}),null===Fn.#Ac){Fn.#Ac=new AbortController;const{signal:t}=Fn.#Ac;document.addEventListener("selectionchange",Fn.#Ut.bind(Fn),{signal:t}),document.addEventListener("pointerdown",(()=>{Fn.#bc=!0}),{signal:t}),document.addEventListener("pointerup",(()=>{Fn.#bc=!1}),{signal:t}),window.addEventListener("blur",(()=>{Fn.#bc=!1}),{signal:t})}}}setParent(t){if(!this.#Lo)return this.#Lo=t,void(this.#ic?.isConnected&&Fn.#xc()&&Fn.#Ut());if(this.#Lo!==t){if(this.#fc.size>0)for(const s of this.#fc.values())s.remove(),t.append(s);this.#Lo=t}}static#Mc(t){const s=this.#vc.get(t);s?.selectionDiv&&(s.selectionDiv.remove(),this.#wc.delete(s.selectionDiv),s.selectionDiv=null,s.path=null)}static#xc(){const t=document.getSelection();return!!t&&!t.isCollapsed}static#kc(){return this.#yc.keys().filter((t=>t.isConnected)).toArray().sort(En)}static#Ut(){const t=document.getSelection();if(!t||t.isCollapsed){for(const t of this.#wc)t.remove();return void this.#wc.clear()}const s=new WeakMap,e=this.#kc(),i=[];for(let s=0,n=t.rangeCount;s<n;s++){const n=t.getRangeAt(s);if(n.collapsed)continue;let{startContainer:r,startOffset:o,endContainer:h,endOffset:a}=n,l=Dn(r),c=Dn(h);if(this.#bc&&null===l!=(null===c))return;if(1===t.rangeCount){const{anchorNode:s,anchorOffset:e,focusNode:i,focusOffset:n}=t,u=Dn(s),d=Dn(i),f=Nn(s,e,i,n);u&&d&&null!==f&&(f?(r=s,o=e,l=u,h=i,a=n,c=d):(r=i,o=n,l=d,h=s,a=e,c=u))}const u=e.filter((t=>n.intersectsNode(t)));if(0===u.length)continue;let d=!1;if(l||(l=u[0],r=l,o=0,d=!0),c||(c=u.at(-1),h=c,a=c.childNodes.length,d=!0),h.nodeType===Node.ELEMENT_NODE)if(h.classList.contains("endOfContent")){const t=h.previousSibling;if(!t)continue;h=t,a=t.nodeType===Node.TEXT_NODE?t.textContent.length:t.childNodes.length}else if(h.classList.contains("textLayer")&&h.childNodes.length===a){const t=In(h,a,c);if(!t)continue;h=t.container,a=t.offset}if(r.nodeType===Node.ELEMENT_NODE){const t=In(r,o,l);if(!t)continue;r=t.container,o=t.offset}if(l!==c||d||!u.includes(l))for(const t of u){const s=t.firstChild;if(!s)continue;const e=document.createRange();if(t===l?e.setStart(r,o):e.setStartBefore(s),t===c)e.setEnd(h,a);else{const s=t.lastChild;if(!s)continue;if(s.nodeType===Node.ELEMENT_NODE&&s.classList.contains("endOfContent")){const t=s.previousSibling;if(!t)continue;e.setEndAfter(t)}else e.setEndAfter(s)}e.collapsed||i.push([e,t])}else i.push([n,l])}const n=new Set(i.map((t=>t[1])));for(const t of this.#yc)n.has(t)||this.#Mc(t);for(const[t,e]of i){const i=Fn.#vc.get(e);if(!i)continue;let n=s.get(e);if(!n){const t=e.getBoundingClientRect();n=(s,e,i,n)=>({x:(s-t.x)/t.width,y:(e-t.y)/t.height,width:i/t.width,height:n/t.height}),s.set(e,n)}const r=[];for(let{x:s,y:e,width:i,height:o}of t.getClientRects())0!==i&&0!==o&&(({x:s,y:e,width:i,height:o}=n(s,e,i,o)),1===i&&1===o||r.push(`M${s} ${e} h${i} v${o} h-${i} Z`));if(0===r.length)continue;const o=i.drawLayer;let h=i.selectionDiv,a=i.path;if(!h){const t="clip_selection_"+Fn.#mc++;h=document.createElement("div"),h.className="selection",h.style.clipPath=`url(#${t})`;const s=o.#rt?.createSelectionStyle(o.#kt);if(s)for(const[t,e]of Object.entries(s))h.style.setProperty(t,e);const e=Fn._svgFactory.create(1,1,!0);e.setAttribute("aria-hidden","true"),e.setAttribute("width","100%"),e.setAttribute("height","100%");const n=Fn._svgFactory.createElement("clipPath");n.setAttribute("id",t),n.setAttribute("clipPathUnits","objectBoundingBox"),a=Fn._svgFactory.createElement("path"),n.append(a),e.append(n),h.append(e),i.path=a,i.selectionDiv=h}o.#Lo&&h.parentNode!==o.#Lo&&(o.#Lo.append(h),this.#wc.add(h)),a.setAttribute("d",r.join(" "))}}static get _svgFactory(){return S(this,"_svgFactory",new xi)}static#Cc(t,[s,e,i,n]){const{style:r}=t;r.top=100*e+"%",r.left=100*s+"%",r.width=100*i+"%",r.height=100*n+"%"}#Sc(){const t=Fn._svgFactory.create(1,1,!0);return this.#Lo.append(t),t.setAttribute("aria-hidden","true"),t}#Tc(t,s){const e=Fn._svgFactory.createElement("clipPath");t.append(e);const i=`clip_${s}`;e.setAttribute("id",i),e.setAttribute("clipPathUnits","objectBoundingBox");const n=Fn._svgFactory.createElement("use");return e.append(n),n.setAttribute("href",`#${s}`),n.classList.add("clip"),i}#Pc(t,s){for(const[e,i]of Object.entries(s))null===i?t.removeAttribute(e):t.setAttribute(e,i)}draw(t,s=!1,e=!1){const i=Fn.#T++,n=this.#Sc(),r=Fn._svgFactory.createElement("defs");n.append(r);const o=Fn._svgFactory.createElement("path");r.append(o);const h=`path_${i}`;o.setAttribute("id",h),o.setAttribute("vector-effect","non-scaling-stroke"),s&&this.#gc.set(i,o);const a=e?this.#Tc(r,h):null,l=Fn._svgFactory.createElement("use");return n.append(l),l.setAttribute("href",`#${h}`),this.updateProperties(n,t),this.#fc.set(i,n),{id:i,clipPathId:`url(#${a})`}}drawOutline(t,s){const e=Fn.#T++,i=this.#Sc(),n=Fn._svgFactory.createElement("defs");i.append(n);const r=Fn._svgFactory.createElement("path");n.append(r);const o=`path_${e}`;let h;if(r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke"),s){const t=Fn._svgFactory.createElement("mask");n.append(t),h=`mask_${e}`,t.setAttribute("id",h),t.setAttribute("maskUnits","objectBoundingBox");const s=Fn._svgFactory.createElement("rect");t.append(s),s.setAttribute("width","1"),s.setAttribute("height","1"),s.setAttribute("fill","white");const i=Fn._svgFactory.createElement("use");t.append(i),i.setAttribute("href",`#${o}`),i.setAttribute("stroke","none"),i.setAttribute("fill","black"),i.setAttribute("fill-rule","nonzero"),i.classList.add("mask")}const a=Fn._svgFactory.createElement("use");i.append(a),a.setAttribute("href",`#${o}`),h&&a.setAttribute("mask",`url(#${h})`);const l=a.cloneNode();return i.append(l),a.classList.add("mainOutline"),l.classList.add("secondaryOutline"),this.updateProperties(i,t),this.#fc.set(e,i),e}finalizeDraw(t,s){this.#gc.delete(t),this.updateProperties(t,s)}updateProperties(t,s){if(!s)return;const{root:e,bbox:i,rootClass:n,path:r}=s,o="number"==typeof t?this.#fc.get(t):t;if(o){if(e&&this.#Pc(o,e),i&&Fn.#Cc(o,i),n){const{classList:t}=o;for(const[s,e]of Object.entries(n))t.toggle(s,e)}r&&this.#Pc(o.firstElementChild.firstElementChild,r)}}updateParent(t,s){if(s===this)return;const e=this.#fc.get(t);e&&(s.#Lo.append(e),this.#fc.delete(t),s.#fc.set(t,e))}remove(t){this.#gc.delete(t),null!==this.#Lo&&(this.#fc.get(t).remove(),this.#fc.delete(t))}destroy(){this.#Lo=null;for(const t of this.#fc.values())t.remove();if(this.#fc.clear(),this.#gc.clear(),this.#pc?.disconnect(),this.#pc=null,this.#ic){const t=Fn.#vc.get(this.#ic);t?.drawLayer===this&&(Fn.#Mc(this.#ic),Fn.#vc.delete(this.#ic),Fn.#yc.delete(this.#ic),0===Fn.#yc.size&&(Fn.#Ac?.abort(),Fn.#Ac=null,Fn.#bc=!1)),this.#ic=null}}}function _n(t){return`${(100*t).toFixed(2)}%`}class Rn{#Ec=[];#Dc=new Map;#Nc=null;#Ic=0;#ur=0;#cr=0;static#Fc=null;constructor(t,s,e,i){this.#Ic=t,this.#Ec=s,this.#ur=e.rawDims.pageWidth,this.#cr=e.rawDims.pageHeight,this.#Nc=i}render(){const t=document.createElement("div");t.className="textLayerImages";for(let s=0;s<this.#Ec.length;s+=6){const e=this.#_c(this.#Ec.subarray(s,s+6));e&&t.append(e)}return t.addEventListener("contextmenu",(t=>{if(!(t.target instanceof HTMLCanvasElement))return;const s=t.target,e=this.#Dc.get(s);if(!e)return;const i=Rn.#Fc?.deref();if(i===s)return;i&&(i.width=0,i.height=0),Rn.#Fc=new WeakRef(s);const{inverseTransform:n,x1:r,y1:o,width:h,height:a}=e,l=this.#Nc(),c=Math.ceil(r*l.width),u=Math.ceil(o*l.height),d=Math.floor((r+h/this.#ur)*l.width),f=Math.floor((o+a/this.#cr)*l.height);s.width=d-c,s.height=f-u;const p=s.getContext("2d");p.setTransform(...n),p.translate(-c,-u),p.drawImage(l,0,0)})),t}#_c([t,s,e,i,n,r]){const o=Math.hypot((n-t)*this.#ur,(r-s)*this.#cr),h=Math.hypot((e-t)*this.#ur,(i-s)*this.#cr);if(o<this.#Ic||h<this.#Ic)return null;const a=[(n-t)*this.#ur/o,(r-s)*this.#cr/o,(e-t)*this.#ur/h,(i-s)*this.#cr/h,0,0],l=O.inverseTransform(a),c=document.createElement("canvas");return c.className="textLayerImagePlaceholder",c.width=0,c.height=0,Object.assign(c.style,{opacity:0,position:"absolute",left:_n(t),top:_n(s),width:_n(o/this.#ur),height:_n(h/this.#cr),transformOrigin:"0% 0%",transform:`matrix(${a.join(",")})`}),this.#Dc.set(c,{inverseTransform:l,width:o,height:h,x1:t,y1:s}),c}}globalThis._pdfjsTestingUtils={HighlightOutliner:un},globalThis.pdfjsLib={AbortException:F,AnnotationEditorLayer:Pn,AnnotationEditorParamsType:l,AnnotationEditorType:a,AnnotationEditorUIManager:Bt,AnnotationLayer:tn,AnnotationMode:r,AnnotationType:d,applyOpacity:wt,build:gi,ColorPicker:mi,createValidAbsoluteUrl:M,CSSConstants:At,DOMSVGFactory:xi,DrawLayer:Fn,FeatureTest:R,fetchData:J,findContrastColor:kt,getDocument:ri,getFilenameFromUrl:et,getPdfFilenameFromUrl:it,getRGB:ct,getRGBA:lt,getUuid:U,GlobalWorkerOptions:Ke,ImageKind:u,InvalidPDFException:D,isDataScheme:tt,isPdfFile:st,isValidExplicitDest:Fs,makeArr:j,makeMap:G,makeObj:z,makeSet:H,MathClamp:W,noContextMenu:ot,normalizeUnicode:L,OPS:p,OutputScale:pt,PasswordException:P,PasswordResponses:g,PDFDataRangeTransport:hi,PDFDateString:at,PDFWorker:ci,PermissionFlag:c,PixelsPerInch:Q,RenderingCancelledException:Z,renderRichText:Ct,ResponseException:N,setLayerDimensions:ft,shadow:S,SignatureExtractor:Mn,stopEvent:ht,SupportedImageMimeTypes:gt,TextLayer:ni,TextLayerImages:Rn,TouchManager:zt,updateUrlHash:k,Util:O,VerbosityLevel:f,version:pi,XfaLayer:q};export{F as AbortException,Pn as AnnotationEditorLayer,l as AnnotationEditorParamsType,a as AnnotationEditorType,Bt as AnnotationEditorUIManager,tn as AnnotationLayer,r as AnnotationMode,d as AnnotationType,At as CSSConstants,mi as ColorPicker,xi as DOMSVGFactory,Fn as DrawLayer,R as FeatureTest,Ke as GlobalWorkerOptions,u as ImageKind,D as InvalidPDFException,W as MathClamp,p as OPS,pt as OutputScale,hi as PDFDataRangeTransport,at as PDFDateString,ci as PDFWorker,P as PasswordException,g as PasswordResponses,c as PermissionFlag,Q as PixelsPerInch,Z as RenderingCancelledException,N as ResponseException,Mn as SignatureExtractor,gt as SupportedImageMimeTypes,ni as TextLayer,Rn as TextLayerImages,zt as TouchManager,O as Util,f as VerbosityLevel,q as XfaLayer,wt as applyOpacity,gi as build,M as createValidAbsoluteUrl,J as fetchData,kt as findContrastColor,ri as getDocument,et as getFilenameFromUrl,it as getPdfFilenameFromUrl,ct as getRGB,lt as getRGBA,U as getUuid,tt as isDataScheme,st as isPdfFile,Fs as isValidExplicitDest,j as makeArr,G as makeMap,z as makeObj,H as makeSet,ot as noContextMenu,L as normalizeUnicode,Ct as renderRichText,ft as setLayerDimensions,S as shadow,ht as stopEvent,k as updateUrlHash,pi as version}
|