/** * @licstart The following is the entire license notice for the * JavaScript code in this page * * Copyright 2024 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @licend The above is the entire license notice for the * JavaScript code in this page */ /** * pdfjsVersion = 5.5.207 * pdfjsBuild = 527964698 */const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),e=[.001,0,0,.001,0,0],i=1.35,n=1,s=2,r=4,a=16,o=32,l=64,h=128,d=256,c={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},u="pdfjs_internal_editor_",p={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},g={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},m={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},f=1,b=2,w=0,y=1,A=2,v=3,x=3,E=4,C={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},S={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},T=1,_=2,D=3,P=4,M=5,k={ERRORS:0,WARNINGS:1,INFOS:5},I={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},F=0,R=1,B=2,L=3,O=4,N={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let U=k.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(U=t)}function getVerbosityLevel(){return U}function info(t){U>=k.INFOS&&console.info(`Info: ${t}`)}function warn(t){U>=k.WARNINGS&&console.warn(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const n=e?URL.parse(t,e):URL.parse(t);return function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(n)?n:null}function updateUrlHash(t,e,i=!1){const n=URL.parse(t);if(n){n.hash=e;return n.href}return i&&createValidAbsoluteUrl(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function stripPath(t){return t.substring(t.lastIndexOf("/")+1)}function shadow(t,e,i,n=!1){Object.defineProperty(t,e,{value:i,enumerable:!n,configurable:!0,writable:!1});return i}const H=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends H{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends H{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends H{constructor(t){super(t,"InvalidPDFException")}}class ResponseException extends H{constructor(t,e,i){super(t,"ResponseException");this.status=e;this.missing=i}}class FormatError extends H{constructor(t){super(t,"FormatError")}}class AbortException extends H{constructor(t){super(t,"AbortException")}}function stringToBytes(t){"string"!=typeof t&&unreachable("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let n=0;nt.toString(16).padStart(2,"0"));class Util{static makeHexColor(t,e,i){return`#${z[t]}${z[e]}${z[i]}`}static domMatrixToTransform(t){return[t.a,t.b,t.c,t.d,t.e,t.f]}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,i=0){const n=t[i],s=t[i+1];t[i]=n*e[0]+s*e[2]+e[4];t[i+1]=n*e[1]+s*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const n=e[0],s=e[1],r=e[2],a=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],d=t[i+e+1];t[i+e]=h*n+d*r+o;t[i+e+1]=h*s+d*a+l}}static applyInverseTransform(t,e){const i=t[0],n=t[1],s=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-n*e[2]+e[2]*e[5]-e[4]*e[3])/s;t[1]=(-i*e[1]+n*e[0]+e[4]*e[1]-e[5]*e[0])/s}static axialAlignedBoundingBox(t,e,i){const n=e[0],s=e[1],r=e[2],a=e[3],o=e[4],l=e[5],h=t[0],d=t[1],c=t[2],u=t[3];let p=n*h+o,g=p,m=n*c+o,f=m,b=a*d+l,w=b,y=a*u+l,A=y;if(0!==s||0!==r){const t=s*h,e=s*c,i=r*d,n=r*u;p+=i;f+=i;m+=n;g+=n;b+=t;A+=t;y+=e;w+=e}i[0]=Math.min(i[0],p,m,g,f);i[1]=Math.min(i[1],b,y,w,A);i[2]=Math.max(i[2],p,m,g,f);i[3]=Math.max(i[3],b,y,w,A)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const i=t[0],n=t[1],s=t[2],r=t[3],a=i**2+n**2,o=i*s+n*r,l=s**2+r**2,h=(a+l)/2,d=Math.sqrt(h**2-(a*l-o**2));e[0]=Math.sqrt(h+d||1);e[1]=Math.sqrt(h-d||1)}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),n=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>n)return null;const s=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return s>r?null:[i,s,n,r]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t);i[1]=Math.min(i[1],e);i[2]=Math.max(i[2],t);i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,n,s){s[0]=Math.min(s[0],t,i);s[1]=Math.min(s[1],e,n);s[2]=Math.max(s[2],t,i);s[3]=Math.max(s[3],e,n)}static#t(t,e,i,n,s,r,a,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*n,g=d*(d*(d*s+3*l*r)+3*c*a)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,i,n,s,r,a,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,n,s,r,a,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,n,s,r,a,o,(-h+p)/g,c);this.#t(t,e,i,n,s,r,a,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,n,s,r,a,o,l){l[0]=Math.min(l[0],t,a);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,a);l[3]=Math.max(l[3],e,o);this.#e(t,i,s,a,e,n,r,o,3*(3*(i-s)-t+a),6*(t-2*i+s),3*(i-t),l);this.#e(t,i,s,a,e,n,r,o,3*(3*(n-r)-e+o),6*(e-2*n+r),3*(n-e),l)}}let G=null,W=null;function normalizeUnicode(t){if(!G){G=/([\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;W=new Map([["ſt","ſt"]])}return t.replaceAll(G,(t,e,i)=>e?e.normalize("NFKC"):W.get(i))}function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(e[],makeMap=()=>new Map,makeObj=()=>Object.create(null);function MathClamp(t,e,i){return Math.min(Math.max(t,e),i)}"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(t){return t.reduce((t,e)=>t+e,0)});class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const n=t.name;if("#text"===n)i=t.value;else{if(!XfaText.shouldBuildText(n))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class XfaLayer{static setupStorage(t,e,i,n,s){const r=n.getValue(e,{value:null});switch(i.name){case"textarea":null!==r.value&&(t.textContent=r.value);if("print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})});break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){r.value===i.attributes.xfaOn?t.setAttribute("checked",!0):r.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===s)break;t.addEventListener("change",t=>{n.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{null!==r.value&&t.setAttribute("value",r.value);if("print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})})}break;case"select":if(null!==r.value){t.setAttribute("value",r.value);for(const t of i.children)t.attributes.value===r.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const i=t.target.options,s=-1===i.selectedIndex?"":i[i.selectedIndex].value;n.setValue(e,{value:s})})}}static setAttributes({html:t,element:e,storage:i=null,intent:n,linkService:s}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${n}`);for(const[e,i]of Object.entries(r))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!a||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}a&&s.addLinkAttributes(t,r.href,r.newWindow);i&&r.dataId&&this.setupStorage(t,r.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,n=t.xfaHtml,s=t.intent||"display",r=document.createElement(n.name);n.attributes&&this.setAttributes({html:r,element:n,intent:s,linkService:i});const a="richText"!==s,o=t.div;o.append(r);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}a&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===n.children.length){if(n.value){const t=document.createTextNode(n.value);r.append(t);a&&XfaText.shouldBuildText(n.name)&&l.push(t)}return{textDivs:l}}const h=[[n,-1,r]];for(;h.length>0;){const[t,n,r]=h.at(-1);if(n+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t);r.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);r.append(c);o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:s,linkService:i});if(o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);a&&XfaText.shouldBuildText(d)&&l.push(t);c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const j="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"blob":return i.blob();case"bytes":return i.bytes();case"json":return i.json()}return i.text()}return new Promise((i,n)=>{const s=new XMLHttpRequest;s.open("GET",t,!0);s.responseType="bytes"===e?"arraybuffer":e;s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE)if(200!==s.status&&0!==s.status)n(new Error(s.statusText));else{switch(e){case"bytes":i(new Uint8Array(s.response));return;case"blob":case"json":i(s.response);return}i(s.responseText)}};s.send(null)})}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:n,offsetX:s=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=n;this.offsetX=s;this.offsetY=r;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;(n%=360)<0&&(n+=360);switch(n){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(a){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+s;g=Math.abs(o-t[0])*i+r;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+s;g=Math.abs(l-t[1])*i+r;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const t=this.viewBox;return shadow(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:n=this.offsetY,dontFlip:s=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}convertToViewportPoint(t,e){const i=[t,e];Util.applyTransform(i,this.transform);return i}convertToViewportRectangle(t){const e=[t[0],t[1]];Util.applyTransform(e,this.transform);const i=[t[2],t[3]];Util.applyTransform(i,this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){const i=[t,e];Util.applyInverseTransform(i,this.transform);return i}}class RenderingCancelledException extends H{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i{try{return new URL(t)}catch{try{return new URL(decodeURIComponent(t))}catch{try{return new URL(t,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(t),"https://foo.bar")}catch{return null}}}}})(t);if(!i)return e;const decode=t=>{try{let e=decodeURIComponent(t);if(e.includes("/")){e=stripPath(e);if(/^\.pdf$/i.test(e))return t}return e}catch{return t}},n=/\.pdf$/i,s=stripPath(i.pathname);if(n.test(s))return decode(s);if(i.searchParams.size>0){const getLast=t=>[...t].findLast(t=>n.test(t)),t=getLast(i.searchParams.values())??getLast(i.searchParams.keys());if(t)return decode(t)}if(i.hash){const t=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(i.hash);if(t)return decode(t[0])}return e}class StatTimer{started=Object.create(null);times=[];time(t){t in this.started&&warn(`Timer is already running for ${t}`);this.started[t]=Date.now()}timeEnd(t){t in this.started||warn(`Timer has not been started for ${t}`);this.times.push({name:t,start:this.started[t],end:Date.now()});delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:n,end:s}of this.times)t.push(`${i.padEnd(e)} ${s-n}ms\n`);return t.join("")}}function isValidFetchUrl(t,e){const i=e?URL.parse(t,e):URL.parse(t);return/https?:/.test(i?.protocol??"")}function noContextMenu(t){t.preventDefault()}function stopEvent(t){t.preventDefault();t.stopPropagation()}function deprecated(t){console.log("Deprecated API usage: "+t)}class PDFDateString{static#i;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#i.exec(t);if(!e)return null;const i=parseInt(e[1],10);let n=parseInt(e[2],10);n=n>=1&&n<=12?n-1:0;let s=parseInt(e[3],10);s=s>=1&&s<=31?s:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){r+=h;a+=d}else if("+"===l){r-=h;a-=d}return new Date(Date.UTC(i,n,s,r,a,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:n,height:s}=t.attributes.style,r=[0,0,parseInt(n),parseInt(s)];return new PageViewport({viewBox:r,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map(t=>parseInt(t));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:n,d:s,e:r,f:a}=t.getTransform();return[e,i,n,s,r,a]}function getCurrentTransformInverse(t){const{a:e,b:i,c:n,d:s,e:r,f:a}=t.getTransform().invertSelf();return[e,i,n,s,r,a]}function setLayerDimensions(t,e,i=!1,n=!0){if(e instanceof PageViewport){const{pageWidth:n,pageHeight:s}=e.rawDims,{style:r}=t,a=FeatureTest.isCSSRoundSupported,o=`var(--total-scale-factor) * ${n}px`,l=`var(--total-scale-factor) * ${s}px`,h=a?`round(down, ${o}, var(--scale-round-x))`:`calc(${o})`,d=a?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;if(i&&e.rotation%180!=0){r.width=d;r.height=h}else{r.width=h;r.height=d}}n&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const{pixelRatio:t}=OutputScale;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,i,n,s=-1){let r=1/0,a=1/0,o=1/0;(i=OutputScale.capPixels(i,s))>0&&(r=Math.sqrt(i/(t*e)));if(-1!==n){a=n/t;o=n/e}const l=Math.min(r,a,o);if(this.sx>l||this.sy>l){this.sx=l;this.sy=l;return!0}return!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}}const $=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class ColorScheme{static get isDarkMode(){return shadow(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}class CSSConstants{static get commentForegroundColor(){const t=document.createElement("span");t.classList.add("comment","sidebar");const{style:e}=t;e.width=e.height="0";e.display="none";e.color="var(--comment-fg-color)";document.body.append(t);const{color:i}=window.getComputedStyle(t);t.remove();return shadow(this,"commentForegroundColor",getRGB(i))}}function applyOpacity(t,e,i,n){const s=255*(1-(n=MathClamp(n??1,0,1)));return[t=Math.round(t*n+s),e=Math.round(e*n+s),i=Math.round(i*n+s)]}function RGBToHSL(t,e){const i=t[0]/255,n=t[1]/255,s=t[2]/255,r=Math.max(i,n,s),a=Math.min(i,n,s),o=(r+a)/2;if(r===a)e[0]=e[1]=0;else{const t=r-a;e[1]=o<.5?t/(r+a):t/(2-r-a);switch(r){case i:e[0]=60*((n-s)/t+(ns?(n+.05)/(s+.05):(s+.05)/(n+.05)}const X=new Map;function findContrastColor(t,e){const i=t[0]+256*t[1]+65536*t[2]+16777216*e[0]+4294967296*e[1]+1099511627776*e[2];let n=X.get(i);if(n)return n;const s=new Float32Array(9),r=s.subarray(0,3),a=s.subarray(3,6);RGBToHSL(t,a);const o=s.subarray(6,9);RGBToHSL(e,o);const l=o[2]<.5,h=l?12:4.5;a[2]=l?Math.sqrt(a[2]):1-Math.sqrt(1-a[2]);if(contrastRatio(a,o,r)i;){const i=a[2]=(t+e)/2;l===contrastRatio(a,o,r)=0&&this.#o.splice(e,1)}#c(t){for(const e of this.#o)e(t)}#u(t){if(this.#s)return;const e=this.#a,i=this.#s=new Uint32Array(e);this.#r=new Int32Array(i);const n=this.#n=new Map;if(t)for(let t=1;t<=e;t++){i[t-1]=t;n.set(t,[t])}}#p(){const t=this.#n,e=this.#s;t.clear();for(let i=0,n=this.#a;it===e+1)&&this.#d()}deletePages(t){this.#u(!0);const e=this.#s,i=this.#n;this.pagesNumber-=t.length;this.#u(!1);const n=this.#s;let s=0,r=0;for(const i of t){const t=i-1;if(t!==s){n.set(e.subarray(s,t),r);r+=t-s}s=t+1}sthis.#s[t-1]);this.#c({type:"copy",pageNumbers:t})}pastePages(t){this.#u(!0);const e=this.#s,i=this.#n,n=this.#h,s=new Map;let r=t;for(const t of n)s.set(++r,t);this.pagesNumber+=n.length;this.#u(!1);const a=this.#s;a.set(e.subarray(0,t),0);a.set(this.#l,t);a.set(e.subarray(t),t+n.length);this.#g(i,s);this.#p();this.#c({type:"paste"});this.#l=null}#g(t,e){const i=this.#r,n=this.#s,s=new Map;for(let r=0,a=this.#a;rt[0]-e[0]);for(let i=0,n=t.length;i{e.delete()},{signal:e._signal});this.#w.append(i)}get#D(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#_(e);this.#w.append(e,this.#D);this.#y=t}addComment(t,e=null){if(this.#A)return;const i=t.renderForToolbar();if(!i)return;this.#_(i);const n=this.#v=this.#D;if(e){this.#w.insertBefore(i,e);this.#w.insertBefore(n,e)}else this.#w.append(i,n);this.#A=t;t.toolbar=this}addColorPicker(t){if(this.#f)return;this.#f=t;const e=t.renderButton();this.#_(e);this.#w.append(e,this.#D)}async addEditSignatureButton(t){const e=this.#x=await t.renderEditButton(this.#b);this.#_(e);this.#w.append(e,this.#D)}removeButton(t){if("comment"===t){this.#A?.removeToolbarCommentButton();this.#A=null;this.#v?.remove();this.#v=null}}async addButton(t,e){switch(t){case"colorPicker":e&&this.addColorPicker(e);break;case"altText":e&&await this.addAltText(e);break;case"editSignature":e&&await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":e&&this.addComment(e)}}async addButtonBefore(t,e,i){if(!e&&"comment"===t)return;const n=this.#w.querySelector(i);n&&"comment"===t&&this.addComment(e,n)}updateEditSignatureButton(t){this.#x&&(this.#x.title=t)}remove(){this.#m.remove();this.#f?.destroy();this.#f=null}}class FloatingToolbar{#w=null;#m=null;#P;constructor(t){this.#P=t}#M(){const t=this.#m=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");const e=this.#P._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",noContextMenu,{signal:e});const i=this.#w=document.createElement("div");i.className="buttons";t.append(i);this.#P.hasCommentManager()&&this.#k("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#P.commentSelection("floating_button")});this.#k("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#P.highlightSelection("floating_button")});return t}#I(t,e){let i=0,n=0;for(const s of t){const t=s.y+s.height;if(ti){n=r;i=t}else e?r>n&&(n=r):r=1}static clearPointerType(){CurrentPointers.#L=null}static clearPointerIds(){CurrentPointers.#F=NaN;CurrentPointers.#R=null}static clearTimeStamp(){CurrentPointers.#B=NaN}}class IdManager{#O=0;get id(){return`${u}${this.#O++}`}}class ImageManager{#N=getUuid();#O=0;#U=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,';return shadow(this,"_isSVGFittingCanvas",e.decode().then(()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]}))}async#H(t,e){this.#U||=new Map;let i=this.#U.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#N}_${this.#O++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,n=new FileReader,s=new Image,r=new Promise((t,r)=>{s.onload=()=>{i.bitmap=s;i.isSvg=!0;t()};n.onload=async()=>{const t=i.svgUrl=n.result;s.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};s.onerror=n.onerror=r});n.readAsDataURL(t);await r}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#U.set(t,i);i&&this.#U.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:n,type:s}=t;return this.#H(`${e}_${i}_${n}_${s}`,t)}async getFromUrl(t){return this.#H(t,t)}async getFromBlob(t,e){const i=await e;return this.#H(t,i)}async getFromId(t){this.#U||=new Map;const e=this.#U.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#U||=new Map;let i=this.#U.get(t);if(i?.bitmap){i.refCounter+=1;return i}const n=new OffscreenCanvas(e.width,e.height);n.getContext("2d").drawImage(e,0,0);i={bitmap:n.transferToImageBitmap(),id:`image_${this.#N}_${this.#O++}`,refCounter:1,isSvg:!1};this.#U.set(t,i);this.#U.set(i.id,i);return i}getSvgUrl(t){const e=this.#U.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#U||=new Map;const e=this.#U.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#N}_`)}}class CommandManager{#z=[];#G=!1;#W;#V=-1;constructor(t=128){this.#W=t}add({cmd:t,undo:e,post:i,mustExec:n,type:s=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){n&&t();if(this.#G)return;const o={cmd:t,undo:e,post:i,type:s};if(-1===this.#V){this.#z.length>0&&(this.#z.length=0);this.#V=0;this.#z.push(o);return}if(r&&this.#z[this.#V].type===s){a&&(o.undo=this.#z[this.#V].undo);this.#z[this.#V]=o;return}const l=this.#V+1;if(l===this.#W)this.#z.splice(0,1);else{this.#V=l;l=0;e--)if(this.#z[e].type!==t){this.#z.splice(e+1,this.#V-e);this.#V=e;return}this.#z.length=0;this.#V=-1}}destroy(){this.#z=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=FeatureTest.platform;for(const[i,n,s={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:n,options:s});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:n,options:s});this.allKeys.add(t.split("+").at(-1))}}}#j(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#j(e));if(!i)return;const{callback:n,options:{bubbles:s=!1,args:r=[],checker:a=null}}=i;if(!a||a(t,e)){n.bind(t,...r,e)();s||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";e.style.colorScheme="only light";document.body.append(e);for(const i of t.keys()){e.style.color=i;const n=window.getComputedStyle(e).color;t.set(i,getRGB(n))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every((t,i)=>t===e[i]))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#$=new AbortController;#X=null;#q=null;#K=new Map;#Y=new Map;#Q=null;#J=null;#Z=null;#tt=new CommandManager;#et=null;#it=null;#nt=null;#st=0;#rt=new Set;#at=null;#ot=null;#lt=new Set;_editorUndoBar=null;#ht=!1;#dt=!1;#ct=!1;#ut=null;#pt=null;#gt=null;#mt=null;#ft=!1;#bt=null;#wt=new IdManager;#yt=!1;#At=!1;#vt=!1;#xt=null;#Et=null;#Ct=null;#St=null;#Tt=null;#_t=p.NONE;#Dt=new Set;#Pt=null;#Mt=null;#kt=null;#It=null;#Ft=null;#Rt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Bt=[0,0];#Lt=null;#Ot=null;#Nt=null;#Ut=null;#Ht=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#Ot.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#Ot.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#Ot.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,n,s,r,a,o,l,h,d,c,u,p,g,m){const f=this._signal=this.#$.signal;this.#Ot=t;this.#Nt=e;this.#Ut=i;this.#Q=n;this.#et=s;this.#Mt=r;this.#Ft=o;this._eventBus=a;a._on("editingaction",this.onEditingAction.bind(this),{signal:f});a._on("pagechanging",this.onPageChanging.bind(this),{signal:f});a._on("scalechanging",this.onScaleChanging.bind(this),{signal:f});a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:f});a._on("setpreference",this.onSetPreference.bind(this),{signal:f});a._on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),{signal:f});window.addEventListener("pointerdown",()=>{this.#At=!0},{capture:!0,signal:f});window.addEventListener("pointerup",()=>{this.#At=!1},{capture:!0,signal:f});window.addEventListener("beforeunload",this.#zt.bind(this),{capture:!0,signal:f});this.#Gt();this.#Wt();this.#Vt();this.#J=o.annotationStorage;this.#ut=o.filterFactory;this.#kt=l;this.#mt=h||null;this.#ht=d;this.#dt=c;this.#ct=u;this.#Tt=p||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=g||null;this._supportsPinchToZoom=!1!==m;s?.setSidebarUiManager(this)}destroy(){this.#Ht?.resolve();this.#Ht=null;this.#$?.abort();this.#$=null;this._signal=null;for(const t of this.#Y.values())t.destroy();this.#Y.clear();this.#K.clear();this.#lt.clear();this.#St?.clear();this.#X=null;this.#Dt.clear();this.#tt.destroy();this.#Q?.destroy();this.#et?.destroy();this.#Mt?.destroy();this.#bt?.hide();this.#bt=null;this.#Ct?.destroy();this.#Ct=null;this.#q=null;if(this.#pt){clearTimeout(this.#pt);this.#pt=null}if(this.#Lt){clearTimeout(this.#Lt);this.#Lt=null}this._editorUndoBar?.destroy();this.#Ft=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#Tt}get useNewAltTextFlow(){return this.#dt}get useNewAltTextWhenAddingImage(){return this.#ct}get hcmFilter(){return shadow(this,"hcmFilter",this.#kt?this.#ut.addHCMFilter(this.#kt.foreground,this.#kt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#Ot).direction)}get _highlightColors(){return shadow(this,"_highlightColors",this.#mt?new Map(this.#mt.split(",").map(t=>{(t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase();return t})):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return shadow(this,"highlightColors",null);const e=new Map,i=!!this.#kt;for(const[n,s]of t){const t=n.endsWith("_HCM");i&&t?e.set(n.replace("_HCM",""),s):i||t||e.set(n,s)}return shadow(this,"highlightColors",e)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#nt=t}setMainHighlightColorPicker(t){this.#Ct=t}editAltText(t,e=!1){this.#Q?.editAltText(this,t,e)}hasCommentManager(){return!!this.#et}editComment(t,e,i,n){this.#et?.showDialog(this,t,e,i,n)}selectComment(t,e){const i=this.#Y.get(t),n=i?.getEditorByUID(e);n?.toggleComment(!0,!0)}updateComment(t){this.#et?.updateComment(t.getData())}updatePopupColor(t){this.#et?.updatePopupColor(t)}removeComment(t){this.#et?.removeComments([t.uid])}deleteComment(t,e){const undo=()=>{t.comment=e};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,"comment");this.toggleComment(null);t.comment=null},undo,mustExec:!0})}toggleComment(t,e,i=void 0){this.#et?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#et?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#et?.dialogElement||null}async waitForEditorsRendered(t){if(this.#Y.has(t-1))return;const{resolve:e,promise:i}=Promise.withResolvers(),onEditorsRendered=i=>{if(i.pageNumber===t){this._eventBus._off("editorsrendered",onEditorsRendered);e()}};this._eventBus.on("editorsrendered",onEditorsRendered);await i}getSignature(t){this.#Mt?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#Mt}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#ct=e}onPageChanging({pageNumber:t}){this.#st=t-1}deletePage(t){for(const e of this.getEditors(t))e.remove();this.#Y.delete(t);this.#st===t&&(this.#st=0)}focusMainContainer(){this.#Ot.focus()}findParent(t,e){for(const i of this.#Y.values()){const{x:n,y:s,width:r,height:a}=i.div.getBoundingClientRect();if(t>=n&&t<=n+r&&e>=s&&e<=s+a)return i}return null}disableUserSelect(t=!1){this.#Nt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#lt.add(t)}removeShouldRescale(t){this.#lt.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#lt)t.onScaleChanging();this.#nt?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#jt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#$t(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#Y.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t="",e=!1){const i=document.getSelection();if(!i||i.isCollapsed)return;const{anchorNode:n,anchorOffset:s,focusNode:r,focusOffset:a}=i,o=i.toString(),l=this.#jt(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();const d=this.#$t(l),c=this.#_t===p.NONE,callback=()=>{const i=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:n,anchorOffset:s,focusNode:r,focusOffset:a,text:o});c&&this.showAllEditors("highlight",!0,!0);e&&i?.editComment()};c?this.switchToMode(p.HIGHLIGHT,callback):callback()}commentSelection(t=""){this.highlightSelection(t,!0)}#zt(t){this.commitOrRemove();this.currentLayer?.endDrawingSession(!1)}#Xt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#jt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#bt||=new FloatingToolbar(this);this.#bt.show(e,i,"ltr"===this.direction)}}getAndRemoveDataFromAnnotationStorage(t){if(!this.#J)return null;const e=`${u}${t}`,i=this.#J.getRawValue(e);i&&this.#J.remove(e);return i}addToAnnotationStorage(t){t.isEmpty()||!this.#J||this.#J.has(t.id)||this.#J.setValue(t.id,t)}a11yAlert(t,e=null){const i=this.#Ut;if(i){i.setAttribute("data-l10n-id",t);e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args")}}#qt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#Pt){this.#bt?.hide();this.#Pt=null;this.#Kt({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#Pt)return;const i=this.#jt(t).closest(".textLayer");if(i){this.#bt?.hide();this.#Pt=e;this.#Kt({hasSelectedText:!0});if(this.#_t===p.HIGHLIGHT||this.#_t===p.NONE){this.#_t===p.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#ft=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#_t===p.HIGHLIGHT?this.#$t(i):null;t?.toggleDrawing();if(this.#At){const e=new AbortController,i=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Yt("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:i});window.addEventListener("blur",pointerup,{signal:i})}else{t?.toggleDrawing(!0);this.#Yt("main_toolbar")}}}}else if(this.#Pt){this.#bt?.hide();this.#Pt=null;this.#Kt({hasSelectedText:!1})}}#Yt(t=""){this.#_t===p.HIGHLIGHT?this.highlightSelection(t):this.#ht&&this.#Xt()}#Gt(){document.addEventListener("selectionchange",this.#qt.bind(this),{signal:this._signal})}#Qt(){if(this.#gt)return;this.#gt=new AbortController;const t=this.combinedSignal(this.#gt);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Jt(){this.#gt?.abort();this.#gt=null}blur(){this.isShiftKeyDown=!1;if(this.#ft){this.#ft=!1;this.#Yt("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#Dt)if(e.div.contains(t)){this.#Et=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#Et)return;const[t,e]=this.#Et;this.#Et=null;e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal});e.focus()}#Vt(){if(this.#xt)return;this.#xt=new AbortController;const t=this.combinedSignal(this.#xt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Zt(){this.#xt?.abort();this.#xt=null}#te(){if(this.#it)return;this.#it=new AbortController;const t=this.combinedSignal(this.#it);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})}#ee(){this.#it?.abort();this.#it=null}#Wt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Vt();this.setEditingState(!0)}removeEditListeners(){this.#Zt();this.setEditingState(!1)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#ot)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#ot)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#X?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#Dt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#ot)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const n=this.currentLayer;try{const t=[];for(const e of i){const i=await n.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#ie(e);this.#ne(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#_t===p.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#ft){this.#ft=!1;this.#Yt("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")}}#Kt(t){if(Object.entries(t).some(([t,e])=>this.#Rt[t]!==e)){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#Rt,t)});this.#_t===p.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#se([[g.HIGHLIGHT_FREE,!0]])}}#se(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#Qt();this.#te();this.#Kt({isEditing:this.#_t!==p.NONE,isEmpty:this.#re(),hasSomethingToUndo:this.#tt.hasSomethingToUndo(),hasSomethingToRedo:this.#tt.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Jt();this.#ee();this.#Kt({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#ot){this.#ot=t;for(const t of this.#ot)this.#se(t.defaultPropertiesToUpdate)}}getId(){return this.#wt.id}get currentLayer(){return this.#Y.get(this.#st)}getLayer(t){return this.#Y.get(t)}get currentPageIndex(){return this.#st}addLayer(t){this.#Y.set(t.pageIndex,t);this.#yt?t.enable():t.disable()}removeLayer(t){this.#Y.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,n=!1,s=!1,r=!1){if(this.#_t!==t){if(this.#Ht){await this.#Ht.promise;if(!this.#Ht)return}this.#Ht=Promise.withResolvers();this.#nt?.commitOrRemove();this.#_t===p.POPUP&&this.#et?.hideSidebar();this.#et?.destroyPopup();this.#_t=t;if(t!==p.NONE){for(const t of this.#K.values())t.addStandaloneCommentButton();t===p.SIGNATURE&&await(this.#Mt?.loadSignatures());i&&CurrentPointers.clearPointerType();this.setEditingState(!0);await this.#ae();this.unselectAll();for(const e of this.#Y.values())e.updateMode(t);if(t===p.POPUP){this.#q||=await this.#Ft.getAnnotationsByType(new Set(this.#ot.map(t=>t._editorType)));const t=new Set,e=[];for(const i of this.#K.values()){const{annotationElementId:n,hasComment:s,deleted:r}=i;n&&t.add(n);s&&!r&&e.push(i.getData())}for(const i of this.#q){const{id:n,popupRef:s,contentsObj:r}=i;s&&r?.str&&!t.has(n)&&!this.#rt.has(n)&&e.push(i)}this.#et?.showSidebar(e)}if(e){for(const t of this.#K.values())if(t.uid===e){this.setSelected(t);r?t.editComment():s?t.enterInEditMode():t.focus()}else t.unselect();this.#Ht.resolve()}else{n&&this.addNewEditorFromKeyboard();this.#Ht.resolve()}}else{this.setEditingState(!1);this.#oe();for(const t of this.#K.values())t.hideStandaloneCommentButton();this._editorUndoBar?.hide();this.toggleComment(null);this.#Ht.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#_t&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#ot){switch(t){case g.CREATE:this.currentLayer.addNewEditor(e);return;case g.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#It||=new Map).set(t,e);this.showAllEditors("highlight",e)}if(this.hasSelection)for(const i of this.#Dt)i.updateParams(t,e);else for(const i of this.#ot)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#K.values())i.editorType===t&&i.show(e);(this.#It?.get(g.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#se([[g.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#vt!==t){this.#vt=t;for(const e of this.#Y.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#ae(){if(!this.#yt){this.#yt=!0;const t=[];for(const e of this.#Y.values())t.push(e.enable());await Promise.all(t);for(const t of this.#K.values())t.enable()}}#oe(){this.unselectAll();if(this.#yt){this.#yt=!1;for(const t of this.#Y.values())t.disable();for(const t of this.#K.values())t.disable()}}*getEditors(t){for(const e of this.#K.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#K.get(t)}addEditor(t){this.#K.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#pt&&clearTimeout(this.#pt);this.#pt=setTimeout(()=>{this.focusMainContainer();this.#pt=null},0)}this.#K.delete(t.id);t.annotationElementId&&this.#St?.delete(t.annotationElementId);this.unselect(t);t.annotationElementId&&this.#rt.has(t.annotationElementId)||this.#J?.remove(t.id)}addDeletedAnnotationElement(t){this.#rt.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#rt.has(t)}removeDeletedAnnotationElement(t){this.#rt.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#ie(t){const e=this.#Y.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#X!==t){this.#X=t;t&&this.#se(t.propertiesToUpdate)}}get#le(){let t=null;for(t of this.#Dt);return t}updateUI(t){this.#le===t&&this.#se(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#se(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#Dt.has(t)){this.#Dt.delete(t);t.unselect();this.#Kt({hasSelectedEditor:this.hasSelection})}else{this.#Dt.add(t);t.select();this.#se(t.propertiesToUpdate);this.#Kt({hasSelectedEditor:!0})}}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid});this.#nt?.commitOrRemove();for(const e of this.#Dt)e!==t&&e.unselect();this.#Dt.clear();this.#Dt.add(t);t.select();this.#se(t.propertiesToUpdate);this.#Kt({hasSelectedEditor:!0})}isSelected(t){return this.#Dt.has(t)}get firstSelectedEditor(){return this.#Dt.values().next().value}unselect(t){t.unselect();this.#Dt.delete(t);this.#Kt({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#Dt.size}get isEnterHandled(){return 1===this.#Dt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#tt.undo();this.#Kt({hasSomethingToUndo:this.#tt.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#re()});this._editorUndoBar?.hide()}redo(){this.#tt.redo();this.#Kt({hasSomethingToUndo:!0,hasSomethingToRedo:this.#tt.hasSomethingToRedo(),isEmpty:this.#re()})}addCommands(t){this.#tt.add(t);this.#Kt({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#re()})}cleanUndoStack(t){this.#tt.cleanType(t)}#re(){if(0===this.#K.size)return!0;if(1===this.#K.size)for(const t of this.#K.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#Dt],undo=()=>{for(const t of e)this.#ie(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#X?.commitOrRemove()}hasSomethingToControl(){return this.#X||this.hasSelection}#ne(t){for(const t of this.#Dt)t.unselect();this.#Dt.clear();for(const e of t)if(!e.isEmpty()){this.#Dt.add(e);e.select()}this.#Kt({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#Dt)t.commit();this.#ne(this.#K.values())}unselectAll(){if(this.#X){this.#X.commitOrRemove();if(this.#_t!==p.NONE)return}if(!this.#nt?.commitOrRemove()&&this.hasSelection){for(const t of this.#Dt)t.unselect();this.#Dt.clear();this.#Kt({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#Bt[0]+=t;this.#Bt[1]+=e;const[n,s]=this.#Bt,r=[...this.#Dt];this.#Lt&&clearTimeout(this.#Lt);this.#Lt=setTimeout(()=>{this.#Lt=null;this.#Bt[0]=this.#Bt[1]=0;this.addCommands({cmd:()=>{for(const t of r)if(this.#K.has(t.id)){t.translateInPage(n,s);t.translationDone()}},undo:()=>{for(const t of r)if(this.#K.has(t.id)){t.translateInPage(-n,-s);t.translationDone()}},mustExec:!1})},1e3);for(const i of r){i.translateInPage(t,e);i.translationDone()}}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#at=new Map;for(const t of this.#Dt)this.#at.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#at)return!1;this.disableUserSelect(!1);const t=this.#at;this.#at=null;let e=!1;for(const[{x:i,y:n,pageIndex:s},r]of t){r.newX=i;r.newY=n;r.newPageIndex=s;e||=i!==r.savedX||n!==r.savedY||s!==r.savedPageIndex}if(!e)return!1;const move=(t,e,i,n)=>{if(this.#K.has(t.id)){const s=this.#Y.get(n);if(s)t._setParentAndPosition(s,e,i);else{t.pageIndex=n;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:n,newPageIndex:s}]of t)move(e,i,n,s)},undo:()=>{for(const[e,{savedX:i,savedY:n,savedPageIndex:s}]of t)move(e,i,n,s)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#at)for(const i of this.#at.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#Dt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#X===t}getActive(){return this.#X}getMode(){return this.#_t}isEditingMode(){return this.#_t!==p.NONE}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,n=e.rangeCount;i({x:(e-n)/r,y:1-(t+a-i)/s,width:o/r,height:a/s});break;case"180":a=(t,e,a,o)=>({x:1-(t+a-i)/s,y:1-(e+o-n)/r,width:a/s,height:o/r});break;case"270":a=(t,e,a,o)=>({x:1-(e+o-n)/r,y:(t-i)/s,width:o/r,height:a/s});break;default:a=(t,e,a,o)=>({x:(t-i)/s,y:(e-n)/r,width:a/s,height:o/r})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation(),{signal:i});const onClick=t=>{t.preventDefault();this.#b._uiManager.editAltText(this.#b);this.#we&&this.#b._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Ae}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",e=>{if(e.target===t&&"Enter"===e.key){this.#ge=!0;onClick(e)}},{signal:i});await this.#ve();return t}get#Ae(){return(this.#y?"added":null===this.#y&&this.guessedText&&"review")||"missing"}finish(){if(this.#de){this.#de.focus({focusVisible:this.#ge});this.#ge=!1}}isEmpty(){return this.#we?null===this.#y:!this.#y&&!this.#he}hasData(){return this.#we?null!==this.#y||!!this.#fe:this.isEmpty()}get guessedText(){return this.#fe}async setGuessedText(t){if(null===this.#y){this.#fe=t;this.#be=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#ve()}}toggleAltTextBadge(t=!1){if(this.#we&&!this.#y){if(!this.#me){const t=this.#me=document.createElement("div");t.className="noAltTextBadge";this.#b.div.append(t)}this.#me.classList.toggle("hidden",!t)}else{this.#me?.remove();this.#me=null}}serialize(t){let e=this.#y;t||this.#fe!==e||(e=this.#be);return{altText:e,decorative:this.#he,guessedText:this.#fe,textWithDisclaimer:this.#be}}get data(){return{altText:this.#y,decorative:this.#he}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:n,cancel:s=!1}){if(i){this.#fe=i;this.#be=n}if(this.#y!==t||this.#he!==e){if(!s){this.#y=t;this.#he=e}this.#ve()}}toggle(t=!1){if(this.#de){if(!t&&this.#pe){clearTimeout(this.#pe);this.#pe=null}this.#de.disabled=!t}}shown(){this.#b._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Ae}})}destroy(){this.#de?.remove();this.#de=null;this.#ce=null;this.#ue=null;this.#me?.remove();this.#me=null}async#ve(){const t=this.#de;if(!t)return;if(this.#we){t.classList.toggle("done",!!this.#y);t.setAttribute("data-l10n-id",AltText.#ye[this.#Ae]);this.#ce?.setAttribute("data-l10n-id",AltText.#ye[`${this.#Ae}-label`]);if(!this.#y){this.#ue?.remove();return}}else{if(!this.#y&&!this.#he){t.classList.remove("done");this.#ue?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#ue;if(!e){this.#ue=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#b.id}`;const i=100,n=this.#b._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#pe);this.#pe=null},{once:!0});t.addEventListener("mouseenter",()=>{this.#pe=setTimeout(()=>{this.#pe=null;this.#ue.classList.add("show");this.#b._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n});t.addEventListener("mouseleave",()=>{if(this.#pe){clearTimeout(this.#pe);this.#pe=null}this.#ue?.classList.remove("show")},{signal:n})}if(this.#he)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#y}e.parentNode||t.append(e);const i=this.#b.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class Comment{#xe=null;#Ee=null;#Ce=!1;#b=null;#Se=null;#Te=null;#_e=null;#De=null;#Pe=!1;#Me=null;constructor(t){this.#b=t}renderForToolbar(){const t=this.#Ee=document.createElement("button");t.className="comment";return this.#M(t,!1)}renderForStandalone(){const t=this.#xe=document.createElement("button");t.className="annotationCommentButton";const e=this.#b.commentButtonPosition;if(e){const{style:i}=t;i.insetInlineEnd=`calc(${100*("ltr"===this.#b._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`;i.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const n=this.#b.commentButtonColor;n&&(i.backgroundColor=n)}return this.#M(t,!0)}focusButton(){setTimeout(()=>{(this.#xe??this.#Ee)?.focus()},0)}onUpdatedColor(){if(!this.#xe)return;const t=this.#b.commentButtonColor;t&&(this.#xe.style.backgroundColor=t);this.#b._uiManager.updatePopupColor(this.#b)}get commentButtonWidth(){return(this.#xe?.getBoundingClientRect().width??0)/this.#b.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#Me)return this.#Me;if(!this.#xe)return null;const{x:t,y:e,height:i}=this.#xe.getBoundingClientRect(),{x:n,y:s,width:r,height:a}=this.#b.parent.boundingClientRect;return[(t-n)/r,(e+i-s)/a]}set commentPopupPositionInLayer(t){this.#Me=t}hasDefaultPopupPosition(){return null===this.#Me}removeStandaloneCommentButton(){this.#xe?.remove();this.#xe=null}removeToolbarCommentButton(){this.#Ee?.remove();this.#Ee=null}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#xe){this.#xe.classList.toggle("selected",t);this.#xe.ariaExpanded=e}}#M(t,e){if(!this.#b._uiManager.hasCommentManager())return null;t.tabIndex="0";t.ariaHasPopup="dialog";if(e){t.ariaControls="commentPopup";t.setAttribute("data-l10n-id","pdfjs-show-comment-button")}else{t.ariaControlsElements=[this.#b._uiManager.getCommentDialogElement()];t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button")}const i=this.#b._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",noContextMenu,{signal:i});if(e){t.addEventListener("focusin",t=>{this.#b._focusEventsAllowed=!1;stopEvent(t)},{capture:!0,signal:i});t.addEventListener("focusout",t=>{this.#b._focusEventsAllowed=!0;stopEvent(t)},{capture:!0,signal:i})}t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const onClick=e=>{e.preventDefault();t===this.#Ee?this.edit():this.#b.toggleComment(!0)};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",e=>{if(e.target===t&&"Enter"===e.key){this.#Ce=!0;onClick(e)}},{signal:i});t.addEventListener("pointerenter",()=>{this.#b.toggleComment(!1,!0)},{signal:i});t.addEventListener("pointerleave",()=>{this.#b.toggleComment(!1,!1)},{signal:i});return t}edit(t){const e=this.commentPopupPositionInLayer;let i,n;if(e)[i,n]=e;else{[i,n]=this.#b.commentButtonPosition;const{width:t,height:e,x:s,y:r}=this.#b;i=s+i*t;n=r+n*e}const s=this.#b.parent.boundingClientRect,{x:r,y:a,width:o,height:l}=s;this.#b._uiManager.editComment(this.#b,r+i*o,a+n*l,{...t,parentDimensions:s})}finish(){if(this.#Ee){this.#Ee.focus({focusVisible:this.#Ce});this.#Ce=!1}}isDeleted(){return this.#Pe||""===this.#_e}isEmpty(){return null===this.#_e}hasBeenEdited(){return this.isDeleted()||this.#_e!==this.#Se}serialize(){return this.data}get data(){return{text:this.#_e,richText:this.#Te,date:this.#De,deleted:this.isDeleted()}}set data(t){t!==this.#_e&&(this.#Te=null);if(null!==t){this.#_e=t;this.#De=new Date;this.#Pe=!1}else{this.#_e="";this.#Pe=!0}}restoreData({text:t,richText:e,date:i}){this.#_e=t;this.#Te=e;this.#De=i;this.#Pe=!1}setInitialText(t,e=null){this.#Se=t;this.data=t;this.#De=null;this.#Te=e}shown(){}destroy(){this.#Ee?.remove();this.#Ee=null;this.#xe?.remove();this.#xe=null;this.#_e="";this.#Te=null;this.#De=null;this.#b=null;this.#Ce=!1;this.#Pe=!1}}class TouchManager{#Ot;#ke=!1;#Ie=null;#Fe;#Re;#Be;#Le;#Oe=null;#Ne;#Ue=null;#He;#ze=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:n=null,onPinching:s=null,onPinchEnd:r=null,signal:a}){this.#Ot=t;this.#Ie=i;this.#Fe=e;this.#Re=n;this.#Be=s;this.#Le=r;this.#He=new AbortController;this.#Ne=AbortSignal.any([a,this.#He.signal]);t.addEventListener("touchstart",this.#Ge.bind(this),{passive:!1,signal:this.#Ne})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/OutputScale.pixelRatio}#Ge(t){if(this.#Fe?.())return;if(1===t.touches.length){if(this.#Oe)return;const t=this.#Oe=new AbortController,e=AbortSignal.any([this.#Ne,t.signal]),i=this.#Ot,n={capture:!0,signal:e,passive:!1},cancelPointerDown=t=>{if("touch"===t.pointerType){this.#Oe?.abort();this.#Oe=null}};i.addEventListener("pointerdown",t=>{if("touch"===t.pointerType){stopEvent(t);cancelPointerDown(t)}},n);i.addEventListener("pointerup",cancelPointerDown,n);i.addEventListener("pointercancel",cancelPointerDown,n);return}if(!this.#ze){this.#ze=new AbortController;const t=AbortSignal.any([this.#Ne,this.#ze.signal]),e=this.#Ot,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#We.bind(this),i);const n=this.#Ve.bind(this);e.addEventListener("touchend",n,i);e.addEventListener("touchcancel",n,i);i.capture=!0;e.addEventListener("pointerdown",stopEvent,i);e.addEventListener("pointermove",stopEvent,i);e.addEventListener("pointercancel",stopEvent,i);e.addEventListener("pointerup",stopEvent,i);this.#Re?.()}stopEvent(t);if(2!==t.touches.length||this.#Ie?.()){this.#Ue=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#Ue={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#We(t){if(!this.#Ue||2!==t.touches.length)return;stopEvent(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:n,screenY:s}=e,{screenX:r,screenY:a}=i,o=this.#Ue,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=r-n,m=a-s,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#ke&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=n;o.touch0Y=s;o.touch1X=r;o.touch1Y=a;if(!this.#ke){this.#ke=!0;return}const w=[(n+r)/2,(s+a)/2];this.#Be?.(w,b,f)}#Ve(t){if(!(t.touches.length>=2)){if(this.#ze){this.#ze.abort();this.#ze=null;this.#Le?.()}if(this.#Ue){stopEvent(t);this.#Ue=null;this.#ke=!1}}}destroy(){this.#He?.abort();this.#He=null;this.#Oe?.abort();this.#Oe=null}}class AnnotationEditor{#je=null;#$e=null;#y=null;#A=null;#xe=null;#Xe=!1;#qe=null;#Ke="";#Ye=null;#Qe=null;#Je=null;#Ze=null;#ti=null;#ei="";#ii=!1;#ni=null;#si=!1;#ri=!1;#ai=!1;#oi=null;#li=0;#hi=0;#di=null;#ci=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#ui=!1;#pi=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;this.annotationElementId=t.annotationElementId||null;this.creationDate=t.creationDate||new Date;this.modificationDate=t.modificationDate||null;this.canAddComment=!0;const{rotation:e,rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:r}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,n];this.pageTranslation=[s,r];const[a,o]=this.parentDimensions;this.x=t.x/a;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}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 shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ui}set _isDraggable(t){this.#ui=t;this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#pi}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else{this.#gi();this.#Ze?.remove();this.#Ze=null}this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ii?this.#ii=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,n){const[s,r]=this.parentDimensions;[i,n]=this.screenToPageTranslation(i,n);this.x=(t+i)/s;this.y=(e+n)/r;this.fixAndSetPosition()}_moveAfterPaste(t,e){const[i,n]=this.parentDimensions;this.setAt(t*i,e*n,this.width*i,this.height*n);this._onTranslated()}#mi([t,e],i,n){[i,n]=this.screenToPageTranslation(i,n);this.x+=i/t;this.y+=n/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#mi(this.parentDimensions,t,e)}translateInPage(t,e){this.#ni||=[this.x,this.y,this.width,this.height];this.#mi(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#ni||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[n,s]}=this;this.x+=t/n;this.y+=e/s;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:r,y:a}=this;const[o,l]=this.getBaseTranslation();r+=o;a+=l;const{style:h}=i;h.left=`${(100*r).toFixed(2)}%`;h.top=`${(100*a).toFixed(2)}%`;this._onTranslating(r,a);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#ni&&(this.#ni[0]!==this.x||this.#ni[1]!==this.y)}get _hasBeenResized(){return!!this.#ni&&(this.#ni[2]!==this.width||this.#ni[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,n=i/t,s=i/e;switch(this.rotation){case 90:return[-n,s];case 180:return[n,s];case 270:return[n,-s];default:return[-n,-s]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,n]}=this;let{x:s,y:r,width:a,height:o}=this;a*=i;o*=n;s*=i;r*=n;if(this._mustFixPosition)switch(t){case 0:s=MathClamp(s,0,i-a);r=MathClamp(r,0,n-o);break;case 90:s=MathClamp(s,0,i-o);r=MathClamp(r,a,n);break;case 180:s=MathClamp(s,a,i);r=MathClamp(r,o,n);break;case 270:s=MathClamp(s,o,i);r=MathClamp(r,0,n-a)}this.x=s/=i;this.y=r/=n;const[l,h]=this.getBaseTranslation();s+=l;r+=h;e.left=`${(100*s).toFixed(2)}%`;e.top=`${(100*r).toFixed(2)}%`;this.moveInDOM()}static#fi(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#fi(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#fi(t,e,360-this.parentRotation)}#bi(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(){const{div:{style:t},width:e,height:i}=this;t.width=`${(100*e).toFixed(2)}%`;t.height=`${(100*i).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#wi(){if(this.#Ye)return;this.#Ye=document.createElement("div");this.#Ye.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#Ye.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#yi.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#Ye)}#yi(t,e){e.preventDefault();const{isMac:i}=FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#y?.toggle(!1);const n=this._isDraggable;this._isDraggable=!1;this.#Qe=[e.screenX,e.screenY];const s=new AbortController,r=this._uiManager.combinedSignal(s);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#Ai.bind(this,t),{passive:!0,capture:!0,signal:r});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:r});window.addEventListener("contextmenu",noContextMenu,{signal:r});this.#Je={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{s.abort();this.parent.togglePointerEvents(!0);this.#y?.toggle(!0);this._isDraggable=n;this.parent.div.style.cursor=a;this.div.style.cursor=o;this.#vi()};window.addEventListener("pointerup",pointerUpCallback,{signal:r});window.addEventListener("blur",pointerUpCallback,{signal:r})}#xi(t,e,i,n){this.width=i;this.height=n;this.x=t;this.y=e;this.setDims();this.fixAndSetPosition();this._onResized()}_onResized(){}#vi(){if(!this.#Je)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:n}=this.#Je;this.#Je=null;const s=this.x,r=this.y,a=this.width,o=this.height;s===t&&r===e&&a===i&&o===n||this.addCommands({cmd:this.#xi.bind(this,s,r,a,o),undo:this.#xi.bind(this,t,e,i,n),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Ai(t,e){const[i,n]=this.parentDimensions,s=this.x,r=this.y,a=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/n,d=this.#bi(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#bi(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(a,o),b=p(a,o);let w=transf(...b);const y=AnnotationEditor._round(s+w[0]),A=AnnotationEditor._round(r+w[1]);let v,x,E=1,C=1;if(e.fromKeyboard)({deltaX:v,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[n,s]=this.#Qe;[v,x]=this.screenToPageTranslation(t-n,i-s);this.#Qe[0]=t;this.#Qe[1]=i}[v,x]=(S=v/i,T=x/n,[c[0]*S+c[2]*T,c[1]*S+c[3]*T]);var S,T;if(g){const t=Math.hypot(a,o);E=C=Math.max(Math.min(Math.hypot(b[0]-f[0]-v,b[1]-f[1]-x)/t,1/a,1/o),l/a,h/o)}else m?E=MathClamp(Math.abs(b[0]-f[0]-v),l,1)/a:C=MathClamp(Math.abs(b[1]-f[1]-x),h,1)/o;const _=AnnotationEditor._round(a*E),D=AnnotationEditor._round(o*C);w=transf(...p(_,D));const P=y-w[0],M=A-w[1];this.#ni||=[this.x,this.y,this.width,this.height];this.width=_;this.height=D;this.x=P;this.y=M;this.setDims();this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#y?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#ri)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,i]of t)await this._editToolbar.addButton(e,i);this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton());this._editToolbar.addButton("delete");return this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove();this._editToolbar=null;this.#y?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){if(!this.#y){AltText.initialize(AnnotationEditor._l10n);this.#y=new AltText(this);if(this.#je){this.#y.data=this.#je;this.#je=null}}return this.#y}get altTextData(){return this.#y?.data}set altTextData(t){this.#y&&(this.#y.data=t)}get guessedAltText(){return this.#y?.guessedText}async setGuessedAltText(t){await(this.#y?.setGuessedText(t))}serializeAltText(t){return this.#y?.serialize(t)}hasAltText(){return!!this.#y&&!this.#y.isEmpty()}hasAltTextData(){return this.#y?.hasData()??!1}focusCommentButton(){this.#A?.focusButton()}addCommentButton(){return this.canAddComment?this.#A||=new Comment(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager())if(this.#xe)this._uiManager.isEditingMode()&&this.#xe.classList.remove("hidden");else if(this.hasComment){this.#xe=this.#A.renderForStandalone();this.div.append(this.#xe)}}removeStandaloneCommentButton(){this.#A.removeStandaloneCommentButton();this.#xe=null}hideStandaloneCommentButton(){this.#xe?.classList.add("hidden")}get comment(){if(!this.#A)return null;const{data:{richText:t,text:e,date:i,deleted:n}}=this.#A;return{text:e,richText:t,date:i,deleted:n,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#A||=new Comment(this);"object"==typeof t&&null!==t?this.#A.restoreData(t):this.#A.data=t;if(this.hasComment){this.removeCommentButtonFromToolbar();this.addStandaloneCommentButton();this._uiManager.updateComment(this)}else{this.addCommentButtonInToolbar();this.removeStandaloneCommentButton();this._uiManager.removeComment(this)}}setCommentData({comment:t,popupRef:e,richText:i}){if(!e)return;this.#A||=new Comment(this);this.#A.setInitialText(t,i);if(!this.annotationElementId)return;const n=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);n&&this.updateFromAnnotationLayer(n)}get hasEditedComment(){return this.#A?.hasBeenEdited()}get hasDeletedComment(){return this.#A?.isDeleted()}get hasComment(){return!!this.#A&&!this.#A.isEmpty()&&!this.#A.isDeleted()}async editComment(t){this.#A||=new Comment(this);this.#A.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#A.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,i=100,[,,,n]=t.rect,[s]=this.pageDimensions,[r]=this.pageTranslation,a=r+s+1,o=n-i,l=a+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,o,l,n]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#A.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360);t.className=this.name;t.setAttribute("id",this.id);t.tabIndex=this.#Xe?-1:0;t.setAttribute("role","application");this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId);this._isVisible||t.classList.add("hidden");this.setInForeground();this.#Ei();const[e,i]=this.parentDimensions;if(this.parentRotation%180!=0){t.style.maxWidth=`${(100*i/e).toFixed(2)}%`;t.style.maxHeight=`${(100*e/i).toFixed(2)}%`}const[n,s]=this.getInitialTranslation();this.translate(n,s);bindEvents(this,t,["keydown","pointerdown","dblclick"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#ci||=new TouchManager({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ci.bind(this),onPinching:this.#Si.bind(this),onPinchEnd:this.#Ti.bind(this),signal:this._uiManager._signal}));this.addStandaloneCommentButton();this._uiManager._editorUndoBar?.hide();return t}#Ci(){this.#Je={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#y?.toggle(!1);this.parent.togglePointerEvents(!1)}#Si(t,e,i){let n=i/e*.7+1-.7;if(1===n)return;const s=this.#bi(this.rotation),transf=(t,e)=>[s[0]*t+s[2]*e,s[1]*t+s[3]*e],[r,a]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/r,u=AnnotationEditor.MIN_SIZE/a;n=Math.max(Math.min(n,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*n),g=AnnotationEditor._round(d*n);if(p===h&&g===d)return;this.#ni||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),w=transf(p/2,g/2);this.x=f-w[0];this.y=b-w[1];this.width=p;this.height=g;this.setDims();this.fixAndSetPosition();this._onResizing()}#Ti(){this.#y?.toggle(!0);this.parent.togglePointerEvents(!0);this.#vi()}pointerdown(t){const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#ii=!0;this._isDraggable?this.#_i(t):this.#Di(t)}}#Di(t){const{isMac:e}=FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#_i(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const n=new AbortController,s=this._uiManager.combinedSignal(n),r={capture:!0,passive:!1,signal:s},cancelDrag=t=>{n.abort();this.#qe=null;this.#ii=!1;this._uiManager.endDragSession()||this.#Di(t);i&&this._onStopDragging()};if(e){this.#li=t.clientX;this.#hi=t.clientY;this.#qe=t.pointerId;this.#Ke=t.pointerType;window.addEventListener("pointermove",t=>{if(!i){i=!0;this._uiManager.toggleComment(this,!0,!1);this._onStartDragging()}const{clientX:e,clientY:n,pointerId:s}=t;if(s!==this.#qe){stopEvent(t);return}const[r,a]=this.screenToPageTranslation(e-this.#li,n-this.#hi);this.#li=e;this.#hi=n;this._uiManager.dragSelectedEditors(r,a)},r);window.addEventListener("touchmove",stopEvent,r);window.addEventListener("pointerdown",t=>{t.pointerType===this.#Ke&&(this.#ci||t.isPrimary)&&cancelDrag(t);stopEvent(t)},r)}const pointerUpCallback=t=>{this.#qe&&this.#qe!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:s});window.addEventListener("blur",pointerUpCallback,{signal:s})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#oi&&clearTimeout(this.#oi);this.#oi=setTimeout(()=>{this.#oi=null;this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const n=this.parentScale,[s,r]=this.pageDimensions,[a,o]=this.pageTranslation,l=t/n,h=e/n,d=this.x*s,c=this.y*r,u=this.width*s,p=this.height*r;switch(i){case 0:return[d+l+a,r-c-h-p+o,d+l+u+a,r-c-h+o];case 90:return[d+h+a,r-c+l+o,d+h+p+a,r-c+l+u+o];case 180:return[d-l-u+a,r-c+h+o,d-l+a,r-c+h+p+o];case 270:return[d-h-p+a,r-c-l-u+o,d-h+a,r-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,n,s,r]=t,a=s-i,o=r-n;switch(this.rotation){case 0:return[i,e-r,a,o];case 90:return[i,e-n,o,a];case 180:return[s,e-n,a,o];case 270:return[s,e-r,o,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#A?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:i,opacity:n,deleted:s,richText:r},uid:a,pageIndex:o,creationDate:l,modificationDate:h}=this;return{id:a,pageIndex:o,rect:this.getPDFRect(),richText:r,contentsObj:{str:t},creationDate:l,modificationDate:i||h,popupRef:!s,color:e,opacity:n}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){if(this.isInEditMode())return!1;this.parent.setEditingState(!1);this.#ri=!0;return!0}disableEditMode(){if(!this.isInEditMode())return!1;this.parent.setEditingState(!0);this.#ri=!1;return!0}isInEditMode(){return this.#ri}shouldGetKeyboardEvents(){return this.#ai}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:n}=this.getClientDimensions(),{innerHeight:s,innerWidth:r}=window;return e0&&t0}#Ei(){if(this.#ti||!this.div)return;this.#ti=new AbortController;const t=this._uiManager.combinedSignal(this.#ti);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#Ei()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,i){const n=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});n.rotation=t.rotation;n.#je=t.accessibilityData;n._isCopy=t.isCopy||!1;const[s,r]=n.pageDimensions,[a,o,l,h]=n.getRectInCurrentCoords(t.rect,r);n.x=a/s;n.y=o/r;n.width=l/s;n.height=h/r;return n}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#ti?.abort();this.#ti=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);this.hideCommentPopup();if(this.#oi){clearTimeout(this.#oi);this.#oi=null}this.#gi();this.removeEditToolbar();if(this.#di){for(const t of this.#di.values())clearTimeout(t);this.#di=null}this.parent=null;this.#ci?.destroy();this.#ci=null;this.#Ze?.remove();this.#Ze=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#wi();this.#Ye.classList.remove("hidden")}}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[i,n,s,r]=this.getPDFRect();return[AnnotationEditor._round(i+(s-i)*t),AnnotationEditor._round(n+(r-n)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#A.commentPopupPositionInLayer}set commentPopupPosition(t){this.#A.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#A.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#A.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#A?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#Je={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Ye.children;if(!this.#$e){this.#$e=Array.from(e);const t=this.#Pi.bind(this),i=this.#Mi.bind(this),n=this._uiManager._signal;for(const e of this.#$e){const s=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:n});e.addEventListener("blur",i,{signal:n});e.addEventListener("focus",this.#ki.bind(this,s),{signal:n});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[s])}}const i=this.#$e[0];let n=0;for(const t of e){if(t===i)break;n++}const s=(360-this.rotation+this.parentRotation)%360/90*(this.#$e.length/4);if(s!==n){if(sn)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()})}}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){if(this.isSelected){this.isSelected=!1;this.#Ye?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#y?.toggleAltTextBadge(!0);this.hideCommentPopup()}}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){if(this.canChangeContent){this.enableEditMode();this.div.focus()}}dblclick(t){if("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.#si}set isEditing(t){this.#si=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#di||=new Map;const{action:e}=t;let i=this.#di.get(e);i&&clearTimeout(i);i=setTimeout(()=>{this._reportTelemetry(t);this.#di.delete(e);0===this.#di.size&&(this.#di=null)},AnnotationEditor._telemetryTimeout);this.#di.set(e,i);return}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.#Xe=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#Xe=!0}updateFakeAnnotationElement(t){if(this.#Ze||this.deleted)if(this.deleted){this.#Ze.remove();this.#Ze=null}else(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#Ze.updateEdited({rect:this.getPDFRect(),popup:this.comment});else this.#Ze=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted){t.hide();return null}let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstElementChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const q=3285377520,K=4294901760,Y=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:q;this.h2=t?4294967295&t:q}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let n=0,s=t.length;n>>8;e[i++]=255&s}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const n=i>>2,s=i-4*n,r=new Uint32Array(e.buffer,0,n);let a=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17;a=a*c&K|a*p&Y;l^=a;l=l<<13|l>>>19;l=5*l+3864292196}else{o=r[t];o=o*d&K|o*u&Y;o=o<<15|o>>>17;o=o*c&K|o*p&Y;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}a=0;switch(s){case 3:a^=e[4*n+2]<<16;case 2:a^=e[4*n+1]<<8;case 1:a^=e[4*n];a=a*d&K|a*u&Y;a=a<<15|a>>>17;a=a*c&K|a*p&Y;1&n?l^=a:h^=a}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&K|36045*t&Y;e=4283543511*e&K|(2950163797*(e<<16|t>>>16)&K)>>>16;t^=e>>>1;t=444984403*t&K|60499*t&Y;e=3301882366*e&K|(3120437893*(e<<16|t>>>16)&K)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Q=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Fi=!1;#Ri=null;#Bi=null;#Li=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(t,e){const i=this.#Li.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Li.get(t)}remove(t){const e=this.#Li.get(t);if(void 0!==e){e instanceof AnnotationEditor&&this.#Bi.delete(e.annotationElementId);this.#Li.delete(t);0===this.#Li.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#Li.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}}setValue(t,e){const i=this.#Li.get(t);let n=!1;if(void 0!==i){for(const[t,s]of Object.entries(e))if(i[t]!==s){n=!0;i[t]=s}}else{n=!0;this.#Li.set(t,e)}n&&this.#Oi();if(e instanceof AnnotationEditor){(this.#Bi||=new Map).set(e.annotationElementId,e);"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}}has(t){return this.#Li.has(t)}get size(){return this.#Li.size}#Oi(){if(!this.#Fi){this.#Fi=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#Fi){this.#Fi=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Li.size)return Q;const t=new Map,e=new MurmurHash3_64,i=[],n=Object.create(null);let s=!1;for(const[i,r]of this.#Li){const a=r instanceof AnnotationEditor?r.serialize(!1,n):r;if(r.page){r.pageIndex=r.page._pageIndex;delete r.page}if(a){t.set(i,a);e.update(`${i}:${JSON.stringify(a)}`);s||=!!a.bitmap}}if(s)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:Q}get editorStats(){let t=null;const e=new Map;let i=0,n=0;for(const s of this.#Li.values()){if(!(s instanceof AnnotationEditor)){s.popup&&(s.popup.deleted?n+=1:i+=1);continue}s.isCommentDeleted?n+=1:s.hasEditedComment&&(i+=1);const r=s.telemetryFinalData;if(!r)continue;const{type:a}=r;e.has(a)||e.set(a,Object.getPrototypeOf(s).constructor);t||=Object.create(null);const o=t[a]||=new Map;for(const[t,e]of Object.entries(r)){if("type"===t)continue;const i=o.getOrInsertComputed(t,makeMap);i.set(e,(i.get(e)??0)+1)}}if(n>0||i>0){t||=Object.create(null);t.comments={deleted:n,edited:i}}if(!t)return null;for(const[i,n]of e)t[i]=n.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Ri=null}updateEditor(t,e){const i=this.#Bi?.get(t);if(i){i.updateFromAnnotationLayer(e);return!0}return!1}getEditor(t){return this.#Bi?.get(t)||null}get modifiedIds(){if(this.#Ri)return this.#Ri;const t=[];if(this.#Bi)for(const e of this.#Bi.values())e.serialize()&&t.push(e.annotationElementId);return this.#Ri={ids:new Set(t),hash:t.join(",")}}[Symbol.iterator](){return this.#Li.entries()}}class PrintAnnotationStorage extends AnnotationStorage{#Ni=Q;constructor(t){super();const{serializable:e}=t;if(e===Q)return;const{map:i,hash:n,transfer:s}=e,r=structuredClone(i,s?{transfer:s}:null);this.#Ni={map:r,hash:n,transfer:[]}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Ni}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#Ui=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#Ui.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#Ui.has(t.loadedName)){assert(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:e,src:n,style:s}=t,r=new FontFace(e,n,s);this.addNativeFontFace(r);try{await r.load();this.#Ui.add(e);i?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(r)}return}unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise(e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return shadow(this,"isSyncFontLoadingSupported",t||FeatureTest.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,n){return t.substring(0,e)+n+t.substring(e+i)}let i,n;const s=this._document.createElement("canvas");s.width=1;s.height=1;const r=s.getContext("2d");let a=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let d=int32(l,16);for(i=0,n=o.length-3;i>24&255,t>>16&255,t>>8&255,255&t)}(d));const c=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(c);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++a>30){warn("Load test font never loaded.");e();return}r.font="30px "+t;r.fillText(".",0,20);r.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,()=>{u.remove();e.complete()})}}class FontFaceObject{#Hi;constructor(t,e=null,i,n){this.compiledGlyphs=Object.create(null);this.#Hi=t;this._inspectFont=e;i&&Object.assign(this,i);n&&(this.charProcOperatorList=n)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let n;try{n=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const s=makePathFromDrawOPS(n?.path);this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=s}get black(){return this.#Hi.black}get bold(){return this.#Hi.bold}get disableFontFace(){return this.#Hi.disableFontFace??!1}set disableFontFace(t){shadow(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#Hi.fontExtraProperties??!1}get isInvalidPDFjsFont(){return this.#Hi.isInvalidPDFjsFont}get isType3Font(){return this.#Hi.isType3Font}get italic(){return this.#Hi.italic}get missingFile(){return this.#Hi.missingFile}get remeasure(){return this.#Hi.remeasure}get vertical(){return this.#Hi.vertical}get ascent(){return this.#Hi.ascent}get defaultWidth(){return this.#Hi.defaultWidth}get descent(){return this.#Hi.descent}get bbox(){return this.#Hi.bbox}set bbox(t){shadow(this,"bbox",t)}get fontMatrix(){return this.#Hi.fontMatrix}get fallbackName(){return this.#Hi.fallbackName}get loadedName(){return this.#Hi.loadedName}get mimetype(){return this.#Hi.mimetype}get name(){return this.#Hi.name}get data(){return this.#Hi.data}clearData(){this.#Hi.clearData()}get cssFontInfo(){return this.#Hi.cssFontInfo}get systemFontInfo(){return this.#Hi.systemFontInfo}get defaultVMetrics(){return this.#Hi.defaultVMetrics}}class CssFontInfo{#zi;#Gi;#Wi;static strings=["fontFamily","fontWeight","italicAngle"];static write(t){const e=new TextEncoder,i={};let n=0;for(const s of CssFontInfo.strings){const r=e.encode(t[s]);i[s]=r;n+=4+r.length}const s=new ArrayBuffer(n),r=new Uint8Array(s),a=new DataView(s);let o=0;for(const t of CssFontInfo.strings){const e=i[t],n=e.length;a.setUint32(o,n);r.set(e,o+4);o+=4+n}assert(o===s.byteLength,"CssFontInfo.write: Buffer overflow");return s}constructor(t){this.#zi=t;this.#Gi=new DataView(this.#zi);this.#Wi=new TextDecoder}#Vi(t){assert(t>i&3;return 0===n?void 0:2===n}get black(){return this.#Yi(0)}get bold(){return this.#Yi(1)}get disableFontFace(){return this.#Yi(2)}get fontExtraProperties(){return this.#Yi(3)}get isInvalidPDFjsFont(){return this.#Yi(4)}get isType3Font(){return this.#Yi(5)}get italic(){return this.#Yi(6)}get missingFile(){return this.#Yi(7)}get remeasure(){return this.#Yi(8)}get vertical(){return this.#Yi(9)}#Qi(t){assert(t0){let t=h[0],i=h[0],n=h[1],s=h[1];for(let e=0;er?r:t;n=n>a?a:n;i=i"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,J=function _isValidExplicitDest(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[n,s,...r]=i;if(!t(n)&&!Number.isInteger(n))return!1;if(!e(s))return!1;const a=r.length;let o=!0;switch(s.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return 0===a;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(4!==a)return!1;o=!1;break;default:return!1}for(const t of r)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,isRefProxy,t=>"object"==typeof t&&"string"==typeof t?.name);class LoopbackPort{#o=new Map;#an=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#an.then(()=>{for(const[t]of this.#o)t.call(this,i)})}addEventListener(t,e,i=null){let n=null;if(i?.signal instanceof AbortSignal){const{signal:s}=i;if(s.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);n=()=>s.removeEventListener("abort",onAbort);s.addEventListener("abort",onAbort)}this.#o.set(e,n)}removeEventListener(t,e){const i=this.#o.get(e);i?.();this.#o.delete(e)}terminate(){for(const[,t]of this.#o)t?.();this.#o.clear()}}const Z=1,tt=2,et=1,it=2,nt=3,st=4,rt=5,at=6,ot=7,lt=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof PasswordException||t instanceof ResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"ResponseException":return new ResponseException(t.message,t.status,t.missing);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#on=new AbortController;constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#ln.bind(this),{signal:this.#on.signal})}#ln({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#hn(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===Z)i.resolve(t.data);else{if(t.callback!==tt)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,n=t.sourceName,s=this.comObj;Promise.try(e,t.data).then(function(e){s.postMessage({sourceName:i,targetName:n,callback:Z,callbackId:t.callbackId,data:e})},function(e){s.postMessage({sourceName:i,targetName:n,callback:tt,callbackId:t.callbackId,reason:wrapReason(e)})});return}t.streamId?this.#dn(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const n=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[n]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:n,data:e},i)}catch(t){s.reject(t)}return s.promise}sendWithStream(t,e,i,n){const s=this.streamId++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[s]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:r,targetName:a,action:t,streamId:s,data:e,desiredSize:i.desiredSize},n);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[s].pullCall=e;o.postMessage({sourceName:r,targetName:a,stream:at,streamId:s,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[s].cancelCall=e;this.streamControllers[s].isClosed=!0;o.postMessage({sourceName:r,targetName:a,stream:et,streamId:s,reason:wrapReason(t)});return e.promise}},i)}#dn(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,r=this,a=this.actionHandler[t.action],o={enqueue(t,r=1,a){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=r;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:i,targetName:n,stream:st,streamId:e,chunk:t},a)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:n,stream:nt,streamId:e});delete r.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:n,stream:rt,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(a,t.data,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:lt,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:lt,streamId:e,reason:wrapReason(t)})})}#hn(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case lt:t.success?r.startCall.resolve():r.startCall.reject(wrapReason(t.reason));break;case ot:t.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(t.reason));break;case at:if(!a){s.postMessage({sourceName:i,targetName:n,stream:ot,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve();a.desiredSize=t.desiredSize;Promise.try(a.onPull||onFn).then(function(){s.postMessage({sourceName:i,targetName:n,stream:ot,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:ot,streamId:e,reason:wrapReason(t)})});break;case st:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(t.chunk);break;case nt:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#cn(r,e);break;case rt:assert(r,"error should have stream controller");r.controller.error(wrapReason(t.reason));this.#cn(r,e);break;case it:t.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(t.reason));this.#cn(r,e);break;case et:if(!a)break;const o=wrapReason(t.reason);Promise.try(a.onCancel||onFn,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:it,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:it,streamId:e,reason:wrapReason(t)})});a.sinkCapability.reject(o);a.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#cn(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#on?.abort();this.#on=null}}class BaseCanvasFactory{#un=!1;constructor({enableHWA:t=!1}){this.#un=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#un})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(t=>({cMapData:t,isCompressed:this.isCompressed})).catch(t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"bytes":"text");return e instanceof Uint8Array?e:stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,n,s){return"none"}destroy(t=!1){}}class DOMFilterFactory extends BaseFilterFactory{#pn;#gn;#mn;#fn;#bn;#wn;#O=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#fn=t;this.#bn=e}get#U(){return this.#gn||=new Map}get#yn(){return this.#wn||=new Map}get#An(){if(!this.#mn){const t=this.#bn.createElement("div"),{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#bn.createElementNS(j,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#mn=this.#bn.createElementNS(j,"defs");t.append(i);i.append(this.#mn);this.#bn.body.append(t)}return this.#mn}#vn(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const n=i.join(",");return[n,n,n]}const[e,i,n]=t,s=new Array(256),r=new Array(256),a=new Array(256);for(let t=0;t<256;t++){s[t]=e[t]/255;r[t]=i[t]/255;a[t]=n[t]/255}return[s.join(","),r.join(","),a.join(",")]}#xn(t){if(void 0===this.#pn){this.#pn="";const t=this.#bn.URL;t!==this.#bn.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#pn=updateUrlHash(t,""))}return`url(${this.#pn}#${t})`}addFilter(t){if(!t)return"none";let e=this.#U.get(t);if(e)return e;const[i,n,s]=this.#vn(t),r=1===t.length?i:`${i}${n}${s}`;e=this.#U.get(r);if(e){this.#U.set(t,e);return e}const a=`g_${this.#fn}_transfer_map_${this.#O++}`,o=this.#xn(a);this.#U.set(t,o);this.#U.set(r,o);const l=this.#En(a);this.#Cn(i,n,s,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,n="base";let s=this.#yn.get(n);if(s?.key===i)return s.url;if(s){s.filter?.remove();s.key=i;s.url="none";s.filter=null}else{s={key:i,url:"none",filter:null};this.#yn.set(n,s)}if(!t||!e)return s.url;const r=this.#Sn(t);t=Util.makeHexColor(...r);const a=this.#Sn(e);e=Util.makeHexColor(...a);this.#An.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return s.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#fn}_hcm_filter`,d=s.filter=this.#En(h);this.#Cn(l,l,l,d);this.#Tn(d);const getSteps=(t,e)=>{const i=r[t]/255,n=a[t]/255,s=new Array(e+1);for(let t=0;t<=e;t++)s[t]=i+t/e*(n-i);return s.join(",")};this.#Cn(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);s.url=this.#xn(h);return s.url}addAlphaFilter(t){let e=this.#U.get(t);if(e)return e;const[i]=this.#vn([t]),n=`alpha_${i}`;e=this.#U.get(n);if(e){this.#U.set(t,e);return e}const s=`g_${this.#fn}_alpha_map_${this.#O++}`,r=this.#xn(s);this.#U.set(t,r);this.#U.set(n,r);const a=this.#En(s);this.#_n(i,a);return r}addLuminosityFilter(t){let e,i,n=this.#U.get(t||"luminosity");if(n)return n;if(t){[e]=this.#vn([t]);i=`luminosity_${e}`}else i="luminosity";n=this.#U.get(i);if(n){this.#U.set(t,n);return n}const s=`g_${this.#fn}_luminosity_map_${this.#O++}`,r=this.#xn(s);this.#U.set(t,r);this.#U.set(i,r);const a=this.#En(s);this.#Dn(a);t&&this.#_n(e,a);return r}addHighlightHCMFilter(t,e,i,n,s){const r=`${e}-${i}-${n}-${s}`;let a=this.#yn.get(t);if(a?.key===r)return a.url;if(a){a.filter?.remove();a.key=r;a.url="none";a.filter=null}else{a={key:r,url:"none",filter:null};this.#yn.set(t,a)}if(!e||!i)return a.url;const[o,l]=[e,i].map(this.#Sn.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[n,s].map(this.#Sn.bind(this));d{const n=new Array(256),s=(d-h)/i,r=t/255,a=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*s),i=r+t*a;for(let t=o;t<=e;t++)n[t]=i;o=e+1}for(let t=o;t<256;t++)n[t]=n[o-1];return n.join(",")},p=`g_${this.#fn}_hcm_${t}_filter`,g=a.filter=this.#En(p);this.#Tn(g);this.#Cn(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);a.url=this.#xn(p);return a.url}destroy(t=!1){if(!t||!this.#wn?.size){this.#mn?.parentNode.parentNode.remove();this.#mn=null;this.#gn?.clear();this.#gn=null;this.#wn?.clear();this.#wn=null;this.#O=0}}#Dn(t){const e=this.#bn.createElementNS(j,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");t.append(e)}#Tn(t){const e=this.#bn.createElementNS(j,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#En(t){const e=this.#bn.createElementNS(j,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#An.append(e);return e}#Pn(t,e,i){const n=this.#bn.createElementNS(j,e);n.setAttribute("type","discrete");n.setAttribute("tableValues",i);t.append(n)}#Cn(t,e,i,n){const s=this.#bn.createElementNS(j,"feComponentTransfer");n.append(s);this.#Pn(s,"feFuncR",t);this.#Pn(s,"feFuncG",e);this.#Pn(s,"feFuncB",i)}#_n(t,e){const i=this.#bn.createElementNS(j,"feComponentTransfer");e.append(i);this.#Pn(i,"feFuncA",t)}#Sn(t){this.#An.style.color=t;return getRGB(getComputedStyle(this.#An).getPropertyValue("color"))}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return fetchData(t,"bytes")}}class BaseWasmFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!t)throw new Error("Wasm filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load wasm data at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMWasmFactory extends BaseWasmFactory{async _fetch(t){return fetchData(t,"bytes")}}t&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}class NodeFilterFactory extends BaseFilterFactory{}class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeWasmFactory extends BaseWasmFactory{async _fetch(t){return node_utils_fetchData(t)}}const ht="__forcedDependency",{floor:dt,ceil:ct}=Math;function expandBBox(t,e,i,n,s,r){t[4*e+0]=Math.min(t[4*e+0],i);t[4*e+1]=Math.min(t[4*e+1],n);t[4*e+2]=Math.max(t[4*e+2],s);t[4*e+3]=Math.max(t[4*e+3],r)}const ut=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class BBoxReader{#Mn;#kn;constructor(t,e){this.#Mn=t;this.#kn=e}get length(){return this.#Mn.length}isEmpty(t){return this.#Mn[t]===ut}minX(t){return this.#kn[4*t+0]/256}minY(t){return this.#kn[4*t+1]/256}maxX(t){return(this.#kn[4*t+2]+1)/256}maxY(t){return(this.#kn[4*t+3]+1)/256}}const ensureDebugMetadata=(t,e)=>t?.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));class CanvasDependencyTracker{#In={__proto__:null};#Fn={__proto__:null,transform:[],moveText:[],sameLineText:[],[ht]:[]};#Rn=new Map;#Bn=[];#Ln=[];#On=[[1,0,0,1,0,0]];#Nn=[-1/0,-1/0,1/0,1/0];#Un=new Float64Array([1/0,1/0,-1/0,-1/0]);#Hn=-1;#zn=new Set;#Gn=new Map;#Wn=new Map;#Vn;#jn;#$n;#Mn;#Xn;constructor(t,e,i=!1){this.#Vn=t.width;this.#jn=t.height;this.#qn(e);i&&(this.#Xn=new Map)}growOperationsCount(t){t>=this.#Mn.length&&this.#qn(t,this.#Mn)}#qn(t,e){const i=new ArrayBuffer(4*t);this.#$n=new Uint8ClampedArray(i);this.#Mn=new Uint32Array(i);if(e&&e.length>0){this.#Mn.set(e);this.#Mn.fill(ut,e.length)}else this.#Mn.fill(ut)}save(t){this.#In={__proto__:this.#In};this.#Fn={__proto__:this.#Fn,transform:{__proto__:this.#Fn.transform},moveText:{__proto__:this.#Fn.moveText},sameLineText:{__proto__:this.#Fn.sameLineText},[ht]:{__proto__:this.#Fn[ht]}};this.#Nn={__proto__:this.#Nn};this.#Bn.push(t);return this}restore(t){const e=Object.getPrototypeOf(this.#In);if(null===e)return this;this.#In=e;this.#Fn=Object.getPrototypeOf(this.#Fn);this.#Nn=Object.getPrototypeOf(this.#Nn);const i=this.#Bn.pop();if(void 0!==i){ensureDebugMetadata(this.#Xn,t)?.dependencies.add(i);this.#Mn[t]=this.#Mn[i]}return this}recordOpenMarker(t){this.#Bn.push(t);return this}getOpenMarker(){return 0===this.#Bn.length?null:this.#Bn.at(-1)}recordCloseMarker(t){const e=this.#Bn.pop();if(void 0!==e){ensureDebugMetadata(this.#Xn,t)?.dependencies.add(e);this.#Mn[t]=this.#Mn[e]}return this}beginMarkedContent(t){this.#Ln.push(t);return this}endMarkedContent(t){const e=this.#Ln.pop();if(void 0!==e){ensureDebugMetadata(this.#Xn,t)?.dependencies.add(e);this.#Mn[t]=this.#Mn[e]}return this}pushBaseTransform(t){this.#On.push(Util.multiplyByDOMMatrix(this.#On.at(-1),t.getTransform()));return this}popBaseTransform(){this.#On.length>1&&this.#On.pop();return this}recordSimpleData(t,e){this.#In[t]=e;return this}recordIncrementalData(t,e){this.#Fn[t].push(e);return this}resetIncrementalData(t,e){this.#Fn[t].length=0;return this}recordNamedData(t,e){this.#Rn.set(t,e);return this}recordSimpleDataFromNamed(t,e,i){this.#In[t]=this.#Rn.get(e)??i}recordFutureForcedDependency(t,e){this.recordIncrementalData(ht,e);return this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#In&&this.recordFutureForcedDependency(e,this.#In[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#zn)this.recordFutureForcedDependency(ht,t);return this}resetBBox(t){if(this.#Hn!==t){this.#Hn=t;this.#Un[0]=1/0;this.#Un[1]=1/0;this.#Un[2]=-1/0;this.#Un[3]=-1/0}return this}recordClipBox(t,e,i,n,s,r){const a=Util.multiplyByDOMMatrix(this.#On.at(-1),e.getTransform()),o=[1/0,1/0,-1/0,-1/0];Util.axialAlignedBoundingBox([i,s,n,r],a,o);const l=Util.intersect(this.#Nn,o);if(l){this.#Nn[0]=l[0];this.#Nn[1]=l[1];this.#Nn[2]=l[2];this.#Nn[3]=l[3]}else{this.#Nn[0]=this.#Nn[1]=1/0;this.#Nn[2]=this.#Nn[3]=-1/0}return this}recordBBox(t,e,i,n,s,r){const a=this.#Nn;if(a[0]===1/0)return this;const o=Util.multiplyByDOMMatrix(this.#On.at(-1),e.getTransform());if(a[0]===-1/0){Util.axialAlignedBoundingBox([i,s,n,r],o,this.#Un);return this}const l=[1/0,1/0,-1/0,-1/0];Util.axialAlignedBoundingBox([i,s,n,r],o,l);this.#Un[0]=Math.min(this.#Un[0],Math.max(l[0],a[0]));this.#Un[1]=Math.min(this.#Un[1],Math.max(l[1],a[1]));this.#Un[2]=Math.max(this.#Un[2],Math.min(l[2],a[2]));this.#Un[3]=Math.max(this.#Un[3],Math.min(l[3],a[3]));return this}recordCharacterBBox(t,e,i,n=1,s=0,r=0,a){const o=i.bbox;let l,h;if(o){l=o[2]!==o[0]&&o[3]!==o[1]&&this.#Wn.get(i);if(!1!==l){h=[0,0,0,0];Util.axialAlignedBoundingBox(o,i.fontMatrix,h);1===n&&0===s&&0===r||Util.scaleMinMax([n,0,0,-n,s,r],h);if(l)return this.recordBBox(t,e,h[0],h[2],h[1],h[3])}}if(!a)return this.recordFullPageBBox(t);const d=a();if(o&&h&&void 0===l){l=h[0]<=s-d.actualBoundingBoxLeft&&h[2]>=s+d.actualBoundingBoxRight&&h[1]<=r-d.actualBoundingBoxAscent&&h[3]>=r+d.actualBoundingBoxDescent;this.#Wn.set(i,l);if(l)return this.recordBBox(t,e,h[0],h[2],h[1],h[3])}return this.recordBBox(t,e,s-d.actualBoundingBoxLeft,s+d.actualBoundingBoxRight,r-d.actualBoundingBoxAscent,r+d.actualBoundingBoxDescent)}recordFullPageBBox(t){this.#Un[0]=Math.max(0,this.#Nn[0]);this.#Un[1]=Math.max(0,this.#Nn[1]);this.#Un[2]=Math.min(this.#Vn,this.#Nn[2]);this.#Un[3]=Math.min(this.#jn,this.#Nn[3]);return this}getSimpleIndex(t){return this.#In[t]}recordDependencies(t,e){const i=this.#zn,n=this.#In,s=this.#Fn;for(const t of e)t in this.#In?i.add(n[t]):t in s&&s[t].forEach(i.add,i);return this}recordNamedDependency(t,e){this.#Rn.has(e)&&this.#zn.add(this.#Rn.get(e));return this}recordOperation(t,e=!1){this.recordDependencies(t,[ht]);if(this.#Xn){const e=ensureDebugMetadata(this.#Xn,t),{dependencies:i}=e;this.#zn.forEach(i.add,i);this.#Bn.forEach(i.add,i);this.#Ln.forEach(i.add,i);i.delete(t);e.isRenderingOperation=!0}if(this.#Hn===t){const i=dt(256*this.#Un[0]/this.#Vn),n=dt(256*this.#Un[1]/this.#jn),s=ct(256*this.#Un[2]/this.#Vn),r=ct(256*this.#Un[3]/this.#jn);expandBBox(this.#$n,t,i,n,s,r);for(const e of this.#zn)e!==t&&expandBBox(this.#$n,e,i,n,s,r);for(const e of this.#Bn)e!==t&&expandBBox(this.#$n,e,i,n,s,r);for(const e of this.#Ln)e!==t&&expandBBox(this.#$n,e,i,n,s,r);if(!e){this.#zn.clear();this.#Hn=-1}}return this}recordShowTextOperation(t,e=!1){const i=Array.from(this.#zn);this.recordOperation(t,e);this.recordIncrementalData("sameLineText",t);for(const t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){if(this.#Hn===t){this.#Hn=-1;this.#Nn[0]=Math.max(this.#Nn[0],this.#Un[0]);this.#Nn[1]=Math.max(this.#Nn[1],this.#Un[1]);this.#Nn[2]=Math.min(this.#Nn[2],this.#Un[2]);this.#Nn[3]=Math.min(this.#Nn[3],this.#Un[3]);e||this.#zn.clear()}return this}_takePendingDependencies(){const t=this.#zn;this.#zn=new Set;return t}_extractOperation(t){const e=this.#Gn.get(t);this.#Gn.delete(t);return e}_pushPendingDependencies(t){for(const e of t)this.#zn.add(e)}take(){this.#Wn.clear();return new BBoxReader(this.#Mn,this.#$n)}takeDebugMetadata(){return this.#Xn}}class CanvasNestedDependencyTracker{#Kn;#Yn;#Qn;#Jn=0;#Zn=0;constructor(t,e,i){if(t instanceof CanvasNestedDependencyTracker&&t.#Qn===!!i)return t;this.#Kn=t;this.#Yn=e;this.#Qn=!!i}growOperationsCount(){throw new Error("Unreachable")}save(t){this.#Zn++;this.#Kn.save(this.#Yn);return this}restore(t){if(this.#Zn>0){this.#Kn.restore(this.#Yn);this.#Zn--}return this}recordOpenMarker(t){this.#Jn++;return this}getOpenMarker(){return this.#Jn>0?this.#Yn:this.#Kn.getOpenMarker()}recordCloseMarker(t){this.#Jn--;return this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){this.#Kn.pushBaseTransform(t);return this}popBaseTransform(){this.#Kn.popBaseTransform();return this}recordSimpleData(t,e){this.#Kn.recordSimpleData(t,this.#Yn);return this}recordIncrementalData(t,e){this.#Kn.recordIncrementalData(t,this.#Yn);return this}resetIncrementalData(t,e){this.#Kn.resetIncrementalData(t,this.#Yn);return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){this.#Kn.recordSimpleDataFromNamed(t,e,this.#Yn);return this}recordFutureForcedDependency(t,e){this.#Kn.recordFutureForcedDependency(t,this.#Yn);return this}inheritSimpleDataAsFutureForcedDependencies(t){this.#Kn.inheritSimpleDataAsFutureForcedDependencies(t);return this}inheritPendingDependenciesAsFutureForcedDependencies(){this.#Kn.inheritPendingDependenciesAsFutureForcedDependencies();return this}resetBBox(t){this.#Qn||this.#Kn.resetBBox(this.#Yn);return this}recordClipBox(t,e,i,n,s,r){this.#Qn||this.#Kn.recordClipBox(this.#Yn,e,i,n,s,r);return this}recordBBox(t,e,i,n,s,r){this.#Qn||this.#Kn.recordBBox(this.#Yn,e,i,n,s,r);return this}recordCharacterBBox(t,e,i,n,s,r,a){this.#Qn||this.#Kn.recordCharacterBBox(this.#Yn,e,i,n,s,r,a);return this}recordFullPageBBox(t){this.#Qn||this.#Kn.recordFullPageBBox(this.#Yn);return this}getSimpleIndex(t){return this.#Kn.getSimpleIndex(t)}recordDependencies(t,e){this.#Kn.recordDependencies(this.#Yn,e);return this}recordNamedDependency(t,e){this.#Kn.recordNamedDependency(this.#Yn,e);return this}recordOperation(t){this.#Kn.recordOperation(this.#Yn,!0);return this}recordShowTextOperation(t){this.#Kn.recordShowTextOperation(this.#Yn,!0);return this}bboxToClipBoxDropOperation(t){this.#Qn||this.#Kn.bboxToClipBoxDropOperation(this.#Yn,!0);return this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const pt=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],gt=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],mt=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],ft=["filter","fillColor","fillAlpha"],bt=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],wt=["transform"],yt=["transform","fillColor"],At="Fill",vt="Stroke",xt="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],n=e[3]-e[1],s=new Path2D;s.rect(e[0],e[1],i,n);t.clip(s)}class BaseShadingPattern{isModifyingCurrentTransform(){return!1}getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}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}_createGradient(t,e=null){let i,n=this._p0,s=this._p1;if(e){n=n.slice();s=s.slice();Util.applyTransform(n,e);Util.applyTransform(s,e)}if("axial"===this._type)i=t.createLinearGradient(n[0],n[1],s[0],s[1]);else if("radial"===this._type){let r=this._r0,a=this._r1;if(e){const t=new Float32Array(2);Util.singularValueDecompose2dScale(e,t);r*=t[0];a*=t[0]}i=t.createRadialGradient(n[0],n[1],r,s[0],s[1],a)}for(const t of this._colorStops)i.addColorStop(t[0],t[1]);return i}getPattern(t,e,i,n){let s;if(n===vt||n===At){if(this.isOriginBased()){let n=Util.transform(i,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix));const s=.001,r=Math.hypot(n[0],n[1]),a=Math.hypot(n[2],n[3]),o=(n[0]*n[2]+n[1]*n[3])/(r*a);if(Math.abs(o)l[n+1]){u=i;i=n;n=u;u=r;r=a;a=u}if(l[n+1]>l[s+1]){u=n;n=s;s=u;u=a;a=o;o=u}if(l[i+1]>l[n+1]){u=i;i=n;n=u;u=r;r=a;a=u}const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[n]+e.offsetX)*e.scaleX,f=(l[n+1]+e.offsetY)*e.scaleY,b=(l[s]+e.offsetX)*e.scaleX,w=(l[s+1]+e.offsetY)*e.scaleY;if(g>=w)return;const y=h[r],A=h[r+1],v=h[r+2],x=h[a],E=h[a+1],C=h[a+2],S=h[o],T=h[o+1],_=h[o+2],D=Math.round(g),P=Math.round(w);let M,k,I,F,R,B,L,O;for(let t=D;t<=P;t++){if(tw?1:f===w?0:(f-t)/(f-w);M=m-(m-b)*e;k=x-(x-S)*e;I=E-(E-T)*e;F=C-(C-_)*e}let e;e=tw?1:(g-t)/(g-w);R=p-(p-b)*e;B=y-(y-S)*e;L=A-(A-T)*e;O=v-(v-_)*e;const i=Math.round(Math.min(M,R)),n=Math.round(Math.max(M,R));let s=c*t+4*i;for(let t=i;t<=n;t++){e=(M-t)/(M-R);e<0?e=0:e>1&&(e=1);d[s++]=k-(k-B)*e|0;d[s++]=I-(I-L)*e|0;d[s++]=F-(F-O)*e|0;d[s++]=255}}}function drawFigure(t,e,i){const n=e.coords,s=e.colors;let r,a;switch(e.type){case b:const o=e.verticesPerRow,l=Math.floor(n.length/o)-1,h=o-1;for(r=0;r=Math.ceil(g*y)?v=l:E=!0;T>=Math.ceil(m*A)?x=h:C=!0;const _=this.getSizeAndScale(v,this.ctx.canvas.width,y),D=this.getSizeAndScale(x,this.ctx.canvas.height,A),P=t.cachedCanvases.getCanvas("pattern",_.size,D.size),M=P.context,k=o.createCanvasGraphics(M,e);k.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(k,s,a);M.translate(-_.scale*d,-D.scale*c);k.transform(0,_.scale,0,0,D.scale,0,0);M.save();k.dependencyTracker?.save();this.clipBbox(k,d,c,u,p);k.baseTransform=getCurrentTransform(k.ctx);k.executeOperatorList(n);k.endDrawing();k.dependencyTracker?.restore();M.restore();if(E||C){const e=P.canvas;E&&(v=l);C&&(x=h);const i=this.getSizeAndScale(v,this.ctx.canvas.width,y),n=this.getSizeAndScale(x,this.ctx.canvas.height,A),s=i.size,r=n.size,a=t.cachedCanvases.getCanvas("pattern-workaround",s,r),o=a.context,u=E?Math.floor(g/l):0,p=C?Math.floor(m/h):0;for(let t=0;t<=u;t++)for(let i=0;i<=p;i++)o.drawImage(e,s*t,r*i,s,r,0,0,s,r);return{canvas:a.canvas,scaleX:i.scale,scaleY:n.scale,offsetX:d,offsetY:c}}return{canvas:P.canvas,scaleX:_.scale,scaleY:D.scale,offsetX:d,offsetY:c}}getSizeAndScale(t,e,i){const n=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let s=Math.ceil(t*i);s>=n?s=n:i=s/t;return{scale:i,size:s}}clipBbox(t,e,i,n,s){const r=n-e,a=s-i;t.ctx.rect(e,i,r,a);Util.axialAlignedBoundingBox([e,i,n,s],getCurrentTransform(t.ctx),t.current.minMax);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const n=t.ctx,s=t.current;switch(e){case Et:const{fillStyle:t,strokeStyle:r}=this.ctx;n.fillStyle=s.fillColor=t;n.strokeStyle=s.strokeColor=r;break;case Ct:n.fillStyle=n.strokeStyle=i;s.fillColor=s.strokeColor=i;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,n,s){let r=i;if(n!==xt){r=Util.transform(r,e.baseTransform);this.matrix&&(r=Util.transform(r,this.matrix))}const a=this.createPatternCanvas(e,s);let o=new DOMMatrix(r);o=o.translate(a.offsetX,a.offsetY);o=o.scale(1/a.scaleX,1/a.scaleY);const l=t.createPattern(a.canvas,"repeat");l.setTransform(o);return l}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:n,height:s,nonBlackColor:r=4294967295,inverseDecode:a=!1}){const o=FeatureTest.isLittleEndian?4278190080:255,[l,h]=a?[r,o]:[o,r],d=n>>3,c=7&n,u=l^h,p=t.length;i=new Uint32Array(i.buffer);let g=0;for(let n=0;n>7&1)&u;i[g+1]=l^-(n>>6&1)&u;i[g+2]=l^-(n>>5&1)&u;i[g+3]=l^-(n>>4&1)&u;i[g+4]=l^-(n>>3&1)&u;i[g+5]=l^-(n>>2&1)&u;i[g+6]=l^-(n>>1&1)&u;i[g+7]=l^-(1&n)&u}if(0===c)continue;const n=e>7-t&1)&u}return{srcPos:e,destPos:g}}const St=16,Tt=new DOMMatrix,_t=new Float32Array(2),Dt=new Float32Array([1/0,1/0,-1/0,-1/0]);class CachedCanvases{constructor(t){this.canvasFactory=t;this.cache=Object.create(null)}getCanvas(t,e,i){let n;if(void 0!==this.cache[t]){n=this.cache[t];this.canvasFactory.reset(n,e,i)}else{n=this.canvasFactory.create(e,i);this.cache[t]=n}return n}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e);delete this.cache[t]}}}function drawImageAtIntegerCoords(t,e,i,n,s,r,a,o,l,h){const[d,c,u,p,g,m]=getCurrentTransform(t);if(0===c&&0===u){const f=a*d+g,b=Math.round(f),w=o*p+m,y=Math.round(w),A=(a+l)*d+g,v=Math.abs(Math.round(A)-b)||1,x=(o+h)*p+m,E=Math.abs(Math.round(x)-y)||1;t.setTransform(Math.sign(d),0,0,Math.sign(p),b,y);t.drawImage(e,i,n,s,r,0,0,v,E);t.setTransform(d,c,u,p,g,m);return[v,E]}if(0===d&&0===p){const f=o*u+g,b=Math.round(f),w=a*c+m,y=Math.round(w),A=(o+h)*u+g,v=Math.abs(Math.round(A)-b)||1,x=(a+l)*c+m,E=Math.abs(Math.round(x)-y)||1;t.setTransform(0,Math.sign(c),Math.sign(u),0,b,y);t.drawImage(e,i,n,s,r,0,0,E,v);t.setTransform(d,c,u,p,g,m);return[E,v]}t.drawImage(e,i,n,s,r,a,o,l,h);return[Math.hypot(d,c)*l,Math.hypot(u,p)*h]}class CanvasExtraState{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=e;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=w;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(t,e,i){i?.(this);this.clipBox=new Float32Array([0,0,t,e]);this.minMax=Dt.slice()}clone(){const t=Object.create(this);t.clipBox=this.clipBox.slice();t.minMax=this.minMax.slice();return t}getPathBoundingBox(t=At,e=null){const i=this.minMax.slice();if(t===vt){e||unreachable("Stroke bounding box must include transform.");Util.singularValueDecompose2dScale(e,_t);const t=_t[0]*this.lineWidth/2,n=_t[1]*this.lineWidth/2;i[0]-=t;i[1]-=n;i[2]+=t;i[3]+=n}return i}updateClipFromPath(){const t=Util.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(Dt,0)}getClippedPathBoundingBox(t=At,e=null){return Util.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function putBinaryImageData(t,e){if(e instanceof ImageData){t.putImageData(e,0,0);return}const i=e.height,n=e.width,s=i%St,r=(i-s)/St,a=0===s?r:r+1,o=t.createImageData(n,St);let l,h=0;const d=e.data,c=o.data;let u,p,g,m;if(e.kind===C.GRAYSCALE_1BPP){const e=d.byteLength,i=new Uint32Array(c.buffer,0,c.byteLength>>2),m=i.length,f=n+7>>3,b=4294967295,w=FeatureTest.isLittleEndian?4278190080:255;for(u=0;uf?n:8*t-7,a=-8&r;let o=0,c=0;for(;s>=1}}for(;l=r){g=s;m=n*g}l=0;for(p=m;p--;){c[l++]=d[h++];c[l++]=d[h++];c[l++]=d[h++];c[l++]=255}t.putImageData(o,0,u*St)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,n=e.width,s=i%St,r=(i-s)/St,a=0===s?r:r+1,o=t.createImageData(n,St);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,d=h?Date.now()+15:0;let c=0;const u=this.commonObjs,p=this.objs;let g,m;for(;;){if(void 0!==n&&o===n.nextBreakPoint){n.breakIt(o,i);return o}if(!s||s(o)){g=a[o];m=r[o]??null;if(g!==I.dependency)null===m?this[g](o):this[g](o,...m);else for(const t of m){this.dependencyTracker?.recordNamedData(t,o);const e=t.startsWith("g_")?u:p;if(!e.has(t)){e.get(t,i);return o}}}o++;if(o===l)return o;if(h&&++c>10){if(Date.now()>d){i();return o}c=0}}}#ts(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#ts();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#es()}#es(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,n=t.height??t.displayHeight;let s,r,a=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=n,d="prescale1";for(;a>2&&l>1||o>2&&h>1;){let e=l,i=h;if(a>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);a/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}s=this.cachedCanvases.getCanvas(d,e,i);r=s.context;r.clearRect(0,0,e,i);r.drawImage(t,0,0,l,h,0,0,e,i);t=s.canvas;l=e;h=i;d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t,e){const i=this.ctx,{width:n,height:s}=e,r=this.current.fillColor,a=this.current.patternFill,o=getCurrentTransform(i);let l,h,d,c;if((e.bitmap||e.data)&&e.count>1){const i=e.bitmap||e.data.buffer;h=JSON.stringify(a?o:[o.slice(0,4),r]);l=this._cachedBitmapsMap.getOrInsertComputed(i,makeMap);const n=l.get(h);if(n&&!a){const e=Math.round(Math.min(o[0],o[2])+o[4]),i=Math.round(Math.min(o[1],o[3])+o[5]);this.dependencyTracker?.recordDependencies(t,yt);return{canvas:n,offsetX:e,offsetY:i}}d=n}if(!d){c=this.cachedCanvases.getCanvas("maskCanvas",n,s);putBinaryImageMask(c.context,e)}let u=Util.transform(o,[1/n,0,0,-1/s,0,0]);u=Util.transform(u,[1,0,0,1,0,-s]);const p=Dt.slice();Util.axialAlignedBoundingBox([0,0,n,s],u,p);const[g,m,f,b]=p,w=Math.round(f-g)||1,y=Math.round(b-m)||1,A=this.cachedCanvases.getCanvas("fillCanvas",w,y),v=A.context,x=g,E=m;v.translate(-x,-E);v.transform(...u);if(!d){d=this._scaleImage(c.canvas,getCurrentTransformInverse(v));d=d.img;l&&a&&l.set(h,d)}v.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(v),e.interpolate);drawImageAtIntegerCoords(v,d,0,0,d.width,d.height,0,0,n,s);v.globalCompositeOperation="source-in";const C=Util.transform(getCurrentTransformInverse(v),[1,0,0,1,-x,-E]);v.fillStyle=a?r.getPattern(i,this,C,At,t):r;v.fillRect(0,0,n,s);if(l&&!a){this.cachedCanvases.delete("fillCanvas");l.set(h,A.canvas)}this.dependencyTracker?.recordDependencies(t,yt);return{canvas:A.canvas,offsetX:Math.round(x),offsetY:Math.round(E)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t);e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=e;this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t);this.ctx.lineCap=Pt[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t);this.ctx.lineJoin=Mt[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t);this.ctx.miterLimit=e}setDash(t,e,i){this.dependencyTracker?.recordSimpleData("dash",t);const n=this.ctx;if(void 0!==n.setLineDash){n.setLineDash(e);n.lineDashOffset=i}}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[i,n]of e)switch(i){case"LW":this.setLineWidth(t,n);break;case"LC":this.setLineCap(t,n);break;case"LJ":this.setLineJoin(t,n);break;case"ML":this.setMiterLimit(t,n);break;case"D":this.setDash(t,n[0],n[1]);break;case"RI":this.setRenderingIntent(t,n);break;case"FL":this.setFlatness(t,n);break;case"Font":this.setFont(t,n[0],n[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t);this.current.strokeAlpha=n;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t);this.ctx.globalAlpha=this.current.fillAlpha=n;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t);this.ctx.globalCompositeOperation=n;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t);this.current.activeSMask=n?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t);this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(n)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const e=this.ctx.canvas.width,i=this.ctx.canvas.height,n="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(n,e,i);this.suspendedCtx=this.ctx;const r=this.ctx=s.context;r.setTransform(this.suspendedCtx.getTransform());copyCtxState(this.suspendedCtx,r);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function(){e.save();this.__originalSave()};t.restore=function(){e.restore();this.__originalRestore()};t.translate=function(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function(t,i,n,s,r,a){e.transform(t,i,n,s,r,a);this.__originalTransform(t,i,n,s,r,a)};t.setTransform=function(t,i,n,s,r,a){e.setTransform(t,i,n,s,r,a);this.__originalSetTransform(t,i,n,s,r,a)};t.resetTransform=function(){e.resetTransform();this.__originalResetTransform()};t.rotate=function(t){e.rotate(t);this.__originalRotate(t)};t.clip=function(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,n,s,r,a){e.bezierCurveTo(t,i,n,s,r,a);this.__originalBezierCurveTo(t,i,n,s,r,a)};t.rect=function(t,i,n,s){e.rect(t,i,n,s);this.__originalRect(t,i,n,s)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(r,this.suspendedCtx);this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,n){const s=n[0],r=n[1],a=n[2]-s,o=n[3]-r;if(0!==a&&0!==o){this.genericComposeSMask(e.context,i,a,o,e.subtype,e.backdrop,e.transferMap,s,r,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,0,0);t.restore()}}genericComposeSMask(t,e,i,n,s,r,a,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(r)if(u<0||p<0||u+i>c.width||p+n>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,n),e=t.context;e.drawImage(c,-u,-p);e.globalCompositeOperation="destination-atop";e.fillStyle=r;e.fillRect(0,0,i,n);e.globalCompositeOperation="source-over";c=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,n);t.clip(e);t.globalCompositeOperation="destination-atop";t.fillStyle=r;t.fillRect(u,p,i,n);t.restore()}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===s&&a?e.filter=this.filterFactory.addAlphaFilter(a):"Luminosity"===s&&(e.filter=this.filterFactory.addLuminosityFilter(a));const g=new Path2D;g.rect(o,l,i,n);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(c,u,p,i,n,o,l,i,n);e.restore()}save(t){this.inSMaskMode&©CtxState(this.ctx,this.suspendedCtx);this.ctx.save();const e=this.current;this.stateStack.push(e);this.current=e.clone();this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t);if(0!==this.stateStack.length){this.current=this.stateStack.pop();this.ctx.restore();this.inSMaskMode&©CtxState(this.suspendedCtx,this.ctx);this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}else this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,n,s,r,a){this.dependencyTracker?.recordIncrementalData("transform",t);this.ctx.transform(e,i,n,s,r,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,n){let[s]=i;if(n){if(null!==this.dependencyTracker){const i=e===I.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,n[0]-i,n[2]+i,n[1]-i,n[3]+i).recordDependencies(t,["transform"])}s instanceof Path2D||(s=i[0]=makePathFromDrawOPS(s));Util.axialAlignedBoundingBox(n,getCurrentTransform(this.ctx),this.current.minMax);this[e](t,s);this._pathStartIdx=t}else{s||=i[0]=new Path2D;this[e](t,s)}}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){const n=this.ctx,s=this.current.strokeColor;n.globalAlpha=this.current.strokeAlpha;if(this.contentVisible)if("object"==typeof s&&s?.getPattern){const i=s.isModifyingCurrentTransform()?n.getTransform():null;n.save();n.strokeStyle=s.getPattern(n,this,getCurrentTransformInverse(n),vt,t);if(i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i));e=t}this.rescaleAndStroke(e,!1);n.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,pt);i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(vt,getCurrentTransform(this.ctx)));n.globalAlpha=this.current.fillAlpha}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){const n=this.ctx,s=this.current.fillColor;let r=!1;if(this.current.patternFill){const i=s.isModifyingCurrentTransform()?n.getTransform():null;this.dependencyTracker?.save(t);n.save();n.fillStyle=s.getPattern(n,this,getCurrentTransformInverse(n),At,t);if(i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i));e=t}r=!0}const a=this.current.getClippedPathBoundingBox();if(this.contentVisible&&null!==a)if(this.pendingEOFill){n.fill(e,"evenodd");this.pendingEOFill=!1}else n.fill(e);this.dependencyTracker?.recordDependencies(t,gt);if(r){n.restore();this.dependencyTracker?.restore(t)}i&&this.consumePath(t,e,a)}eoFill(t,e){this.pendingEOFill=!0;this.fill(t,e)}fillStroke(t,e){this.fill(t,e,!1);this.stroke(t,e,!1);this.consumePath(t,e)}eoFillStroke(t,e){this.pendingEOFill=!0;this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0;this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){this.ctx.fill(e);this.dependencyTracker?.recordDependencies(t,ft).recordOperation(t)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=kt}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=It}beginText(t){this.current.textMatrix=null;this.current.textMatrixScale=1;this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0;this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,i=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;void 0!==e&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t);i.recordCloseMarker(t)}if(void 0!==e){const t=new Path2D,n=i.getTransform().invertSelf();for(const{transform:i,x:s,y:r,fontSize:a,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(n).translate(s,r).scale(a,-a));i.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t);this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t);this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t);this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t);this.current.leading=-e}setFont(t,i,n){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",i,t);const s=this.commonObjs.get(i),r=this.current;if(!s)throw new Error(`Can't find font for ${i}`);r.fontMatrix=s.fontMatrix||e;0!==r.fontMatrix[0]&&0!==r.fontMatrix[3]||warn("Invalid font matrix for font "+i);if(n<0){n=-n;r.fontDirection=-1}else r.fontDirection=1;this.current.font=s;this.current.fontSize=n;if(s.isType3Font)return;const a=s.loadedName||"sans-serif",o=s.systemFontInfo?.css||`"${a}", ${s.fallbackName}`;let l="normal";s.black?l="900":s.bold&&(l="bold");const h=s.italic?"italic":"normal";let d=n;n<16?d=16:n>100&&(d=100);this.current.fontSizeScale=n/d;this.ctx.font=`${h} ${l} ${d}px ${o}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t);this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t);this.current.textRise=e}moveText(t,e,i){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t);this.current.x=this.current.lineX+=e;this.current.y=this.current.lineY+=i}setLeadingMoveText(t,e,i){this.setLeading(t,-i);this.moveText(t,e,i)}setTextMatrix(t,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);const{current:i}=this;i.textMatrix=e;i.textMatrixScale=Math.hypot(e[0],e[1]);i.x=i.lineX=0;i.y=i.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading);this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#is(t,e,i){const n=new Path2D;n.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return n}paintChar(t,e,i,n,s,r){const a=this.ctx,o=this.current,l=o.font,h=o.textRenderingMode,d=o.fontSize/o.fontSizeScale,c=h&x,u=!!(h&E),p=o.patternFill&&!l.missingFile,g=o.patternStroke&&!l.missingFile;let m;(l.disableFontFace||u||p||g)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,e));if(m&&(l.disableFontFace||p||g)){a.save();a.translate(i,n);a.scale(d,-d);this.dependencyTracker?.recordCharacterBBox(t,a,l);let e;if(c===w||c===A)if(s){e=a.getTransform();a.setTransform(...s);const t=this.#is(m,e,s);a.fill(t)}else a.fill(m);if(c===y||c===A)if(r){e||=a.getTransform();a.setTransform(...r);const{a:t,b:i,c:n,d:s}=e,o=Util.inverseTransform(r),l=Util.transform([t,i,n,s,0,0],o);Util.singularValueDecompose2dScale(l,_t);a.lineWidth*=Math.max(_t[0],_t[1])/d;a.stroke(this.#is(m,e,r))}else{a.lineWidth/=d;a.stroke(m)}a.restore()}else{if(c===w||c===A){a.fillText(e,i,n);this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,n,()=>a.measureText(e))}if(c===y||c===A){this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,n,()=>a.measureText(e)).recordDependencies(t,pt);a.strokeText(e,i,n)}}if(u){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(a),x:i,y:n,fontSize:d,path:m});this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,n)}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t,e){if(this.dependencyTracker){this.dependencyTracker.recordDependencies(t,bt).resetBBox(t);this.current.textRenderingMode&E&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies()}const i=this.current,n=i.font;if(n.isType3Font){this.showType3Text(t,e);this.dependencyTracker?.recordShowTextOperation(t);return}const s=i.fontSize;if(0===s){this.dependencyTracker?.recordOperation(t);return}const r=this.ctx,a=i.fontSizeScale,o=i.charSpacing,l=i.wordSpacing,h=i.fontDirection,d=i.textHScale*h,c=e.length,u=n.vertical,p=u?1:-1,g=n.defaultVMetrics,m=s*i.fontMatrix[0],f=i.textRenderingMode===w&&!n.disableFontFace&&!i.patternFill;r.save();i.textMatrix&&r.transform(...i.textMatrix);r.translate(i.x,i.y+i.textRise);h>0?r.scale(d,-1):r.scale(d,1);let b,v;const C=i.textRenderingMode&x,S=C===y||C===A;if((C===w||C===A)&&i.patternFill){r.save();const e=i.fillColor.getPattern(r,this,getCurrentTransformInverse(r),At,t);b=getCurrentTransform(r);r.restore();r.fillStyle=e}if(S&&i.patternStroke){r.save();const e=i.strokeColor.getPattern(r,this,getCurrentTransformInverse(r),vt,t);v=getCurrentTransform(r);r.restore();r.strokeStyle=e}let T=i.lineWidth;const _=i.textMatrixScale;0===_||0===T?S&&(T=this.getSinglePixelWidth()):T/=_;if(1!==a){r.scale(a,a);T/=a}r.lineWidth=T;if(n.isInvalidPDFjsFont){const n=[];let s=0;for(const t of e){n.push(t.unicode);s+=t.width}const a=n.join("");r.fillText(a,0,0);if(null!==this.dependencyTracker){const e=r.measureText(a);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}i.x+=s*m*d;r.restore();this.compose();return}let D,P=0;for(D=0;D0){E=r.measureText(w);const t=1e3*E.width/s*a;if(CE??r.measureText(w))}else{this.paintChar(t,w,A,x,b,v);if(y){const e=A+s*y.offset.x/a,i=x-s*y.offset.y/a;this.paintChar(t,y.fontChar,e,i,b,v)}}P+=u?C*m-c*h:C*m+c*h;d&&r.restore()}u?i.y-=P:i.x+=P*d;r.restore();this.compose();this.dependencyTracker?.recordShowTextOperation(t)}showType3Text(t,i){const n=this.ctx,s=this.current,r=s.font,a=s.fontSize,o=s.fontDirection,l=r.vertical?1:-1,h=s.charSpacing,d=s.wordSpacing,c=s.textHScale*o,u=s.fontMatrix||e,p=i.length;let g,m,f,b;if(s.textRenderingMode===v||0===a)return;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null;n.save();s.textMatrix&&n.transform(...s.textMatrix);n.translate(s.x,s.y+s.textRise);n.scale(c,o);const w=this.dependencyTracker;this.dependencyTracker=w?new CanvasNestedDependencyTracker(w,t):null;for(g=0;gnew CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new CanvasNestedDependencyTracker(this.dependencyTracker,e,!0):null)};i=new TilingPattern(e,this.ctx,n,t)}else i=this._getPattern(t,e[1],e[2]);return i}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t);this.current.strokeColor=this.getColorN_Pattern(t,e);this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t);this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t);this.ctx.strokeStyle=this.current.strokeColor=e;this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t);this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t);this.ctx.fillStyle=this.current.fillColor=e;this.current.patternFill=!1}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t);this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e,i=null){let n;if(this.cachedPatterns.has(e))n=this.cachedPatterns.get(e);else{n=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e));this.cachedPatterns.set(e,n)}i&&(n.matrix=i);return n}shadingFill(t,e){if(!this.contentVisible)return;const i=this.ctx;this.save(t);const n=this._getPattern(t,e);i.fillStyle=n.getPattern(i,this,getCurrentTransformInverse(i),xt,t);const s=getCurrentTransformInverse(i);if(s){const{width:t,height:e}=i.canvas,n=Dt.slice();Util.axialAlignedBoundingBox([0,0,t,e],s,n);const[r,a,o,l]=n;this.ctx.fillRect(r,a,o-r,l-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,wt).recordDependencies(t,gt).recordOperation(t);this.compose(this.current.getClippedPathBoundingBox());this.restore(t)}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e,i){if(this.contentVisible){this.save(t);this.baseTransformStack.push(this.baseTransform);e&&this.transform(t,...e);this.baseTransform=getCurrentTransform(this.ctx);if(i){Util.axialAlignedBoundingBox(i,this.baseTransform,this.current.minMax);const[e,n,s,r]=i,a=new Path2D;a.rect(e,n,s-e,r-n);this.ctx.clip(a);this.dependencyTracker?.recordClipBox(t,this.ctx,e,s,n,r);this.endPath(t)}}}paintFormXObjectEnd(t){if(this.contentVisible){this.restore(t);this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t,e){if(!this.contentVisible)return;this.save(t);if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const i=this.ctx;e.isolated||info("TODO: Support non-isolated groups.");e.knockout&&warn("Knockout groups not supported.");const n=getCurrentTransform(i);e.matrix&&i.transform(...e.matrix);if(!e.bbox)throw new Error("Bounding box is required.");let s=Dt.slice();Util.axialAlignedBoundingBox(e.bbox,getCurrentTransform(i),s);const r=[0,0,i.canvas.width,i.canvas.height];s=Util.intersect(s,r)||[0,0,0,0];const a=Math.floor(s[0]),o=Math.floor(s[1]),l=Math.max(Math.ceil(s[2])-a,1),h=Math.max(Math.ceil(s[3])-o,1);this.current.startNewPathAndClipBox([0,0,l,h]);let d="groupAt"+this.groupLevel;e.smask&&(d+="_smask_"+this.smaskCounter++%2);const c=this.cachedCanvases.getCanvas(d,l,h),u=c.context;u.translate(-a,-o);u.transform(...n);let p=new Path2D;const[g,m,f,b]=e.bbox;p.rect(g,m,f-g,b-m);if(e.matrix){const t=new Path2D;t.addPath(p,new DOMMatrix(e.matrix));p=t}u.clip(p);e.smask&&this.smaskStack.push({canvas:c.canvas,context:u,offsetX:a,offsetY:o,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null});if(!e.smask||this.dependencyTracker){i.setTransform(1,0,0,1,0,0);i.translate(a,o);i.save()}copyCtxState(i,u);this.ctx=u;this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i);this.setGState(t,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]);this.groupStack.push(i);this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const i=this.ctx,n=this.groupStack.pop();this.ctx=n;this.ctx.imageSmoothingEnabled=!1;this.dependencyTracker?.popBaseTransform();if(e.smask){this.tempSMask=this.smaskStack.pop();this.restore(t);this.dependencyTracker&&this.ctx.restore()}else{this.ctx.restore();const e=getCurrentTransform(this.ctx);this.restore(t);this.ctx.save();this.ctx.setTransform(...e);const n=Dt.slice();Util.axialAlignedBoundingBox([0,0,i.canvas.width,i.canvas.height],e,n);this.ctx.drawImage(i.canvas,0,0);this.ctx.restore();this.compose(n)}}beginAnnotation(t,e,i,n,s,r){this.#ts();resetCtxToDefault(this.ctx);this.ctx.save();this.save(t);this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(i){const s=i[2]-i[0],a=i[3]-i[1];if(r&&this.annotationCanvasMap){(n=n.slice())[4]-=i[0];n[5]-=i[1];(i=i.slice())[0]=i[1]=0;i[2]=s;i[3]=a;Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx),_t);const{viewportScale:t}=this,r=Math.ceil(s*this.outputScaleX*t),o=Math.ceil(a*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(r,o);const{canvas:l,context:h}=this.annotationCanvas;this.annotationCanvasMap.set(e,l);this.annotationCanvas.savedCtx=this.ctx;this.ctx=h;this.ctx.save();this.ctx.setTransform(_t[0],0,0,-_t[1],0,a*_t[1]);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath(t);const e=new Path2D;e.rect(i[0],i[1],s,a);this.ctx.clip(e)}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(t,...n);this.transform(t,...s)}endAnnotation(t){if(this.annotationCanvas){this.ctx.restore();this.#es();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const i=e.count;(e=this.getObject(t,e.data,e)).count=i;const n=this.ctx,s=this._createMaskCanvas(t,e),r=s.canvas;n.save();n.setTransform(1,0,0,1,0,0);n.drawImage(r,s.offsetX,s.offsetY);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,s.offsetX,s.offsetX+r.width,s.offsetY,s.offsetY+r.height).recordOperation(t);n.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,i,n=0,s=0,r,a){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.ctx;o.save();const l=getCurrentTransform(o);o.transform(i,n,s,r,0,0);const h=this._createMaskCanvas(t,e);o.setTransform(1,0,0,1,h.offsetX-l[4],h.offsetY-l[5]);this.dependencyTracker?.resetBBox(t);for(let e=0,d=a.length;ee?h/e:1;a=l>e?l/e:1}}this._cachedScaleForStroking[0]=r;this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:n}}=this,[s,r]=this.getScaleForStroking();if(s===r){i.lineWidth=(n||1)*s;i.stroke(t);return}const a=i.getLineDash();e&&i.save();i.scale(s,r);Tt.a=1/s;Tt.d=1/r;const o=new Path2D;o.addPath(t,Tt);if(a.length>0){const t=Math.max(s,r);i.setLineDash(a.map(e=>e/t));i.lineDashOffset/=t}i.lineWidth=n||1;i.stroke(o);e&&i.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in I)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[I[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#ns=null;static#ss="";static get workerPort(){return this.#ns}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#ns=t}static get workerSrc(){return this.#ss}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#ss=t}}class Metadata{#rs;#as;constructor({parsedData:t,rawData:e}){this.#rs=t;this.#as=e}getRaw(){return this.#as}get(t){return this.#rs.get(t)??null}[Symbol.iterator](){return this.#rs.entries()}}const Ft=Symbol("INTERNAL");class OptionalContentGroup{#os=!1;#ls=!1;#hs=!1;#ds=!0;constructor(t,{name:e,intent:i,usage:n,rbGroups:a}){this.#os=!!(t&s);this.#ls=!!(t&r);this.name=e;this.intent=i;this.usage=n;this.rbGroups=a}get visible(){if(this.#hs)return this.#ds;if(!this.#ds)return!1;const{print:t,view:e}=this.usage;return this.#os?"OFF"!==e?.viewState:!this.#ls||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Ft&&unreachable("Internal method `_setVisible` called.");this.#hs=i;this.#ds=e}}class OptionalContentConfig{#cs=null;#us=new Map;#ps=null;#gs=null;constructor(t,e=s){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#gs=t.order;for(const i of t.groups)this.#us.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#us.values())t._setVisible(Ft,!1);for(const e of t.on)this.#us.get(e)._setVisible(Ft,!0);for(const e of t.off)this.#us.get(e)._setVisible(Ft,!1);this.#ps=this.getHash()}}#ms(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let n=1;n0){const t=getArrayBuffer(i);this._queuedChunks.push(t)}this._progressiveDone=n;e.addRangeListener((t,e)=>{this.#ws(t,e)});e.addProgressiveReadListener(t=>{this.#ws(void 0,t)});e.addProgressiveDoneListener(()=>{this._fullReader?.progressiveDone();this._progressiveDone=!0});e.transportReady()}#ws(t,e){const i=getArrayBuffer(e);if(void 0===t)this._fullReader?this._fullReader._enqueue(i):this._queuedChunks.push(i);else{const e=this._rangeReaders.keys().find(e=>e._begin===t);assert(e,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");e._enqueue(i)}}getFullReader(){const t=super.getFullReader();this._queuedChunks=null;return t}getRangeReader(t,e){const i=super.getRangeReader(t,e);if(i){i.onDone=()=>this._rangeReaders.delete(i);this._source.pdfDataRangeTransport.requestDataRange(t,e)}return i}cancelAllRequests(t){super.cancelAllRequests(t);this._source.pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader extends BasePDFStreamReader{#ys=endRequests.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:e,disableRange:i,disableStream:n}=t._source,{length:s,contentDispositionFilename:r}=e;this._queuedChunks=t._queuedChunks||[];for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._done=t._progressiveDone;this._contentLength=s;this._isStreamingSupported=!n;this._isRangeSupported=!i;isPdfFile(r)&&(this._filename=r);this._headersCapability.resolve();const a=this._loaded;Promise.resolve().then(()=>{a>0&&this._loaded===a&&this._callOnProgress()})}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength;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();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this.#ys()}progressiveDone(){this._done||=!0;0===this._queuedChunks.length&&this.#ys()}}class PDFDataTransportStreamRangeReader extends BasePDFStreamRangeReader{#ys=endRequests.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,e,i){super(t,e,i);this._begin=e}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});this.#ys()}this._done=!0;this.onDone?.()}}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this.#ys();this.onDone?.()}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const n=e[t];void 0!==n&&i.append(t,n)}return i}function getResponseOrigin(t){return URL.parse(t)?.origin??null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:n}){const s={allowRangeRequests:!1,suggestedLength:void 0},r=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(r))return s;s.suggestedLength=r;if(r<=2*i)return s;if(n||!e)return s;if("bytes"!==t.get("Accept-Ranges"))return s;if("identity"!==(t.get("Content-Encoding")||"identity"))return s;s.allowRangeRequests=!0;return s}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const n=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,n,s]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[n,s]}const s=[];for(let t=0;t{t._responseOrigin=getResponseOrigin(i.url);ensureResponseStatus(i.status,r);this._reader=i.body.getReader();const n=i.headers,{allowRangeRequests:a,suggestedLength:o}=validateRangeRequestCapabilities({responseHeaders:n,isHttp:!0,rangeChunkSize:s,disableRange:e});this._isRangeSupported=a;this._contentLength=o||this._contentLength;this._filename=extractFilenameFromHeader(n);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."));this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this._callOnProgress();return{value:fetch_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader extends BasePDFStreamRangeReader{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const{url:n,withCredentials:s}=t._source,r=new Headers(t.headers);r.append("Range",`bytes=${e}-${i-1}`);fetchUrl(n,r,s,this._abortController).then(e=>{ensureResponseOrigin(getResponseOrigin(e.url),t._responseOrigin);ensureResponseStatus(e.status,n);this._reader=e.body.getReader();this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:fetch_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFNetworkStream extends BasePDFStream{#As=new WeakMap;_responseOrigin=null;constructor(t){super(t,PDFNetworkStreamReader,PDFNetworkStreamRangeReader);const{httpHeaders:e,url:i}=t;this.url=i;this.isHttp=/https?:/.test(i.protocol);this.headers=createHeaders(this.isHttp,e)}_request(t){const e=new XMLHttpRequest,i={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#As.set(e,i);e.open("GET",this.url);e.withCredentials=this._source.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);i.validateStatus=t=>206===t||200===t}else i.validateStatus=t=>200===t;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>t.onError(e.status);e.onreadystatechange=this.#vs.bind(this,e);e.onprogress=this.#xs.bind(this,e);e.send(null);return e}#xs(t,e){const i=this.#As.get(t);i?.onProgress?.(e)}#vs(t,e){const i=this.#As.get(t);if(!i)return;if(t.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==t.readyState)return;if(!this.#As.has(t))return;this.#As.delete(t);if(0===t.status&&this.isHttp){i.onError(t.status);return}const n=t.status||200;if(!i.validateStatus(n)){i.onError(t.status);return}const s=function network_getArrayBuffer(t){return"string"!=typeof t?t:stringToBytes(t).buffer}(t.response);if(206===n){const e=t.getResponseHeader("Content-Range");if(/bytes (\d+)-(\d+)\/(\d+)/.test(e))i.onDone(s);else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else s?i.onDone(s):i.onError(t.status)}_abortRequest(t){if(this.#As.has(t)){this.#As.delete(t);t.abort()}}getRangeReader(t,e){const i=super.getRangeReader(t,e);i&&(i.onClosed=()=>this._rangeReaders.delete(i));return i}}class PDFNetworkStreamReader extends BasePDFStreamReader{#ys=endRequests.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t);const{length:e}=t._source;this._contentLength=e;this._fullRequestXhr=t._request({onHeadersReceived:this.#Es.bind(this),onDone:this.#Cs.bind(this),onError:this.#Ss.bind(this),onProgress:this.#xs.bind(this)})}#Es(){const t=this._stream,{disableRange:e,rangeChunkSize:i}=t._source,n=this._fullRequestXhr;t._responseOrigin=getResponseOrigin(n.responseURL);const s=n.getAllResponseHeaders(),r=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{allowRangeRequests:a,suggestedLength:o}=validateRangeRequestCapabilities({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:i,disableRange:e});a&&(this._isRangeSupported=!0);this._contentLength=o||this._contentLength;this._filename=extractFilenameFromHeader(r);this._isRangeSupported&&t._abortRequest(n);this._headersCapability.resolve()}#Cs(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._cachedChunks.push(t);this._done=!0;0===this._cachedChunks.length&&this.#ys()}#Ss(t){this._storedError=createResponseError(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}#xs(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);this.#ys();this._stream._abortRequest(this._fullRequestXhr);this._fullRequestXhr=null}}class PDFNetworkStreamRangeReader extends BasePDFStreamRangeReader{#ys=endRequests.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,e,i){super(t,e,i);this._requestXhr=t._request({begin:e,end:i,onHeadersReceived:this.#Es.bind(this),onDone:this.#Cs.bind(this),onError:this.#Ss.bind(this),onProgress:null})}#Es(){const t=getResponseOrigin(this._requestXhr?.responseURL);try{ensureResponseOrigin(t,this._stream._responseOrigin)}catch(t){this._storedError=t;this.#Ss(0)}}#Cs(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunk=t;this._done=!0;this.#ys();this.onClosed?.()}#Ss(t){this._storedError??=createResponseError(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;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this.#ys();this._stream._abortRequest(this._requestXhr);this.onClosed?.()}}function getReadableStream(t){const{Readable:e}=process.getBuiltinModule("stream");if("function"==typeof e.toWeb)return e.toWeb(t);return process.getBuiltinModule("module").createRequire(import.meta.url)("node-readable-to-web-readable-stream").makeDefaultReadableStreamFromNodeReadable(t)}class PDFNodeStream extends BasePDFStream{constructor(t){super(t,PDFNodeStreamReader,PDFNodeStreamRangeReader);const{url:e}=t;assert("file:"===e.protocol,"PDFNodeStream only supports file:// URLs.")}}class PDFNodeStreamReader extends BasePDFStreamReader{_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:i,length:n,rangeChunkSize:s,url:r}=t._source;this._contentLength=n;this._isStreamingSupported=!i;this._isRangeSupported=!e;const a=process.getBuiltinModule("fs");a.promises.lstat(r).then(t=>{const e=getReadableStream(a.createReadStream(r));this._reader=e.getReader();const{size:i}=t;i<=2*s&&(this._isRangeSupported=!1);this._contentLength=i;!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."));this._headersCapability.resolve()}).catch(t=>{"ENOENT"===t.code&&(t=createResponseError(0,r));this._headersCapability.reject(t)})}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this._callOnProgress();return{value:fetch_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t)}}class PDFNodeStreamRangeReader extends BasePDFStreamRangeReader{_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const{url:n}=t._source,s=process.getBuiltinModule("fs");try{const t=getReadableStream(s.createReadStream(n,{start:e,end:i-1}));this._reader=t.getReader();this._readCapability.resolve()}catch(t){this._readCapability.reject(t)}}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:fetch_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t)}}const Rt=Symbol("INITIAL_DATA"),dataObj=()=>({...Promise.withResolvers(),data:Rt});class PDFObjects{#Ts=new Map;#_s(t){return this.#Ts.getOrInsertComputed(t,dataObj)}get(t,e=null){if(e){const i=this.#_s(t);i.promise.then(()=>e(i.data));return null}const i=this.#Ts.get(t);if(!i||i.data===Rt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Ts.get(t);return!!e&&e.data!==Rt}delete(t){const e=this.#Ts.get(t);if(!e||e.data===Rt)return!1;this.#Ts.delete(t);return!0}resolve(t,e=null){const i=this.#_s(t);i.data=e;i.resolve()}clear(){for(const{data:t}of this.#Ts.values())t?.bitmap?.close();this.#Ts.clear()}*[Symbol.iterator](){for(const[t,{data:e}]of this.#Ts)e!==Rt&&(yield[t,e])}}class TextLayer{#Ds=Promise.withResolvers();#Ot=null;#Ps=!1;#Ms=!!globalThis.FontInspector?.enabled;#ks=null;#Is=null;#Fs=0;#Rs=0;#Bs=null;#Ls=null;#Os=0;#Ns=0;#Us=Object.create(null);#Hs=[];#zs=null;#Gs=[];#Ws=new WeakMap;#Vs=null;static#js=new Map;static#$s=new Map;static#Xs=new WeakMap;static#qs=null;static#Ks=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#zs=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#zs=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#Ot=this.#Ls=e;this.#Ns=i.scale*OutputScale.pixelRatio;this.#Os=i.rotation;this.#Is={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:s,pageX:r,pageY:a}=i.rawDims;this.#Vs=[1,0,0,-1,-r,a+s];this.#Rs=n;this.#Fs=s;TextLayer.#Ys();e.style.setProperty("--min-font-size",TextLayer.#qs);setLayerDimensions(e,i);this.#Ds.promise.finally(()=>{TextLayer.#Ks.delete(this);this.#Is=null;this.#Us=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Bs.read().then(({value:t,done:e})=>{if(e)this.#Ds.resolve();else{this.#ks??=t.lang;Object.assign(this.#Us,t.styles);this.#Qs(t.items);pump()}},this.#Ds.reject)};this.#Bs=this.#zs.getReader();TextLayer.#Ks.add(this);pump();return this.#Ds.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*OutputScale.pixelRatio,n=t.rotation;if(n!==this.#Os){e?.();this.#Os=n;setLayerDimensions(this.#Ls,{rotation:n})}if(i!==this.#Ns){e?.();this.#Ns=i;const t={div:null,properties:null,ctx:TextLayer.#Js(this.#ks)};for(const e of this.#Gs){t.properties=this.#Ws.get(e);t.div=e;this.#Zs(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Bs?.cancel(t).catch(()=>{});this.#Bs=null;this.#Ds.reject(t)}get textDivs(){return this.#Gs}get textContentItemsStr(){return this.#Hs}#Qs(t){if(this.#Ps)return;this.#Is.ctx??=TextLayer.#Js(this.#ks);const e=this.#Gs,i=this.#Hs;for(const n of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Ps=!0;return}if(void 0!==n.str){i.push(n.str);this.#tr(n)}else if("beginMarkedContentProps"===n.type||"beginMarkedContent"===n.type){const t=this.#Ot;this.#Ot=document.createElement("span");this.#Ot.classList.add("markedContent");n.id&&this.#Ot.setAttribute("id",`${n.id}`);"Artifact"===n.tag&&(this.#Ot.ariaHidden=!0);t.append(this.#Ot)}else"endMarkedContent"===n.type&&(this.#Ot=this.#Ot.parentNode)}}#tr(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Gs.push(e);const n=Util.transform(this.#Vs,t.transform);let s=Math.atan2(n[1],n[0]);const r=this.#Us[t.fontName];r.vertical&&(s+=Math.PI/2);let a=this.#Ms&&r.fontSubstitution||r.fontFamily;a=TextLayer.fontFamilyMap.get(a)||a;const o=Math.hypot(n[2],n[3]),l=o*TextLayer.#er(a,r,this.#ks);let h,d;if(0===s){h=n[4];d=n[5]-l}else{h=n[4]+l*Math.sin(s);d=n[5]-l*Math.cos(s)}const c=e.style;c.left=`${(100*h/this.#Rs).toFixed(2)}%`;c.top=`${(100*d/this.#Fs).toFixed(2)}%`;c.setProperty("--font-height",`${o.toFixed(2)}px`);c.fontFamily=a;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ms&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName);0!==s&&(i.angle=s*(180/Math.PI));let u=!1;if(t.str.length>1)u=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(u=!0)}u&&(i.canvasWidth=r.vertical?t.height:t.width);this.#Ws.set(e,i);this.#Is.div=e;this.#Is.properties=i;this.#Zs(this.#Is);i.hasText&&this.#Ot.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#Ot.append(t)}}#Zs(t){const{div:e,properties:i,ctx:n}=t,{style:s}=e;if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=s,{canvasWidth:r,fontSize:a}=i;TextLayer.#ir(n,a*this.#Ns,t);const{width:o}=n.measureText(e.textContent);o>0&&s.setProperty("--scale-x",r*this.#Ns/o)}0!==i.angle&&s.setProperty("--rotate",`${i.angle}deg`)}static cleanup(){if(!(this.#Ks.size>0)){this.#js.clear();for(const{canvas:t}of this.#$s.values())t.remove();this.#$s.clear()}}static#Js(t=null){let e=this.#$s.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#$s.set(t,e);this.#Xs.set(e,{size:0,family:""})}return e}static#ir(t,e,i){const n=this.#Xs.get(t);if(e!==n.size||i!==n.family){t.font=`${e}px ${i}`;n.size=e;n.family=i}}static#Ys(){if(null!==this.#qs)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.#qs=t.getBoundingClientRect().height;t.remove()}static#er(t,e,i){const n=this.#js.get(t);if(n)return n;const s=this.#Js(i);s.canvas.width=s.canvas.height=30;this.#ir(s,30,t);const r=s.measureText(""),a=r.fontBoundingBoxAscent,o=Math.abs(r.fontBoundingBoxDescent);s.canvas.width=s.canvas.height=0;let l=.8;if(a)l=a/(a+o);else{FeatureTest.platform.isFirefox&&warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering.");e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)}this.#js.set(t,l);return l}}function getDocument(e={}){"string"==typeof e||e instanceof URL?e={url:e}:(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e={data:e});const i=new PDFDocumentLoadingTask,{docId:n}=i,s=e.url?function getUrlProp(e){if(e instanceof URL)return e;if("string"==typeof e){if(t){if(/^[a-z][a-z0-9\-+.]+:/i.test(e))return new URL(e);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(e))}const i=URL.parse(e,window.location);if(i)return i}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(e.url):null,r=e.data?function getDataProp(e){if(t&&"undefined"!=typeof Buffer&&e instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength)return e;if("string"==typeof e)return stringToBytes(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||"object"==typeof e&&!isNaN(e?.length))return new Uint8Array(e);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(e.data):null,a=e.httpHeaders||null,o=!0===e.withCredentials,l=e.password??null,h=e.range instanceof PDFDataRangeTransport?e.range:null,d=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:65536;let c=e.worker instanceof PDFWorker?e.worker:null;const u=e.verbosity,p="string"!=typeof e.docBaseUrl||isDataScheme(e.docBaseUrl)?null:e.docBaseUrl,g=getFactoryUrlProp(e.cMapUrl),m=!1!==e.cMapPacked,f=e.CMapReaderFactory||(t?NodeCMapReaderFactory:DOMCMapReaderFactory),b=getFactoryUrlProp(e.iccUrl),w=getFactoryUrlProp(e.standardFontDataUrl),y=e.StandardFontDataFactory||(t?NodeStandardFontDataFactory:DOMStandardFontDataFactory),A=getFactoryUrlProp(e.wasmUrl),v=e.WasmFactory||(t?NodeWasmFactory:DOMWasmFactory),x=!0!==e.stopAtErrors,E=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,C=!1!==e.isEvalSupported,S="boolean"==typeof e.isOffscreenCanvasSupported?e.isOffscreenCanvasSupported:!t,T="boolean"==typeof e.isImageDecoderSupported?e.isImageDecoderSupported:!t&&(FeatureTest.platform.isFirefox||!globalThis.chrome),_=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,D="boolean"==typeof e.disableFontFace?e.disableFontFace:t,P=!0===e.fontExtraProperties,M=!0===e.enableXfa,k=e.ownerDocument||globalThis.document,I=!0===e.disableRange,F=!0===e.disableStream,R=!0===e.disableAutoFetch,B=!0===e.pdfBug,L=e.CanvasFactory||(t?NodeCanvasFactory:DOMCanvasFactory),O=e.FilterFactory||(t?NodeFilterFactory:DOMFilterFactory),N=!0===e.enableHWA,U=!1!==e.useWasm,H=e.pagesMapper||new PagesMapper,z=h?h.length:e.length??NaN,G="boolean"==typeof e.useSystemFonts?e.useSystemFonts:!t&&!D,W="boolean"==typeof e.useWorkerFetch?e.useWorkerFetch:!!(f===DOMCMapReaderFactory&&y===DOMStandardFontDataFactory&&v===DOMWasmFactory&&g&&w&&A&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(w,document.baseURI)&&isValidFetchUrl(A,document.baseURI));setVerbosityLevel(u);const V={canvasFactory:new L({ownerDocument:k,enableHWA:N}),filterFactory:new O({docId:n,ownerDocument:k}),cMapReaderFactory:W?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:W?null:new y({baseUrl:w}),wasmFactory:W?null:new v({baseUrl:A})};if(!c){c=PDFWorker.create({verbosity:u,port:GlobalWorkerOptions.workerPort});i._worker=c}const j={docId:n,apiVersion:"5.5.207",data:r,password:l,disableAutoFetch:R,rangeChunkSize:d,length:z,docBaseUrl:p,enableXfa:M,evaluatorOptions:{maxImageSize:E,disableFontFace:D,ignoreErrors:x,isEvalSupported:C,isOffscreenCanvasSupported:S,isImageDecoderSupported:T,canvasMaxAreaInBytes:_,fontExtraProperties:P,useSystemFonts:G,useWasm:U,useWorkerFetch:W,cMapUrl:g,iccUrl:b,standardFontDataUrl:w,wasmUrl:A}},$={ownerDocument:k,pdfBug:B,styleElement:null,enableHWA:N,loadingParams:{disableAutoFetch:R,enableXfa:M}};c.promise.then(function(){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=c.messageHandler.sendWithPromise("GetDocRequest",j,r?[r.buffer]:null);let l;if(h)l=new PDFDataTransportStream({pdfDataRangeTransport:h,disableRange:I,disableStream:F});else if(!r){if(!s)throw new Error("getDocument - no `url` parameter provided.");const e=isValidFetchUrl(s)?PDFFetchStream:t?PDFNodeStream:PDFNetworkStream;l=new e({url:s,length:z,httpHeaders:a,withCredentials:o,rangeChunkSize:d,disableRange:I,disableStream:F})}return e.then(t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(n,t,c.port),s=new WorkerTransport(e,i,l,$,V,H);i._transport=s;e.send("Ready",null)})}).catch(i._capability.reject);return i}class PDFDocumentLoadingTask{static#fn=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+PDFDocumentLoadingTask.#fn++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}async getData(){return this._transport.getData()}}class PDFDataRangeTransport{#Ds=Promise.withResolvers();#nr=[];#sr=[];#rr=[];constructor(t,e,i=!1,n=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=n;Object.defineProperty(this,"onDataProgress",{value:()=>{deprecated("`PDFDataRangeTransport.prototype.onDataProgress` - method was removed, since loading progress is now reported automatically through the `PDFDataTransportStream` class (and related code).")}})}addRangeListener(t){this.#rr.push(t)}addProgressiveReadListener(t){this.#sr.push(t)}addProgressiveDoneListener(t){this.#nr.push(t)}onDataRange(t,e){for(const i of this.#rr)i(t,e)}onDataProgressiveRead(t){this.#Ds.promise.then(()=>{for(const e of this.#sr)e(t)})}onDataProgressiveDone(){this.#Ds.promise.then(()=>{for(const t of this.#nr)t()})}transportReady(){this.#Ds.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}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 shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(t){return this._transport.extractPages(t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#ar=!1;#or=null;constructor(t,e,i,n,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._intentStates=new Map;this.destroyed=!1;this.recordedBBoxes=null;this.#or=n}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:n=0,dontFlip:s=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:i,intent:n="display",annotationMode:s=c.ENABLE,transform:a=null,background:o=null,optionalContentConfigPromise:l=null,annotationCanvasMap:h=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:p=!1,recordOperations:g=!1,operationsFilter:m=null}){this._stats?.time("Overall");const f=this._transport.getRenderingIntent(n,s,u,p),{renderingIntent:b,cacheKey:w}=f;this.#ar=!1;l||=this._transport.getOptionalContentConfig(b);const y=this._intentStates.getOrInsertComputed(w,makeObj);if(y.streamReaderCancelTimeout){clearTimeout(y.streamReaderCancelTimeout);y.streamReaderCancelTimeout=null}const A=!!(b&r);if(!y.displayReadyCapability){y.displayReadyCapability=Promise.withResolvers();y.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(f)}const v=Boolean(this._pdfBug&&globalThis.StepperManager?.enabled),x=!this.recordedBBoxes&&(g||v),complete=t=>{y.renderTasks.delete(E);if(x){const t=E.gfx?.dependencyTracker.take();if(t){E.stepper&&E.stepper.setOperatorBBoxes(t,E.gfx.dependencyTracker.takeDebugMetadata());g&&(this.recordedBBoxes=t)}}A&&(this.#ar=!0);this.#lr();if(t){E.capability.reject(t);this._abortOperatorList({intentState:y,reason:t instanceof Error?t:new Error(t)})}else E.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},E=new InternalRenderTask({callback:complete,params:{canvas:e,canvasContext:t,dependencyTracker:x?new CanvasDependencyTracker(e,y.operatorList.length,v):null,viewport:i,transform:a,background:o},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:y.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!A,pdfBug:this._pdfBug,pageColors:d,enableHWA:this._transport.enableHWA,operationsFilter:m});(y.renderTasks||=new Set).add(E);const C=E.task;Promise.all([y.displayReadyCapability.promise,l]).then(([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&b))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");E.initializeGraphics({transparency:t,optionalContentConfig:e});E.operatorListChanged()}}).catch(complete);return C}getOperatorList({intent:t="display",annotationMode:e=c.ENABLE,printAnnotationStorage:i=null,isEditing:n=!1}={}){const s=this._transport.getRenderingIntent(t,e,i,n,!0),r=this._intentStates.getOrInsertComputed(s.cacheKey,makeObj);let a;if(!r.opListReadCapability){a=Object.create(null);a.operatorListChanged=function operatorListChanged(){if(r.operatorList.lastChunk){r.opListReadCapability.resolve(r.operatorList);r.renderTasks.delete(a)}};r.opListReadCapability=Promise.withResolvers();(r.renderTasks||=new Set).add(a);r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(s)}return r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#or.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}async getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>XfaText.textContent(t));const e=this.streamTextContent(t),i={items:[],styles:Object.create(null),lang:null};for await(const t of e){i.lang??=t.lang;Object.assign(i.styles,t.styles);i.items.push(...t.items)}return i}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#ar=!1;return Promise.all(t)}cleanup(t=!1){this.#ar=!0;const e=this.#lr();t&&e&&(this._stats&&=new StatTimer);return e}#lr(){if(!this.#ar||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#ar=!1;return!0}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,n=t.length;i{a.read().then(({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}},t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#lr()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}t.streamReader.cancel(new AbortException(e.message)).catch(()=>{});t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class PDFWorker{#Ds=Promise.withResolvers();#hr=null;#ns=null;#dr=null;static#cr=0;static#ur=!1;static#pr=new WeakMap;static{if(t){this.#ur=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const n=new URL(e,i);return i.origin===n.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};this.fromPort=t=>{deprecated("`PDFWorker.fromPort` - please use `PDFWorker.create` instead.");if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.create(t)}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;if(e){if(PDFWorker.#pr.has(e))throw new Error("Cannot use more than one PDFWorker per port.");PDFWorker.#pr.set(e,this);this.#gr(e)}else this.#mr()}get promise(){return this.#Ds.promise}#fr(){this.#Ds.resolve();this.#hr.send("configure",{verbosity:this.verbosity})}get port(){return this.#ns}get messageHandler(){return this.#hr}#gr(t){this.#ns=t;this.#hr=new MessageHandler("main","worker",t);this.#hr.on("ready",()=>{});this.#fr()}#mr(){if(PDFWorker.#ur||PDFWorker.#br){this.#wr();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{n.abort();i.destroy();e.terminate();this.destroyed?this.#Ds.reject(new Error("Worker was destroyed")):this.#wr()},n=new AbortController;e.addEventListener("error",()=>{this.#dr||terminateEarly()},{signal:n.signal});i.on("test",t=>{n.abort();if(!this.destroyed&&t){this.#hr=i;this.#ns=e;this.#dr=e;this.#fr()}else terminateEarly()});i.on("ready",t=>{n.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this.#wr()}});const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this.#wr()}#wr(){if(!PDFWorker.#ur){warn("Setting up fake worker.");PDFWorker.#ur=!0}PDFWorker._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this.#Ds.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this.#ns=e;const i="fake"+PDFWorker.#cr++,n=new MessageHandler(i+"_worker",i,e);t.setup(n,e);this.#hr=new MessageHandler(i,i+"_worker",e);this.#fr()}).catch(t=>{this.#Ds.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0;this.#dr?.terminate();this.#dr=null;PDFWorker.#pr.delete(this.#ns);this.#ns=null;this.#hr?.destroy();this.#hr=null}static create(t){const e=this.#pr.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#br(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#br)return this.#br;return(await import( /*webpackIgnore: true*/ /*@vite-ignore*/ this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{downloadInfoCapability=Promise.withResolvers();#yr=null;#Ar=new Map;#vr=null;#xr=new Map;#Er=new Map;#Cr=new Map;#Sr=null;#Tr=null;constructor(t,e,i,n,s,r){this.messageHandler=t;this.loadingTask=e;this.#vr=i;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:n.ownerDocument,styleElement:n.styleElement});this.enableHWA=n.enableHWA;this.loadingParams=n.loadingParams;this._params=n;this.canvasFactory=s.canvasFactory;this.filterFactory=s.filterFactory;this.cMapReaderFactory=s.cMapReaderFactory;this.standardFontDataFactory=s.standardFontDataFactory;this.wasmFactory=s.wasmFactory;this.destroyed=!1;this.destroyCapability=null;this.setupMessageHandler();this.pagesMapper=r;this.pagesMapper.addListener(this.#_r.bind(this))}#_r({type:t,pageNumbers:e}){if("copy"===t){this.#Tr=new Map;for(const t of e)this.#Tr.set(t,{proxy:this.#xr.get(t-1)||null,promise:this.#Er.get(t-1)||null});return}if("delete"===t)for(const t of e){this.#xr.delete(t-1);this.#Er.delete(t-1)}const i=new Map,n=new Map,{pagesMapper:s}=this;for(let t=0,e=s.pagesNumber;tthis.messageHandler.sendWithPromise(t,e))}#xs({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:MathClamp(Math.round(t/e*100),0,100)})}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=c.ENABLE,i=null,u=!1,p=!1){let g=s,m=Q;switch(t){case"any":g=n;break;case"display":break;case"print":g=r;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&r&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case c.DISABLE:g+=l;break;case c.ENABLE:break;case c.ENABLE_FORMS:g+=a;break;case c.ENABLE_STORAGE:g+=o;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}u&&(g+=h);p&&(g+=d);const{ids:b,hash:w}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,w].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Sr?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#xr.values())t.push(e._destroy());this.#xr.clear();this.#Er.clear();this.#Cr.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then(()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Ar.clear();this.filterFactory.destroy();TextLayer.cleanup();this.#vr?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()},this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{assert(this.#vr,"GetReader - no `BasePDFStream` instance available.");this.#yr=this.#vr.getFullReader();this.#yr.onProgress=t=>this.#xs(t);e.onPull=()=>{this.#yr.read().then(function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}}).catch(t=>{e.error(t)})};e.onCancel=t=>{this.#yr.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}});t.on("ReaderHeadersReady",async t=>{await this.#yr.headersReady;const{isStreamingSupported:e,isRangeSupported:i,contentLength:n}=this.#yr;e&&i&&(this.#yr.onProgress=null);return{isStreamingSupported:e,isRangeSupported:i,contentLength:n}});t.on("GetRangeReader",(t,e)=>{assert(this.#vr,"GetRangeReader - no `BasePDFStream` instance available.");const i=this.#vr.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then(function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}}).catch(t=>{e.error(t)})};e.onCancel=t=>{i.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}}else e.close()});t.on("GetDoc",({pdfInfo:t})=>{this.pagesMapper.pagesNumber=t.numPages;this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))});t.on("DocException",t=>{e._capability.reject(wrapReason(t))});t.on("PasswordRequest",t=>{this.#Sr=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Sr.reject(t):this.#Sr.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Sr.reject(t)}return this.#Sr.promise});t.on("DataLoaded",t=>{this.#xs({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)});t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#xr.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)});t.on("commonobj",([e,i,n])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in n){const t=n.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const s=new FontInfo(n),r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new FontFaceObject(s,r,n.extra,n.charProcOperatorList);this.fontLoader.bind(a).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{!a.fontExtraProperties&&a.data&&a.clearData();this.commonObjs.resolve(e,a)});break;case"CopyLocalImage":const{imageRef:o}=n;assert(o,"The imageRef must be defined.");for(const t of this.#xr.values())for(const[,i]of t.objs)if(i?.ref===o){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":this.commonObjs.resolve(e,new FontPathInfo(n));break;case"Image":this.commonObjs.resolve(e,n);break;case"Pattern":const l=new PatternInfo(n);this.commonObjs.resolve(e,l.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null});t.on("obj",([t,e,i,n])=>{if(this.destroyed)return;const s=this.#xr.get(e);if(!s.objs.has(t))if(0!==s._intentStates.size)switch(i){case"Image":case"Pattern":s.objs.resolve(t,n);break;default:throw new Error(`Got unknown object type ${i}`)}else n?.bitmap?.close()});t.on("DocProgress",t=>{this.destroyed||this.#xs(t)});t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");const e=this[t.type];if(!e)throw new Error(`${t.type} not initialized, see the \`useWorkerFetch\` parameter.`);return e.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this.#yr?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){return this.messageHandler.sendWithPromise("ExtractPages",{pageInfos:t})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.pagesMapper.getPageId(t)-1,n=this.#Er.get(e);if(n)return n;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:i}).then(t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#Cr.set(t.refStr,i);const n=new PDFPageProxy(e,t,this,this.pagesMapper,this._params.pdfBug);this.#xr.set(e,n);return n});this.#Er.set(e,s);return s}async getPageIndex(t){if(!isRefProxy(t))throw new Error("Invalid pageIndex request.");const e=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}),i=this.pagesMapper.getPageNumber(e+1);if(0===i)throw new Error("GetPageIndex: page has been removed.");return i-1}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(t+1)-1,intent:e})}getFieldObjects(){return this.#Dr("GetFieldObjects")}hasJSActions(){return this.#Dr("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#Dr("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.#Dr("GetOptionalContentConfig").then(e=>new OptionalContentConfig(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata";return this.#Ar.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new Metadata(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.#xr.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Ar.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`,i=this.#Cr.get(e);if(i>=0){const t=this.pagesMapper.getPageNumber(i+1);if(0!==t)return t}return null}}class RenderTask{_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:e}=this._internalRenderTask;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Pr=null;static#Mr=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:n,annotationCanvasMap:s,operatorList:r,pageIndex:a,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null,enableHWA:u=!1,operationsFilter:p=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=n;this.annotationCanvasMap=s;this.operatorListIdx=null;this.operatorList=r;this._pageIndex=a;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=d;this.pageColors=c;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvas;this._canvasContext=e.canvas?null:e.canvasContext;this._enableHWA=u;this._dependencyTracker=e.dependencyTracker;this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Mr.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Mr.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{viewport:i,transform:n,background:s,dependencyTracker:r}=this.params,a=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new CanvasGraphics(a,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,r);this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:s});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#Pr){window.cancelAnimationFrame(this.#Pr);this.#Pr=null}InternalRenderTask.#Mr.delete(this._canvas);t||=new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e);this.callback(t);this.task.onError?.(t)}operatorListChanged(){if(this.graphicsReady){this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length);this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Pr=window.requestAnimationFrame(()=>{this.#Pr=null;this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Mr.delete(this._canvas);this.callback()}}}}}const Bt="5.5.207",Lt="527964698";class ColorPicker{#kr=null;#Ir=null;#Fr;#Rr=null;#Br=!1;#Lr=!1;#b=null;#Or;#Nr=null;#P=null;static#Ur=null;static get _keyboardManager(){return shadow(this,"_keyboardManager",new KeyboardManager([[["Escape","mac+Escape"],ColorPicker.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ColorPicker.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ColorPicker.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ColorPicker.prototype._moveToPrevious],[["Home","mac+Home"],ColorPicker.prototype._moveToBeginning],[["End","mac+End"],ColorPicker.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){if(t){this.#Lr=!1;this.#b=t}else this.#Lr=!0;this.#P=t?._uiManager||e;this.#Or=this.#P._eventBus;this.#Fr=t?.color?.toUpperCase()||this.#P?.highlightColors.values().next().value||"#FFFF98";ColorPicker.#Ur||=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.#kr=document.createElement("button");t.className="colorPicker";t.tabIndex="0";t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button");t.ariaHasPopup="true";this.#b&&(t.ariaControls=`${this.#b.id}_colorpicker_dropdown`);const e=this.#P._signal;t.addEventListener("click",this.#Hr.bind(this),{signal:e});t.addEventListener("keydown",this.#zr.bind(this),{signal:e});const i=this.#Ir=document.createElement("span");i.className="swatch";i.ariaHidden="true";i.style.backgroundColor=this.#Fr;t.append(i);return t}renderMainDropdown(){const t=this.#Rr=this.#Gr();t.ariaOrientation="horizontal";t.ariaLabelledBy="highlightColorPickerLabel";return t}#Gr(){const t=document.createElement("div"),e=this.#P._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.className="dropdown";t.role="listbox";t.ariaMultiSelectable="false";t.ariaOrientation="vertical";t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");this.#b&&(t.id=`${this.#b.id}_colorpicker_dropdown`);for(const[i,n]of this.#P.highlightColors){const s=document.createElement("button");s.tabIndex="0";s.role="option";s.setAttribute("data-color",n);s.title=i;s.setAttribute("data-l10n-id",ColorPicker.#Ur[i]);const r=document.createElement("span");s.append(r);r.className="swatch";r.style.backgroundColor=n;s.ariaSelected=n===this.#Fr;s.addEventListener("click",this.#Wr.bind(this,n),{signal:e});t.append(s)}t.addEventListener("keydown",this.#zr.bind(this),{signal:e});return t}#Wr(t,e){e.stopPropagation();this.#Or.dispatch("switchannotationeditorparams",{source:this,type:g.HIGHLIGHT_COLOR,value:t});this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#kr){this.#Hr(t);return}const e=t.target.getAttribute("data-color");e&&this.#Wr(e,t)}_moveToNext(t){this.#Vr?t.target!==this.#kr?t.target.nextSibling?.focus():this.#Rr.firstElementChild?.focus():this.#Hr(t)}_moveToPrevious(t){if(t.target!==this.#Rr?.firstElementChild&&t.target!==this.#kr){this.#Vr||this.#Hr(t);t.target.previousSibling?.focus()}else this.#Vr&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Vr?this.#Rr.firstElementChild?.focus():this.#Hr(t)}_moveToEnd(t){this.#Vr?this.#Rr.lastElementChild?.focus():this.#Hr(t)}#zr(t){ColorPicker._keyboardManager.exec(this,t)}#Hr(t){if(this.#Vr){this.hideDropdown();return}this.#Br=0===t.detail;if(!this.#Nr){this.#Nr=new AbortController;window.addEventListener("pointerdown",this.#C.bind(this),{signal:this.#P.combinedSignal(this.#Nr)})}this.#kr.ariaExpanded="true";if(this.#Rr){this.#Rr.classList.remove("hidden");return}const e=this.#Rr=this.#Gr();this.#kr.append(e)}#C(t){this.#Rr?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#Rr?.classList.add("hidden");this.#kr.ariaExpanded="false";this.#Nr?.abort();this.#Nr=null}get#Vr(){return this.#Rr&&!this.#Rr.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#Lr)if(this.#Vr){this.hideDropdown();this.#kr.focus({preventScroll:!0,focusVisible:this.#Br})}else this.#b?.unselect()}updateColor(t){this.#Ir&&(this.#Ir.style.backgroundColor=t);if(!this.#Rr)return;const e=this.#P.highlightColors.values();for(const i of this.#Rr.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#kr?.remove();this.#kr=null;this.#Ir=null;this.#Rr?.remove();this.#Rr=null}}class BasicColorPicker{#jr=null;#b=null;#P=null;static#Ur=null;constructor(t){this.#b=t;this.#P=t._uiManager;BasicColorPicker.#Ur||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#jr)return this.#jr;const{editorType:t,colorType:e,color:i}=this.#b,n=this.#jr=document.createElement("input");n.type="color";n.value=i||"#000000";n.className="basicColorPicker";n.tabIndex=0;n.setAttribute("data-l10n-id",BasicColorPicker.#Ur[t]);n.addEventListener("input",()=>{this.#P.updateParams(e,n.value)},{signal:this.#P._signal});return n}update(t){this.#jr&&(this.#jr.value=t)}destroy(){this.#jr?.remove();this.#jr=null}hideDropdown(){}}function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,n]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+n)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,n]){return["RGB",1-Math.min(1,t+n),1-Math.min(1,i+n),1-Math.min(1,e+n)]}static CMYK_rgb([t,e,i,n]){return[scaleAndClamp(1-Math.min(1,t+n)),scaleAndClamp(1-Math.min(1,i+n)),scaleAndClamp(1-Math.min(1,e+n))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const n=1-t,s=1-e,r=1-i;return["CMYK",n,s,r,Math.min(n,s,r)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const n=this._createSVG("svg:svg");n.setAttribute("version","1.1");if(!i){n.setAttribute("width",`${t}px`);n.setAttribute("height",`${e}px`)}n.setAttribute("preserveAspectRatio","none");n.setAttribute("viewBox",`0 0 ${t} ${e}`);return n}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(j,t)}}const Ot=new WeakSet,Nt=60*(new Date).getTimezoneOffset()*1e3;class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case S.LINK:return new LinkAnnotationElement(t);case S.TEXT:return new TextAnnotationElement(t);case S.WIDGET:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case S.POPUP:return new PopupAnnotationElement(t);case S.FREETEXT:return new FreeTextAnnotationElement(t);case S.LINE:return new LineAnnotationElement(t);case S.SQUARE:return new SquareAnnotationElement(t);case S.CIRCLE:return new CircleAnnotationElement(t);case S.POLYLINE:return new PolylineAnnotationElement(t);case S.CARET:return new CaretAnnotationElement(t);case S.INK:return new InkAnnotationElement(t);case S.POLYGON:return new PolygonAnnotationElement(t);case S.HIGHLIGHT:return new HighlightAnnotationElement(t);case S.UNDERLINE:return new UnderlineAnnotationElement(t);case S.SQUIGGLY:return new SquigglyAnnotationElement(t);case S.STRIKEOUT:return new StrikeOutAnnotationElement(t);case S.STAMP:return new StampAnnotationElement(t);case S.FILEATTACHMENT:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#$r=null;#Xr=!1;#qr=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:n=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableComment=t.enableComment;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;this.hasOwnCommentButton=!1;e&&(this.contentElement=this.container=this._createContainer(i));n&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:i,rect:n}=this.data;let s=-1/0,r=-1/0;if(e?.length>=8){for(let t=0;tr){r=e[t+1];s=e[t+2]}else e[t+1]===r&&(s=Math.max(s,e[t+2]));return[s,r]}if(i?.length>=1){for(const t of i)for(let e=0,i=t.length;er){r=t[e+1];s=t[e]}else t[e+1]===r&&(s=Math.max(s,t[e]));if(s!==1/0)return[s,r]}return n?[n[2],n[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:r}}}=this.parent;t[1]=e[3]-t[1]+e[1];t[0]=100*(t[0]-s)/i;t[1]=100*(t[1]-r)/n;return t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${u}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,i={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:i})||this.annotationStorage.setValue(`${u}${e.id}`,{id:e.id,annotationType:e.annotationType,page:this.parent.page,popup:i,popupRef:e.popupRef,modificationDate:new Date});t||this.removePopup()}removePopup(){(this.#qr?.popup||this.popup)?.remove();this.#qr=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#$r||={rect:this.data.rect.slice(0)});const{rect:e,popup:i}=t;e&&this.#Kr(e);let n=this.#qr?.popup||this.popup;if(!n&&i?.text){this._createPopup(i);n=this.#qr.popup}if(n){n.updateEdited(t);if(i?.deleted){n.remove();this.#qr=null;this.popup=null}}}resetEdited(){if(this.#$r){this.#Kr(this.#$r.rect);this.#qr?.popup.resetEdited();this.#$r=null}}#Kr(t){const{container:{style:e},data:{rect:i,rotation:n},parent:{viewport:{rawDims:{pageWidth:s,pageHeight:r,pageX:a,pageY:o}}}}=this;i?.splice(0,4,...t);e.left=100*(t[0]-a)/s+"%";e.top=100*(r-t[3]+o)/r+"%";if(0===n){e.width=100*(t[2]-t[0])/s+"%";e.height=100*(t[3]-t[1])/r+"%"}else this.setRotation(n)}_createContainer(t){const{data:e,parent:{page:i,viewport:n}}=this,s=document.createElement("section");s.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||this instanceof LinkAnnotationElement||(s.tabIndex=0);const{style:r}=s;r.zIndex=this.parent.zIndex;this.parent.zIndex+=2;e.alternativeText&&(s.title=e.alternativeText);e.noRotate&&s.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,s);return s}const{width:a,height:o}=this;if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;r.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${a}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;r.borderRadius=t}switch(e.borderStyle.style){case T:r.borderStyle="solid";break;case _:r.borderStyle="dashed";break;case D:warn("Unimplemented border style: beveled");break;case P:warn("Unimplemented border style: inset");break;case M:r.borderBottomStyle="solid"}const n=e.borderColor||null;if(n){this.#Xr=!0;r.borderColor=Util.makeHexColor(0|n[0],0|n[1],0|n[2])}else r.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=n.rawDims;r.left=100*(l[0]-c)/h+"%";r.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){r.width=100*a/h+"%";r.height=100*o/d+"%"}else this.setRotation(p,s);return s}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:n}=this.parent.viewport.rawDims;let{width:s,height:r}=this;t%180!=0&&([s,r]=[r,s]);e.style.width=100*s/i+"%";e.style.height=100*r/n+"%";e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const n=i.detail[t],s=n[0],r=n.slice(1);i.target.style[e]=ColorConverters[`${s}_HTML`](r);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${s}_rgb`](r)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const n of Object.keys(e.detail)){const s=t[n]||i[n];s?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[n,s]of Object.entries(e)){const r=i[n];if(r){r({detail:{[n]:s},target:t});delete e[n]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,n,s]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[r,a,o,l]=t.subarray(2,6);if(n===r&&s===a&&e===o&&i===l)return}const{style:r}=this.container;let a;if(this.#Xr){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0;a=["url('data:image/svg+xml;utf8,",'',``];this.container.classList.add("hasBorder")}const o=n-e,l=s-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);d.role="none";const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");c.append(u);for(let i=2,n=t.length;i`)}if(this.#Xr){a.push("')");r.backgroundImage=a.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:e}=this;let i,n;if(t){i={str:t.text};n=t.date}else{i=e.contentsObj;n=e.modificationDate}this.#qr=new PopupAnnotationElement({data:{color:e.color,titleObj:e.titleObj,modificationDate:n,contentsObj:i,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#qr||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#qr}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const n=this._fieldObjects[t];if(n)for(const{page:t,id:s,exportValues:r}of n){if(-1===t)continue;if(s===e)continue;const n="string"==typeof r?r:null,a=document.querySelector(`[data-element-id="${s}"]`);!a||Ot.has(a)?i.push({id:s,exportValue:n,domElement:a}):warn(`_getElementsByName - element not allowed: ${s}`)}return i}for(const n of document.getElementsByName(t)){const{exportValue:t}=n,s=n.getAttribute("data-element-id");s!==e&&(Ot.has(n)&&i.push({id:s,exportValue:t,domElement:n}))}return i}show(){this.container&&(this.container.hidden=!1);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class EditorAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.editor=t.editor}render(){this.container.className="editorAnnotation";return 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 LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let n=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);n=!0}else if(t.action){this._bindNamedAction(i,t.action,t.overlaidText);n=!0}else if(t.attachment){this.#Yr(i,t.attachment,t.overlaidText,t.attachmentDest);n=!0}else if(t.setOCGState){this.#Qr(i,t.setOCGState,t.overlaidText);n=!0}else if(t.dest){this._bindLink(i,t.dest,t.overlaidText);n=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);n=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);n=!0}else if(this.isTooltipOnly&&!n){this._bindLink(i,"");n=!0}}this.container.classList.add("linkAnnotation");if(n){this.contentElement=i;this.container.append(i)}return this.container}#Jr(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,i=""){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#Jr();i&&(t.title=i)}_bindNamedAction(t,e,i=""){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};i&&(t.title=i);this.#Jr()}#Yr(t,e,i="",n=null){t.href=this.linkService.getAnchorUrl("");e.description?t.title=e.description:i&&(t.title=i);t.onclick=()=>{this.downloadManager?.openOrDownloadData(e.content,e.filename,n);return!1};this.#Jr()}#Qr(t,e,i=""){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};i&&(t.title=i);this.#Jr()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(e.actions)){const s=i.get(n);s&&(t[s]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:n}});return!1})}e.overlaidText&&(t.title=e.overlaidText);t.onclick||(t.onclick=()=>!1);this.#Jr()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#Jr();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:n,include:s}=e,r=[];if(0!==t.length||0!==n.length){const e=new Set(n);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===s&&r.push(i)}else for(const t of Object.values(this._fieldObjects))r.push(...t);const a=this.annotationStorage,o=[];for(const t of r){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;a.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Ot.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,n,s){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(i,t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t)}})})}_setEventListeners(t,e,i,n){for(const[s,r]of i)if("Action"===r||this.data.actions?.[r]){"Focus"!==r&&"Blur"!==r||(e||={focused:!1});this._setEventListener(t,e,s,r,n);"Focus"!==r||this.data.actions?.Blur?"Blur"!==r||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:n}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,r=t.style;let a;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(i*s))||1);a=Math.min(s,roundToOneDecimal(e/i))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(s,roundToOneDecimal(t/i))}r.fontSize=`calc(${a}px * var(--total-scale-factor))`;r.color=Util.makeHexColor(n[0],n[1],n[2]);null!==this.data.textAlignment&&(r.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,n){const s=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id)){r.domElement&&(r.domElement[e]=i);s.setValue(r.id,{[n]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const n=t.getValue(e,{value:this.data.fieldValue});let s=n.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&s.length>r&&(s=s.slice(0,r));let a=n.formattedValue||this.data.textContent?.join("\n")||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const o={userValue:s,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=a??s;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type=this.data.password?"password":"text";i.setAttribute("value",a??s);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);Ot.add(i);this.contentElement=i;i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=0;const{datetimeFormat:l,datetimeType:h,timeStep:d}=this.data,c=!!h&&this.enableScripting;l&&(i.title=l);this._setRequired(i,this.data.required);r&&(i.maxLength=r);i.addEventListener("input",n=>{t.setValue(e,{value:n.target.value});this.setPropertyOnSiblings(i,"value",n.target.value,"value");o.formattedValue=null});i.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e;o.formattedValue=null});let blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",t=>{if(o.focused)return;const{target:e}=t;if(c){e.type=h;d&&(e.step=d)}if(o.userValue){const t=o.userValue;if(c)if("time"===h){const i=new Date(t),n=[i.getHours(),i.getMinutes(),i.getSeconds()];e.value=n.map(t=>t.toString().padStart(2,"0")).join(":")}else e.value=new Date(t-Nt).toISOString().split("date"===h?"T":".",1)[0];else e.value=t}o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=!0)});i.addEventListener("updatefromsandbox",i=>{this.showElementAndHideCanvas(i.target);const n={value(i){o.userValue=i.detail.value??"";c||t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:n}=i.detail;o.formattedValue=n;null!=n&&i.target!==document.activeElement&&(i.target.value=n);const s={formattedValue:n};c&&(s.value=n);t.setValue(e,s)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:n}=i.detail,{target:s}=i;if(0===n){s.removeAttribute("maxLength");return}s.setAttribute("maxLength",n);let r=o.userValue;if(r&&!(r.length<=n)){r=r.slice(0,n);s.value=o.userValue=r;t.setValue(e,{value:r});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,willCommit:!0,commitKey:1,selStart:s.selectionStart,selEnd:s.selectionEnd}})}}};this._dispatchEventFromSandbox(n,i)});i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:n}=t.target;if(o.lastCommittedValue!==n){o.lastCommittedValue=n;o.userValue=n;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}});const n=blurListener;blurListener=null;i.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{target:i}=t;let{value:s}=i;if(c){if(s&&"time"===h){const t=s.split(":").map(t=>parseInt(t,10));s=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf();i.step=""}else{s.includes("T")||(s=`${s}T00:00`);s=new Date(s).valueOf()}i.type="text"}o.userValue=s;o.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});n(t)});this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;const{data:i,target:n}=t,{value:s,selectionStart:r,selectionEnd:a}=n;let l=r,h=a;switch(t.inputType){case"deleteWordBackward":{const t=s.substring(0,r).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=s.substring(r).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":r===a&&(l-=1);break;case"deleteContentForward":r===a&&(h+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,change:i||"",willCommit:!1,selStart:l,selEnd:h}})});this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/r;i.classList.add("comb");i.style.letterSpacing=`calc(${t}px * var(--total-scale-factor) - 1ch)`}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof n){n="Off"!==n;t.setValue(i,{value:n})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const s=document.createElement("input");Ot.add(s);s.setAttribute("data-element-id",i);s.disabled=e.readOnly;this._setRequired(s,this.data.required);s.type="checkbox";s.name=e.fieldName;n&&s.setAttribute("checked",!0);s.setAttribute("exportValue",e.exportValue);s.tabIndex=0;s.addEventListener("change",n=>{const{name:s,checked:r}=n.target;for(const n of this._getElementsByName(s,i)){const i=r&&n.exportValue===e.exportValue;n.domElement&&(n.domElement.checked=i);t.setValue(n.id,{value:i})}t.setValue(i,{value:r})});s.addEventListener("resetform",t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue});if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",e=>{const n={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(n,e)});this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof n){n=n!==e.buttonValue;t.setValue(i,{value:n})}if(n)for(const n of this._getElementsByName(e.fieldName,i))t.setValue(n.id,{value:!1});const s=document.createElement("input");Ot.add(s);s.setAttribute("data-element-id",i);s.disabled=e.readOnly;this._setRequired(s,this.data.required);s.type="radio";s.name=e.fieldName;n&&s.setAttribute("checked",!0);s.tabIndex=0;s.addEventListener("change",e=>{const{name:n,checked:s}=e.target;for(const e of this._getElementsByName(n,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:s})});s.addEventListener("resetform",t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue});if(this.enableScripting&&this.hasJSActions){const n=e.buttonValue;s.addEventListener("updatefromsandbox",e=>{const s={value:e=>{const s=n===e.detail.value;for(const n of this._getElementsByName(e.target.name)){const e=s&&n.id===i;n.domElement&&(n.domElement.checked=e);t.setValue(n.id,{value:e})}}};this._dispatchEventFromSandbox(s,e)});this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),n=document.createElement("select");Ot.add(n);n.setAttribute("data-element-id",e);n.disabled=this.data.readOnly;this._setRequired(n,this.data.required);n.name=this.data.fieldName;n.tabIndex=0;let s=this.data.combo&&this.data.options.length>0;if(!this.data.combo){n.size=this.data.options.length;this.data.multiSelect&&(n.multiple=!0)}n.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue;for(const t of n.options)t.selected=t.value===e});for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);s=!1}n.append(e)}let r=null;if(s){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);n.prepend(t);r=()=>{t.remove();n.removeEventListener("input",r);r=null};n.addEventListener("input",r)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:s}=n;return s?Array.prototype.filter.call(i,t=>t.selected).map(t=>t[e]):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let a=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.textContent,exportValue:t.value}))};if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",i=>{const s={value(i){r?.();const s=i.detail.value,o=new Set(Array.isArray(s)?s:[s]);for(const t of n.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});a=getValue(!1)},multipleSelection(t){n.multiple=!0},remove(i){const s=n.options,r=i.detail.remove;s[r].selected=!1;n.remove(r);if(s.length>0){-1===Array.prototype.findIndex.call(s,t=>t.selected)&&(s[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},clear(i){for(;0!==n.length;)n.remove(0);t.setValue(e,{value:null,items:[]});a=getValue(!1)},insert(i){const{index:s,displayValue:r,exportValue:o}=i.detail.insert,l=n.children[s],h=document.createElement("option");h.textContent=r;h.value=o;l?l.before(h):n.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},items(i){const{items:s}=i.detail;for(;0!==n.length;)n.remove(0);for(const t of s){const{displayValue:e,exportValue:i}=t,s=document.createElement("option");s.textContent=e;s.value=i;n.append(s)}n.options.length>0&&(n.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},indices(i){const n=new Set(i.detail.indices);for(const t of i.target.options)t.selected=n.has(t.index);t.setValue(e,{value:getValue(!0)});a=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(s,i)});n.addEventListener("input",i=>{const n=getValue(!0),s=getValue(!1);t.setValue(e,{value:n});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,change:s,changeEx:n,willCommit:!1,commitKey:1,keyDown:!1}})});this._setEventListeners(n,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],t=>t.target.value)}else n.addEventListener("input",function(i){t.setValue(e,{value:getValue(!0)})});this.data.combo&&this._setTextStyle(n);this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i,parent:n}=t,s=!!n._commentManager;super(t,{isRenderable:!s&&AnnotationElement._hasPopupData(e)});this.elements=i;if(s&&AnnotationElement._hasPopupData(e)){const t=this.popup=this.#Zr();for(const e of i)e.popup=t}else this.popup=null}#Zr(){return new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){const{container:t}=this;t.classList.add("popupAnnotation");t.role="comment";const e=this.popup=this.#Zr(),i=[];for(const t of this.elements){t.popup=e;t.container.ariaHasPopup="dialog";i.push(t.data.id);t.addHighlightArea()}this.container.setAttribute("aria-controls",i.map(t=>`${V}${t}`).join(","));return this.container}}class PopupElement{#et=null;#ta=this.#zr.bind(this);#ea=this.#ia.bind(this);#na=this.#sa.bind(this);#ra=this.#aa.bind(this);#oa=null;#Ot=null;#la=null;#ha=null;#da=null;#ca=null;#ua=null;#pa=!1;#ga=null;#ma=null;#V=null;#fa=null;#ba=null;#Me=null;#wa=null;#Te=null;#ya=null;#$r=null;#Aa=!1;#va=null;#xa=null;constructor({container:t,color:e,elements:i,titleObj:n,modificationDate:s,contentsObj:r,richText:a,parent:o,rect:l,parentRect:h,open:d,commentManager:c=null}){this.#Ot=t;this.#ya=n;this.#la=r;this.#Te=a;this.#ca=o;this.#oa=e;this.#wa=l;this.#ua=h;this.#da=i;this.#et=c;this.#va=i[0];this.#ha=PDFDateString.toDateObject(s);this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup());if(!c){this.#Ea();this.#Ot.hidden=!0;d&&this.#aa()}}#Ea(){if(this.#ma)return;this.#ma=new AbortController;const{signal:t}=this.#ma;for(const e of this.trigger){e.addEventListener("click",this.#ra,{signal:t});e.addEventListener("pointerenter",this.#na,{signal:t});e.addEventListener("pointerleave",this.#ea,{signal:t});e.classList.add("popupTriggerArea")}for(const e of this.#da)e.container?.addEventListener("keydown",this.#ta,{signal:t})}#Ca(){const t=this.#da.find(t=>t.hasCommentButton);t&&(this.#ba=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#fa){this.#fa.parentNode||this.#va.container.after(this.#fa);return}this.#ba||this.#Ca();if(!this.#ba)return;const{signal:t}=this.#ma=new AbortController,e=this.#va.hasOwnCommentButton,togglePopup=()=>{this.#et.toggleCommentPopup(this,!0,void 0,!e)},showPopup=()=>{this.#et.toggleCommentPopup(this,!1,!0,!e)},hidePopup=()=>{this.#et.toggleCommentPopup(this,!1,!1)};if(e){this.#fa=this.#va.container;for(const e of this.trigger){e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.addEventListener("keydown",this.#ta,{signal:t});e.addEventListener("click",togglePopup,{signal:t});e.addEventListener("pointerenter",showPopup,{signal:t});e.addEventListener("pointerleave",hidePopup,{signal:t});e.classList.add("popupTriggerArea")}}else{const e=this.#fa=document.createElement("button");e.className="annotationCommentButton";const i=this.#va.container;e.style.zIndex=i.style.zIndex+1;e.tabIndex=0;e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.setAttribute("data-l10n-id","pdfjs-show-comment-button");this.#Sa();this.#Ta();e.addEventListener("keydown",this.#ta,{signal:t});e.addEventListener("click",togglePopup,{signal:t});e.addEventListener("pointerenter",showPopup,{signal:t});e.addEventListener("pointerleave",hidePopup,{signal:t});i.after(e)}}#Ta(){if(this.#va.extraPopupElement&&!this.#va.editor)return;this.#fa||this.renderCommentButton();const[t,e]=this.#ba,{style:i}=this.#fa;i.left=`calc(${t}%)`;i.top=`calc(${e}% - var(--comment-button-dim))`}#Sa(){if(!this.#va.extraPopupElement){this.#fa||this.renderCommentButton();this.#fa.style.backgroundColor=this.commentButtonColor||""}}get commentButtonColor(){const{color:t,opacity:e}=this.#va.commentData;return t?this.#ca._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#fa?.focus()},0)}getData(){const{richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}=this.#va.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}}get elementBeforePopup(){return this.#fa}get comment(){this.#xa||=this.#va.commentText;return this.#xa}set comment(t){t!==this.comment&&(this.#va.commentText=this.#xa=t)}focus(){this.#va.container?.focus()}get parentBoundingClientRect(){return this.#va.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#fa){this.#fa.classList.toggle("selected",t);this.#fa.ariaExpanded=e}}setSelectedCommentButton(t){this.#fa.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#Me)return this.#Me;const{x:t,y:e,height:i}=this.#fa.getBoundingClientRect(),{x:n,y:s,width:r,height:a}=this.#va.layer.getBoundingClientRect();return[(t-n)/r,(e+i-s)/a]}set commentPopupPosition(t){this.#Me=t}hasDefaultPopupPosition(){return null===this.#Me}get commentButtonPosition(){return this.#ba}get commentButtonWidth(){return this.#fa.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,i]=this.#Me||this.commentButtonPosition.map(t=>t/100),n=this.parentBoundingClientRect,{x:s,y:r,width:a,height:o}=n;this.#et.showDialog(null,this,s+e*a,r+i*o,{...t,parentDimensions:n})}render(){if(this.#ga)return;const t=this.#ga=document.createElement("div");t.className="popup";if(this.#oa){const e=t.style.outlineColor=Util.makeHexColor(...this.#oa);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");e.className="header";if(this.#ya?.str){const t=document.createElement("span");t.className="title";e.append(t);({dir:t.dir,str:t.textContent}=this.#ya)}t.append(e);if(this.#ha){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.#ha.valueOf()}));t.dateTime=this.#ha.toISOString();e.append(t)}renderRichText({html:this.#_a||this.#la.str,dir:this.#la?.dir,className:"popupContent"},t);this.#Ot.append(t)}get#_a(){const t=this.#Te,e=this.#la;return!t?.str||e?.str&&e.str!==t.str?null:this.#Te.html||null}get#Da(){return this.#_a?.attributes?.style?.fontSize||0}get#Pa(){return this.#_a?.attributes?.style?.color||null}#Ma(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},n={style:{color:this.#Pa,fontSize:this.#Da?`calc(${this.#Da}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:n});return i}#zr(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#pa)&&this.#aa()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#et){if(i){this.remove();this.#xa=null}else if(e)if(e.deleted)this.remove();else{this.#Sa();this.#xa=e.text}if(t){this.#ba=null;this.#Ca();this.#Ta()}}else if(i||e?.deleted)this.remove();else{this.#Ea();this.#$r||={contentsObj:this.#la,richText:this.#Te};t&&(this.#V=null);if(e&&e.text){this.#Te=this.#Ma(e.text);this.#ha=PDFDateString.toDateObject(e.date);this.#la=null}this.#ga?.remove();this.#ga=null}}resetEdited(){if(this.#$r){({contentsObj:this.#la,richText:this.#Te}=this.#$r);this.#$r=null;this.#ga?.remove();this.#ga=null;this.#V=null}}remove(){this.#ma?.abort();this.#ma=null;this.#ga?.remove();this.#ga=null;this.#Aa=!1;this.#pa=!1;this.#fa?.remove();this.#fa=null;if(this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#ka(){if(null!==this.#V)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:n,pageY:s}}}=this.#ca;let r=!!this.#ua,a=r?this.#ua:this.#wa;for(const t of this.#da)if(!a||null!==Util.intersect(t.data.rect,a)){a=t.data.rect;r=!0;break}const o=Util.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),l=r?a[2]-a[0]+5:0,h=o[0]+l,d=o[1];this.#V=[100*(h-n)/e,100*(d-s)/i];const{style:c}=this.#Ot;c.left=`${this.#V[0]}%`;c.top=`${this.#V[1]}%`}#aa(){if(this.#et)this.#et.toggleCommentPopup(this,!1);else{this.#pa=!this.#pa;if(this.#pa){this.#sa();this.#Ot.addEventListener("click",this.#ra);this.#Ot.addEventListener("keydown",this.#ta)}else{this.#ia();this.#Ot.removeEventListener("click",this.#ra);this.#Ot.removeEventListener("keydown",this.#ta)}}}#sa(){this.#ga||this.render();if(this.isVisible)this.#pa&&this.#Ot.classList.add("focused");else{this.#ka();this.#Ot.hidden=!1;this.#Ot.style.zIndex=parseInt(this.#Ot.style.zIndex)+1e3}}#ia(){this.#Ot.classList.remove("focused");if(!this.#pa&&this.isVisible){this.#Ot.hidden=!0;this.#Ot.style.zIndex=parseInt(this.#Ot.style.zIndex)-1e3}}forceHide(){this.#Aa=this.isVisible;this.#Aa&&(this.#Ot.hidden=!0)}maybeShow(){if(!this.#et){this.#Ea();if(this.#Aa){this.#ga||this.#sa();this.#Aa=!1;this.#Ot.hidden=!1}}}get isVisible(){return!this.#et&&!1===this.#Ot.hidden}}class FreeTextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.textContent=t.data.textContent;this.textPosition=t.data.textPosition;this.annotationEditorType=p.FREETEXT}render(){this.container.classList.add("freeTextAnnotation");if(this.textContent){const t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent");t.setAttribute("role","comment");for(const e of this.textContent){const i=document.createElement("span");i.textContent=e;t.append(i)}this.container.append(t)}if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this._editOnDoubleClick();return this.container}}class LineAnnotationElement extends AnnotationElement{#Ia=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=this.#Ia=this.svgFactory.createElement("svg:line");s.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]);s.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]);s.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]);s.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]);s.setAttribute("stroke-width",t.borderStyle.width||1);s.setAttribute("stroke","transparent");s.setAttribute("fill","transparent");n.append(s);this.container.append(n);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Ia}addHighlightArea(){this.container.classList.add("highlightArea")}}class SquareAnnotationElement extends AnnotationElement{#Fa=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,r=this.#Fa=this.svgFactory.createElement("svg:rect");r.setAttribute("x",s/2);r.setAttribute("y",s/2);r.setAttribute("width",e-s);r.setAttribute("height",i-s);r.setAttribute("stroke-width",s||1);r.setAttribute("stroke","transparent");r.setAttribute("fill","transparent");n.append(r);this.container.append(n);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Fa}addHighlightArea(){this.container.classList.add("highlightArea")}}class CircleAnnotationElement extends AnnotationElement{#Ra=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,r=this.#Ra=this.svgFactory.createElement("svg:ellipse");r.setAttribute("cx",e/2);r.setAttribute("cy",i/2);r.setAttribute("rx",e/2-s/2);r.setAttribute("ry",i/2-s/2);r.setAttribute("stroke-width",s||1);r.setAttribute("stroke","transparent");r.setAttribute("fill","transparent");n.append(r);this.container.append(n);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Ra}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolylineAnnotationElement extends AnnotationElement{#Ba=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="polylineAnnotation";this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:i,popupRef:n},width:s,height:r}=this;if(!e)return this.container;const a=this.svgFactory.create(s,r,!0);let o=[];for(let i=0,n=e.length;i=0&&s.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#Oa.length;t{"Enter"===t.key&&(n?t.metaKey:t.ctrlKey)&&this.#Ha()});if(!e.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}else i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#Ua}addHighlightArea(){this.container.classList.add("highlightArea")}#Ha(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#za=null;#Ga=null;#J=null;#Wa=new Map;#Va=null;#ja=null;#da=[];#$a=!1;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:n,page:s,viewport:r,structTreeLayer:a,commentManager:o,linkService:l,annotationStorage:h}){this.div=t;this.#za=e;this.#Ga=i;this.#Va=a||null;this.#ja=l||null;this.#J=h||new AnnotationStorage;this.page=s;this.viewport=r;this.zIndex=0;this._annotationEditorUIManager=n;this._commentManager=o||null}hasEditableAnnotations(){return this.#Wa.size>0}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const n=new Map,s=[],r={data:null,layer:i,linkService:this.#ja,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:this.#J,enableComment:!0===t.enableComment,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===S.POPUP;if(e){const e=n.get(t.id);if(!e)continue;if(!this._commentManager){s.push(t);continue}r.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;r.data=t;const i=AnnotationElementFactory.create(r);if(!i.isRenderable)continue;if(!e){this.#da.push(i);t.popupRef&&n.getOrInsertComputed(t.popupRef,makeArr).push(i)}const a=i.render();t.hidden&&(a.style.visibility="hidden");if(i._isEditable){this.#Wa.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}await this.#Xa();for(const t of s){const e=r.elements=n.get(t.id);r.data=t;const i=AnnotationElementFactory.create(r);if(!i.isRenderable)continue;const s=i.render();i.contentElement.id=`${V}${t.id}`;t.hidden&&(s.style.visibility="hidden");e.at(-1).container.after(s)}this.#qa()}async#Xa(){if(0===this.#da.length)return;this.div.replaceChildren();const t=[];if(!this.#$a){this.#$a=!0;for(const{contentElement:e,data:{id:i}}of this.#da){const n=e.id=`${V}${i}`;t.push(this.#Va?.getAriaAttributes(n).then(t=>{if(t)for(const[i,n]of t)e.setAttribute(i,n)}))}}this.#da.sort(({data:{rect:[t,e,i,n]}},{data:{rect:[s,r,a,o]}})=>{if(t===i&&e===n)return 1;if(s===a&&r===o)return-1;const l=(e+n)/2,h=(r+o)/2;if(l>=o&&h<=e)return-1;if(h>=n&&l<=r)return 1;return(t+i)/2-(s+a)/2});const e=document.createDocumentFragment();for(const t of this.#da){e.append(t.container);this._commentManager?(t.extraPopupElement?.popup||t.popup)?.renderCommentButton():t.extraPopupElement&&e.append(t.extraPopupElement.render())}this.div.append(e);await Promise.all(t);if(this.#za)for(const t of this.#da)this.#za.addPointerInTextLayer(t.contentElement,!1)}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#ja,svgFactory:new DOMSVGFactory,parent:this};for(const i of t){i.borderStyle||=AnnotationLayer._defaultBorderStyle;e.data=i;const t=AnnotationElementFactory.create(e);if(t.isRenderable){t.render();t.contentElement.id=`${V}${i.id}`;this.#da.push(t)}}await this.#Xa()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#qa();e.hidden=!1}#qa(){if(!this.#Ga)return;const t=this.div;for(const[e,i]of this.#Ga){const n=t.querySelector(`[data-annotation-id="${e}"]`);if(!n)continue;i.className="annotationContent";const{firstChild:s}=n;s?"CANVAS"===s.nodeName?s.replaceWith(i):s.classList.contains("annotationContent")?s.after(i):s.before(i):n.append(i);const r=this.#Wa.get(e);if(r)if(r._hasNoCanvas){this._annotationEditorUIManager?.setMissingCanvas(e,n.id,i);r._hasNoCanvas=!1}else r.canvas=i}this.#Ga.clear()}getEditableAnnotations(){return Array.from(this.#Wa.values())}getEditableAnnotation(t){return this.#Wa.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:i,rotation:n}=t,s=new EditorAnnotationElement({data:{id:i,rect:t.getPDFRect(),rotation:n},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#ja,annotationStorage:this.#J});s.render();s.contentElement.id=`${V}${i}`;s.createOrUpdatePopup();this.#da.push(s);return s}removeAnnotation(t){const e=this.#da.findIndex(e=>e.data.id===t);if(e<0)return;const[i]=this.#da.splice(e,1);this.#za?.removePointerInTextLayer(i.contentElement)}updateFakeAnnotations(t){if(0!==t.length){for(const e of t)e.updateFakeAnnotationElement(this);this.#Xa()}}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}static get _defaultBorderStyle(){return shadow(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:T,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const Ut=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#Ka="";#Ya=`${this.id}-editor`;#Qa=null;#Da;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=p.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.color=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#Da=t.fontSize||FreeTextEditor._defaultFontSize;this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert");this.canAddComment=!1}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case g.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case g.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case g.FREETEXT_SIZE:this.#Ja(e);break;case g.FREETEXT_COLOR:this.#Sa(e)}}static get defaultPropertiesToUpdate(){return[[g.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[g.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[g.FREETEXT_SIZE,this.#Da],[g.FREETEXT_COLOR,this.color]]}get toolbarButtons(){this._colorPicker||=new BasicColorPicker(this);return[["colorPicker",this._colorPicker]]}get colorType(){return g.FREETEXT_COLOR}#Ja(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`;this.translate(0,-(t-this.#Da)*this.parentScale);this.#Da=t;this.#Za()},e=this.#Da;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color;this._colorPicker?.update(this.color);super.onUpdatedColor()}#Sa(t){const setColor=t=>{this.color=t;this.onUpdatedColor()},e=this.color;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#Da)*t]}rebuild(){if(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.#Qa=new AbortController;const t=this._uiManager.combinedSignal(this.#Qa);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});return!0}disableEditMode(){if(!super.disableEditMode())return!1;this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#Ya);this._isDraggable=!0;this.#Qa?.abort();this.#Qa=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing");return!0}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#to(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#eo(i));e=i}return t.join("\n")}#Za(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,n=e.style.display,s=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=n;e.classList.toggle("hidden",s)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Ka,e=this.#Ka=this.#to().trimEnd();if(t===e)return;const setText=t=>{this.#Ka=t;if(t){this.#io();this._uiManager.rebuild(this);this.#Za()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#Za()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;if(this._isCopy||this.annotationElementId){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#Ya);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#Da}px * var(--total-scale-factor))`;i.color=this.color;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);if(this._isCopy||this.annotationElementId){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:s}=this._initialData;let[r,a]=this.getInitialTranslation();[r,a]=this.pageTranslationToScreen(r,a);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(s[0]-h)/o;u=e+this.height-(s[1]-d)/l;break;case 90:c=t+(s[0]-h)/o;u=e-(s[1]-d)/l;[r,a]=[a,-r];break;case 180:c=t-this.width+(s[0]-h)/o;u=e-(s[1]-d)/l;[r,a]=[-r,-a];break;case 270:c=t+(s[0]-h-this.height*l)/o;u=e+(s[1]-d-this.width*o)/l;[r,a]=[-a,r]}this.setAt(c*i,u*n,r,a)}else this._moveAfterPaste(t,e);this.#io();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#eo(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Ut,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const n=FreeTextEditor.#no(e.getData("text")||"").replaceAll(Ut,"\n");if(!n)return;const s=window.getSelection();if(!s.rangeCount)return;this.editorDiv.normalize();s.deleteFromDocument();const r=s.getRangeAt(0);if(!n.includes("\n")){r.insertNode(document.createTextNode(n));this.editorDiv.normalize();s.collapseToStart();return}const{startContainer:a,startOffset:o}=r,l=[],h=[];if(a.nodeType===Node.TEXT_NODE){const t=a.parentElement;h.push(a.nodeValue.slice(o).replaceAll(Ut,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#eo(i)):e=h}l.push(a.nodeValue.slice(0,o).replaceAll(Ut,""))}else if(a===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#eo(i))}}this.#Ka=`${l.join("\n")}${n}${h.join("\n")}`;this.#io();const d=new Range;let c=Math.sumPrecise(l.map(t=>t.length));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c);d.setEnd(t,c);break}c-=e}s.removeAllRanges();s.addRange(d)}#io(){this.editorDiv.replaceChildren();if(this.#Ka)for(const t of this.#Ka.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#so(){return this.#Ka.replaceAll(" "," ")}static#no(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=FreeTextEditor._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,i){let n=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:s,rotation:r,id:a,popupRef:o,richText:l,contentsObj:h,creationDate:d,modificationDate:c},textContent:u,textPosition:g,parent:{page:{pageNumber:m}}}=t;if(!u||0===u.length)return null;n=t={annotationType:p.FREETEXT,color:Array.from(i),fontSize:e,value:u.join("\n"),position:g,pageIndex:m-1,rect:s.slice(0),rotation:r,annotationElementId:a,id:a,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:d,modificationDate:c}}const s=await super.deserialize(t,e,i);s.#Da=t.fontSize;s.color=Util.makeHexColor(...t.color);s.#Ka=FreeTextEditor.#no(t.value);s._initialData=n;t.comment&&s.setCommentData(t);return s}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:e,fontSize:this.#Da,value:this.#so()});this.addComment(i);if(t){i.isCopy=!0;return i}if(this.annotationElementId&&!this.#ro(i))return null;i.id=this.annotationElementId;return i}#ro(t){const{value:e,fontSize:i,color:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==n[e])||t.pageIndex!==s}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:i}=e;i.fontSize=`calc(${this.#Da}px * var(--total-scale-factor))`;i.color=this.color;e.replaceChildren();for(const t of this.#Ka.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#Ka}});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,n,s,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#So(i);return i.join(" ")}#Eo(){const[t,e,i,n]=this.#ao,[s,r,a,o]=this.#xo();return`M${(this.#co[2]-t)/i} ${(this.#co[3]-e)/n} L${(this.#co[4]-t)/i} ${(this.#co[5]-e)/n} L${s} ${r} L${a} ${o} L${(this.#co[16]-t)/i} ${(this.#co[17]-e)/n} L${(this.#co[14]-t)/i} ${(this.#co[15]-e)/n} Z`}#So(t){const e=this.#oo;t.push(`L${e[4]} ${e[5]} Z`)}#Co(t){const[e,i,n,s]=this.#ao,r=this.#co.subarray(4,6),a=this.#co.subarray(16,18),[o,l,h,d]=this.#xo();t.push(`L${(r[0]-e)/n} ${(r[1]-i)/s} L${o} ${l} L${h} ${d} L${(a[0]-e)/n} ${(a[1]-i)/s}`)}newFreeDrawOutline(t,e,i,n,s,r){return new FreeDrawOutline(t,e,i,n,s,r)}getOutlines(){const t=this.#do,e=this.#oo,i=this.#co,[n,s,r,a]=this.#ao,o=new Float32Array((this.#wo?.length??0)+2);for(let t=0,e=o.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#Do(l,h);return this.newFreeDrawOutline(l,o,this.#ao,this.#fo,this.#lo,this.#ho)}#To(t){const e=this.#co,[i,n,s,r]=this.#ao,[a,o,l,h]=this.#xo(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/s,(e[3]-n)/r,NaN,NaN,NaN,NaN,(e[4]-i)/s,(e[5]-n)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/s,(e[17]-n)/r,NaN,NaN,NaN,NaN,(e[14]-i)/s,(e[15]-n)/r],0);return this.newFreeDrawOutline(d,t,this.#ao,this.#fo,this.#lo,this.#ho)}#Do(t,e){const i=this.#oo;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#_o(t,e){const i=this.#co.subarray(4,6),n=this.#co.subarray(16,18),[s,r,a,o]=this.#ao,[l,h,d,c]=this.#xo();t.set([NaN,NaN,NaN,NaN,(i[0]-s)/a,(i[1]-r)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(n[0]-s)/a,(n[1]-r)/o],e);return e+24}}class FreeDrawOutline extends Outline{#ao;#Po=new Float32Array(4);#lo;#ho;#wo;#fo;#Mo;constructor(t,e,i,n,s,r){super();this.#Mo=t;this.#wo=e;this.#ao=i;this.#fo=n;this.#lo=s;this.#ho=r;this.firstPoint=[NaN,NaN];this.lastPoint=[NaN,NaN];this.#ko(r);const[a,o,l,h]=this.#Po;for(let e=0,i=t.length;eu){r=c;a=u}else a===u&&(r=h(r,c));if(ld[1]){r=d[0];a=d[1]}else a===d[1]&&(r=h(r,d[0]));if(lt[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#Ro)if(e[3]){t.push(...this.#Lo(e));this.#Oo(e)}else{this.#No(e);t.push(...this.#Lo(e))}return this.#Uo(t)}#Uo(t){const e=[],i=new Set;for(const i of t){const[t,n,s]=i;e.push([t,n,i],[t,s,i])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,n=e.length;t0;){const t=i.values().next().value;let[e,r,a,o,l]=t;i.delete(t);let h=e,d=r;s=[e,a];n.push(s);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,r,a,o,l]=t;if(h!==e){s.push(h,d,e,d===r?r:a);h=e}d=d===r?a:r}s.push(h,d)}return new HighlightOutline(n,this.#ao,this.#Io,this.#Fo)}#Ho(t){const e=this.#Bo;let i=0,n=e.length-1;for(;i<=n;){const s=i+n>>1,r=e[s][0];if(r===t)return s;r=0;n--){const[i,s]=this.#Bo[n];if(i!==t)break;if(i===t&&s===e){this.#Bo.splice(n,1);return}}}#Lo(t){const[e,i,n]=t,s=[[e,i,n]],r=this.#Ho(n);for(let t=0;t=i)if(o>n)s[t][1]=n;else{if(1===r)return[];s.splice(t,1);t--;r--}else{s[t][2]=i;o>n&&s.push([e,n,o])}}}return s}}class HighlightOutline extends Outline{#ao;#zo;constructor(t,e,i,n){super();this.#zo=t;this.#ao=e;this.firstPoint=i;this.lastPoint=n}toSVGPath(){const t=[];for(const e of this.#zo){let[i,n]=e;t.push(`M${i} ${n}`);for(let s=2;s-1){this.#Qo=!0;this.#tl(t);this.#el()}else if(this.#Vo){this.#Go=t.anchorNode;this.#Wo=t.anchorOffset;this.#Xo=t.focusNode;this.#qo=t.focusOffset;this.#il();this.#el();this.rotate(this.rotation)}this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}get telemetryInitialData(){return{action:"added",type:this.#Qo?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#bo,methodOfCreation:this.#Zo}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#il(){const t=new HighlightOutliner(this.#Vo,.001);this.#Yo=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#Yo.box;const e=new HighlightOutliner(this.#Vo,.0025,.001,"ltr"===this._uiManager.direction);this.#$o=e.getOutlines();const{firstPoint:i}=this.#Yo;this.#Io=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];const{lastPoint:n}=this.#$o;this.#Fo=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height]}#tl({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#Yo=t;this.#$o=t.getNewOutline(this.#bo/2+1.5,.0025);if(e>=0){this.#O=e;this.#jo=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Jo=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#$o.box,path:{d:this.#$o.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#O,{bbox:HighlightEditor.#nl(this.#Yo.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Jo,{bbox:HighlightEditor.#nl(this.#$o.box,e),path:{d:this.#$o.toSVGPath()}})}const[n,s,r,a]=t.box;switch(this.rotation){case 0:this.x=n;this.y=s;this.width=r;this.height=a;break;case 90:{const[t,e]=this.parentDimensions;this.x=s;this.y=1-n;this.width=r*e/t;this.height=a*t/e;break}case 180:this.x=1-n;this.y=1-s;this.width=r;this.height=a;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-s;this.y=n;this.width=r*e/t;this.height=a*t/e;break}}const{firstPoint:o}=t;this.#Io=[(o[0]-n)/r,(o[1]-s)/a];const{lastPoint:l}=this.#$o;this.#Fo=[(l[0]-n)/r,(l[1]-s)/a]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case g.HIGHLIGHT_COLOR:HighlightEditor._defaultColor=e;break;case g.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Fo}get commentButtonPosition(){return this.#Io}updateParams(t,e){switch(t){case g.HIGHLIGHT_COLOR:this.#Sa(e);break;case g.HIGHLIGHT_THICKNESS:this.#sl(e)}}static get defaultPropertiesToUpdate(){return[[g.HIGHLIGHT_COLOR,HighlightEditor._defaultColor],[g.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[g.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[g.HIGHLIGHT_THICKNESS,this.#bo||HighlightEditor._defaultThickness],[g.HIGHLIGHT_FREE,this.#Qo]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#O,{root:{fill:this.color,"fill-opacity":this.opacity}});this.#f?.updateColor(this.color);super.onUpdatedColor()}#Sa(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.opacity=e;this.onUpdatedColor()},e=this.color,i=this.opacity;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#sl(t){const e=this.#bo,setThickness=t=>{this.#bo=t;this.#rl(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){if(this._uiManager.highlightColors){return[["colorPicker",this.#f=new ColorPicker({editor:this})]]}return super.toolbarButtons}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#al())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#al())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#ol();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#el();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#ol();else if(t){this.#el(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#rl(t){if(this.#Qo){this.#tl({highlightOutlines:this.#Yo.getNewOutline(t/2)});this.fixAndSetPosition();this.setDims()}}#ol(){if(null!==this.#O&&this.parent){this.parent.drawLayer.remove(this.#O);this.#O=null;this.parent.drawLayer.remove(this.#Jo);this.#Jo=null}}#el(t=this.parent){if(null===this.#O){({id:this.#O,clipPathId:this.#jo}=t.drawLayer.draw({bbox:this.#Yo.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#Qo},path:{d:this.#Yo.toSVGPath()}},!1,!0));this.#Jo=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Qo},bbox:this.#$o.box,path:{d:this.#$o.toSVGPath()}},this.#Qo);this.#Ko&&(this.#Ko.style.clipPath=this.#jo)}}static#nl([t,e,i,n],s){switch(s){case 90:return[1-e-n,t,n,i];case 180:return[1-t-i,1-e-n,i,n];case 270:return[e,1-t-i,n,i]}return[t,e,i,n]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Qo){t=(t-this.rotation+360)%360;i=HighlightEditor.#nl(this.#Yo.box,t)}else i=HighlightEditor.#nl([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#O,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Jo,{bbox:HighlightEditor.#nl(this.#$o.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#_e){t.setAttribute("aria-label",this.#_e);t.setAttribute("role","mark")}this.#Qo?t.classList.add("free"):this.div.addEventListener("keydown",this.#ll.bind(this),{signal:this._uiManager._signal});const e=this.#Ko=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#jo;this.setDims();bindEvents(this,this.#Ko,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Jo,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Jo,{rootClass:{hovered:!1}})}#ll(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#hl(!0);break;case 1:case 3:this.#hl(!1)}}#hl(t){if(!this.#Go)return;const e=window.getSelection();t?e.setPosition(this.#Go,this.#Wo):e.setPosition(this.#Xo,this.#qo)}select(){super.select();this.#Jo&&this.parent?.drawLayer.updateProperties(this.#Jo,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Jo){this.parent?.drawLayer.updateProperties(this.#Jo,{rootClass:{selected:!1}});this.#Qo||this.#hl(!1)}}get _mustFixPosition(){return!this.#Qo}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#O,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Jo,{rootClass:{hidden:!t}})}}#al(){return this.#Qo?this.rotation:0}#dl(){if(this.#Qo)return null;const[t,e]=this.pageDimensions,[i,n]=this.pageTranslation,s=this.#Vo,r=new Float32Array(8*s.length);let a=0;for(const{x:o,y:l,width:h,height:d}of s){const s=o*t+i,c=(1-l)*e+n;r[a]=r[a+4]=s;r[a+1]=r[a+3]=c;r[a+2]=r[a+6]=s+h*t;r[a+5]=r[a+7]=c-d*e;a+=8}return r}#cl(t){return this.#Yo.serialize(t,this.#al())}static startHighlighting(t,e,{target:i,x:n,y:s}){const{x:r,y:a,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#ul(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:d});window.addEventListener("pointerup",pointerUpCallback,{signal:d});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d});window.addEventListener("contextmenu",noContextMenu,{signal:d});i.addEventListener("pointermove",this.#pl.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({x:n,y:s},[r,a,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#pl(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#ul(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let n=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:s,id:r,color:a,opacity:o,popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:g}}}=t;n=t={annotationType:p.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:s,id:r,color:a,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:g}}}=t;n=t={annotationType:p.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:s,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}const{color:s,quadPoints:r,inkLists:a,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...s);l.opacity=o||1;a&&(l.#bo=t.thickness);l._initialData=n;t.comment&&l.setCommentData(t);const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(r){const t=l.#Vo=[];for(let e=0;et!==e[i])}renderAnnotationElement(t){if(this.deleted){t.hide();return null}t.updateEdited({rect:this.getPDFRect(),popup:this.comment});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#gl=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#gl[t]=e}toSVGProperties(){const t=this.#gl;this.#gl=Object.create(null);return{root:t}}reset(){this.#gl=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#ml=null;#fl;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#bl=null;static#wl=null;static#yl=null;static _INNER_MARGIN=3;constructor(t){super(t);this.#fl=t.mustBeCommitted||!1;this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color);super.onUpdatedColor()}_addOutlines(t){if(t.drawOutlines){this.#Al(t);this.#el()}}#Al({drawOutlines:t,drawId:e,drawingOptions:i}){this.#ml=t;this._drawingOptions||=i;this.annotationElementId||this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`);if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#vl(t,this.parent);this.#xl(t.box)}#vl(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[n,s]of Object.entries(e))i.has(n)?Object.assign(t[n],s):t[n]=s;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#bl.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,n]of this.typesMap)t.push([i,e[n]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,n]of this.constructor.typesMap)t.push([i,e[n]]);return t}_updateProperty(t,e,i){const n=this._drawingOptions,s=n[e],setter=i=>{n.updateProperty(e,i);const s=this.#ml.updateProperty(e,i);s&&this.#xl(s);this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties());t===this.colorType&&this.onUpdatedColor()};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ml.getPathResizingSVGProperties(this.#El()),{bbox:this.#Cl()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ml.getPathResizedSVGProperties(this.#El()),{bbox:this.#Cl()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Cl()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ml.getPathTranslatedSVGProperties(this.#El(),this.parentDimensions),{bbox:this.#Cl()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#fl){this.#fl=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#ol();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#el();this.#xl(this.#ml.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#ol()}else if(t){this._uiManager.addShouldRescale(this);this.#el(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#ol(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#el(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#vl(this.#ml,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Sl([t,e,i,n]){const{parentDimensions:[s,r],rotation:a}=this;switch(a){case 90:return[e,1-t,i*(r/s),n*(s/r)];case 180:return[1-t,1-e,i,n];case 270:return[1-e,t,i*(r/s),n*(s/r)];default:return[t,e,i,n]}}#El(){const{x:t,y:e,width:i,height:n,parentDimensions:[s,r],rotation:a}=this;switch(a){case 90:return[1-e,t,i*(s/r),n*(r/s)];case 180:return[1-t,1-e,i,n];case 270:return[e,1-t,i*(s/r),n*(r/s)];default:return[t,e,i,n]}}#xl(t){[this.x,this.y,this.width,this.height]=this.#Sl(t);if(this.div){this.fixAndSetPosition();this.setDims()}this._onResized()}#Cl(){const{x:t,y:e,width:i,height:n,rotation:s,parentRotation:r,parentDimensions:[a,o]}=this;switch((4*s+r)/90){case 1:return[1-e-n,t,n,i];case 2:return[1-t-i,1-e-n,i,n];case 3:return[e,1-t-i,n,i];case 4:return[t,e-i*(a/o),n*(o/a),i*(a/o)];case 5:return[1-e,t,i*(a/o),n*(o/a)];case 6:return[1-t-n*(o/a),1-e,n*(o/a),i*(a/o)];case 7:return[e-i*(a/o),1-t-n*(o/a),i*(a/o),n*(o/a)];case 8:return[t-i,e-n,i,n];case 9:return[1-e,t-i,n,i];case 10:return[1-t,1-e,i,n];case 11:return[e-n,1-t,n,i];case 12:return[t-n*(o/a),e,n*(o/a),i*(a/o)];case 13:return[1-e-i*(a/o),t-n*(o/a),i*(a/o),n*(o/a)];case 14:return[1-t,1-e-i*(a/o),n*(o/a),i*(a/o)];case 15:return[e,1-t,i*(a/o),n*(o/a)];default:return[t,e,i,n]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Cl()},this.#ml.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#xl(this.#ml.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}const i=super.render();i.classList.add("draw");const n=document.createElement("div");i.append(n);n.setAttribute("aria-hidden","true");n.className="internal";this.setDims();this._uiManager.addShouldRescale(this);this.disableEditing();this._isCopy&&this._moveAfterPaste(t,e);return i}static createDrawerInstance(t,e,i,n,s){unreachable("Not implemented")}static startDrawing(t,e,i,n){const{target:s,offsetX:r,offsetY:a,pointerId:o,pointerType:l}=n;if(CurrentPointers.isInitializedAndDifferentPointerType(l))return;const{viewport:{rotation:h}}=t,{width:d,height:c}=s.getBoundingClientRect(),u=DrawingEditor.#wl=new AbortController,p=t.combinedSignal(u);CurrentPointers.setPointer(l,o);window.addEventListener("pointerup",t=>{CurrentPointers.isSamePointerIdOrRemove(t.pointerId)&&this._endDraw(t)},{signal:p});window.addEventListener("pointercancel",t=>{CurrentPointers.isSamePointerIdOrRemove(t.pointerId)&&this._currentParent.endDrawingSession()},{signal:p});window.addEventListener("pointerdown",t=>{if(CurrentPointers.isSamePointerType(t.pointerType)){CurrentPointers.initializeAndAddPointerId(t.pointerId);if(DrawingEditor.#bl.isCancellable()){DrawingEditor.#bl.removeLastElement();DrawingEditor.#bl.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}},{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});s.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});s.addEventListener("touchmove",t=>{CurrentPointers.isSameTimeStamp(t.timeStamp)&&stopEvent(t)},{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#bl)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#bl.startNew(r,a,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#bl=this.createDrawerInstance(r,a,d,c,h);DrawingEditor.#yl=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#yl.toSVGProperties(),DrawingEditor.#bl.defaultSVGProperties),!0,!1))}}static _drawMove(t){CurrentPointers.isSameTimeStamp(t.timeStamp);if(!DrawingEditor.#bl)return;const{offsetX:e,offsetY:i,pointerId:n}=t;if(CurrentPointers.isSamePointerId(n))if(CurrentPointers.isUsingMultiplePointers())this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#bl.add(e,i));CurrentPointers.setTimeStamp(t.timeStamp);stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#bl=null;DrawingEditor.#yl=null;CurrentPointers.clearTimeStamp()}if(DrawingEditor.#wl){DrawingEditor.#wl.abort();DrawingEditor.#wl=null;CurrentPointers.clearPointerIds()}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#bl.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#bl,i=this._currentDrawId,n=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:g.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(g.DRAW_STEP);if(!DrawingEditor.#bl.isEmpty()){const{pageDimensions:[i,n],scale:s}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#bl.getOutlines(i*s,n*s,s,this._INNER_MARGIN),drawingOptions:DrawingEditor.#yl,mustBeCommitted:!t});this._cleanup(!0);return r}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,n,s,r){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:n,pageHeight:s,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,n,s,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#Al({drawOutlines:o});l.#el();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[n,s]=this.pageDimensions;return this.#ml.serialize([e,i,n,s],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getPDFRect()});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#co=new Float64Array(6);#Ia;#Tl;#Os;#bo;#wo;#_l="";#Dl=0;#zo=new InkDrawOutline;#Pl;#Ml;constructor(t,e,i,n,s,r){this.#Pl=i;this.#Ml=n;this.#Os=s;this.#bo=r;[t,e]=this.#kl(t,e);const a=this.#Ia=[NaN,NaN,NaN,NaN,t,e];this.#wo=[t,e];this.#Tl=[{line:a,points:this.#wo}];this.#co.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#bo=e)}#kl(t,e){return Outline._normalizePoint(t,e,this.#Pl,this.#Ml,this.#Os)}isEmpty(){return!this.#Tl||0===this.#Tl.length}isCancellable(){return this.#wo.length<=10}add(t,e){[t,e]=this.#kl(t,e);const[i,n,s,r]=this.#co.subarray(2,6),a=t-s,o=e-r;if(Math.hypot(this.#Pl*a,this.#Ml*o)<=2)return null;this.#wo.push(t,e);if(isNaN(i)){this.#co.set([s,r,t,e],2);this.#Ia.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#co[0])&&this.#Ia.splice(6,6);this.#co.set([i,n,s,r,t,e],0);this.#Ia.push(...Outline.createBezierPoints(i,n,s,r,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#wo.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,n,s){this.#Pl=i;this.#Ml=n;this.#Os=s;[t,e]=this.#kl(t,e);const r=this.#Ia=[NaN,NaN,NaN,NaN,t,e];this.#wo=[t,e];const a=this.#Tl.at(-1);if(a){a.line=new Float32Array(a.line);a.points=new Float32Array(a.points)}this.#Tl.push({line:r,points:this.#wo});this.#co.set(r,0);this.#Dl=0;this.toSVGPath();return null}getLastElement(){return this.#Tl.at(-1)}setLastElement(t){if(!this.#Tl)return this.#zo.setLastElement(t);this.#Tl.push(t);this.#Ia=t.line;this.#wo=t.points;this.#Dl=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Tl)return this.#zo.removeLastElement();this.#Tl.pop();this.#_l="";for(let t=0,e=this.#Tl.length;tt??NaN),d,c,u,p),points:g(a[t].map(t=>t??NaN),d,c,u,p)});const m=new this.prototype.constructor;m.build(h,i,n,1,o,l,s);return m}#Ll(t=this.#bo){const e=this.#lo+t/2*this.#Fl;return this.#Os%180==0?[e/this.#Pl,e/this.#Ml]:[e/this.#Ml,e/this.#Pl]}#Bl(){const[t,e,i,n]=this.#Po,[s,r]=this.#Ll(0);return[t+s,e+r,i-2*s,n-2*r]}#Rl(){const t=this.#Po=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Tl){if(e.length<=12){for(let i=4,n=e.length;it!==e[i])||t.thickness!==i||t.opacity!==n||t.pageIndex!==s}renderAnnotationElement(t){if(this.deleted){t.hide();return null}const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment});return null}}class ContourDrawOutline extends InkDrawOutline{toSVGPath(){let t=super.toSVGPath();t.endsWith("Z")||(t+="Z");return t}}class SignatureExtractor{static#Ol={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#Nl(t,e,i,n){n-=e;return 0===(i-=t)?n>0?0:4:1===i?n+6:2-n}static#Ul=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#Hl(t,e,i,n,s,r,a){const o=this.#Nl(i,n,s,r);for(let s=0;s<8;s++){const r=(-s+o-a+16)%8;if(0!==t[(i+this.#Ul[2*r])*e+(n+this.#Ul[2*r+1])])return r}return-1}static#zl(t,e,i,n,s,r,a){const o=this.#Nl(i,n,s,r);for(let s=0;s<8;s++){const r=(s+o+a+16)%8;if(0!==t[(i+this.#Ul[2*r])*e+(n+this.#Ul[2*r+1])])return r}return-1}static#Gl(t,e,i,n){const s=t.length,r=new Int32Array(s);for(let e=0;e=1&&0===r[n+1])){1!==s&&(a=Math.abs(s));continue}o+=1;d+=1;s>1&&(a=s)}const c=[i,t],u=d===i+1,p={isHole:u,points:c,id:o,parent:0};l.push(p);let g;for(const t of l)if(t.id===a){g=t;break}g?g.isHole?p.parent=u?g.parent:a:p.parent=u?a:g.parent:p.parent=u?a:0;const m=this.#Hl(r,e,t,i,h,d,0);if(-1===m){r[n]=-o;1!==r[n]&&(a=Math.abs(r[n]));continue}let f=this.#Ul[2*m],b=this.#Ul[2*m+1];const w=t+f,y=i+b;h=w;d=y;let A=t,v=i;for(;;){const s=this.#zl(r,e,A,v,h,d,1);f=this.#Ul[2*s];b=this.#Ul[2*s+1];const l=A+f,u=v+b;c.push(u,l);const p=A*e+v;0===r[p+1]?r[p]=-o:1===r[p]&&(r[p]=o);if(l===t&&u===i&&A===w&&v===y){1!==r[n]&&(a=Math.abs(r[n]));break}h=A;d=v;A=l;v=u}}}return l}static#Wl(t,e,i,n){if(i-e<=4){for(let s=e;sA){v=n;A=e}}if(A>(l*y)**2){this.#Wl(t,e,v+2,n);this.#Wl(t,v,i,n)}else n.push(s,r)}static#Vl(t){const e=[],i=t.length;this.#Wl(t,0,i,e);e.push(t[i-2],t[i-1]);return e.length<=4?null:e}static#jl(t,e,i,n,s,r){const a=new Float32Array(r**2),o=-2*n**2,l=r>>1;for(let t=0;t=i))for(let i=0;i=e)continue;const p=t[u*e+n],m=a[o*r+i]*h[Math.abs(p-d)];c+=p*m;g+=m}}p[u[o]=Math.round(c/g)]++}return[u,p]}static#$l(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#Xl(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let n=-1/0,s=1/0;for(let e=0,r=i.length;e0!==t);let r=s,a=s;for(e=s;e<256;e++){const s=t[e];if(s>i){if(e-r>n){n=e-r;a=e-1}i=s;r=e}}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#Kl(t){const e=t,{width:i,height:n}=t,{maxDim:s}=this.#Ol;let r=i,a=n;if(i>s||n>s){let o=i,l=n,h=Math.log2(Math.max(i,n)/s);const d=Math.floor(h);h=h===d?d-1:d;for(let i=0;i=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,d=8+3*h,c=new Uint32Array(d);let u=0;c[u++]=d*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*r.BYTES_PER_ELEMENT;c[u++]=0;c[u++]=n;c[u++]=s;c[u++]=e?0:1;c[u++]=Math.max(0,Math.floor(i??0));c[u++]=h;c[u++]=r.BYTES_PER_ELEMENT;for(const e of t){c[u++]=e.length-2;c[u++]=e[0];c[u++]=e[1]}const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready;g.write(c);const m=r.prototype.constructor;for(const e of t){const t=new m(e.length-2);for(let i=2,n=e.length;i{await s.ready;await s.close()}).catch(()=>{});let r=null,a=0;for await(const t of i){r||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]);r.set(t,a);a+=t.length}const o=new Uint32Array(r.buffer,0,r.length>>2),l=o[1];if(0!==l)throw new Error(`Invalid version: ${l}`);const h=o[2],d=o[3],c=0===o[4],u=o[5],p=o[6],g=o[7],m=[],f=(8+3*p)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(g){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(r.buffer,f);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(r.buffer,f);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(r.buffer,f)}a=0;for(let t=0;t{e?.updateEditSignatureButton(t)})}}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:i,width:n,height:s}=this.#Jl,r=Math.max(n,s);return{areContours:e,outline:SignatureExtractor.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:n,height:s},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,i,n){const{x:s,y:r}=this,{outline:a}=this.#Jl=t;this.#Yl=a instanceof ContourDrawOutline;this.description=i;let o;if(this.#Yl)o=SignatureEditor.getDefaultDrawingOptions();else{o=SignatureEditor._defaultDrawnSignatureOptions.clone();o.updateProperties({"stroke-width":a.thickness})}this._addOutlines({drawOutlines:a,drawingOptions:o});const[,l]=this.pageDimensions;let h=e/l;h=h>=1?.5:h;this.width*=h/this.height;if(this.width>=1){h*=.9/this.width;this.width=.9}this.height=h;this.setDims();this.x=s;this.y=r;this.center();this._onResized();this.onScaleChanging();this.rotate();this._uiManager.addToAnnotationStorage(this);this.setUuid(n);this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!n,hasDescription:!!i}});this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return SignatureExtractor.process(t,e,i,n,SignatureEditor._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:n},rotation:s}=this.parent.viewport;return SignatureExtractor.extractContoursFromText(t,e,i,n,s,SignatureEditor._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return SignatureExtractor.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){if(t)this._drawingOptions=SignatureEditor.getDefaultDrawingOptions();else{this._drawingOptions=SignatureEditor._defaultDrawnSignatureOptions.clone();this._drawingOptions.updateProperties({"stroke-width":e})}}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":n}}=this,s=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#Yl,color:[0,0,0],thickness:this.#Yl?0:n});this.addComment(s);if(t){s.paths={lines:e,points:i};s.uuid=this.#Zl;s.isCopy=!0}else s.lines=e;this.#Ql&&(s.accessibilityData={type:"Figure",alt:this.#Ql});return s}static deserializeDraw(t,e,i,n,s,r){return r.areContours?ContourDrawOutline.deserialize(t,e,i,n,s,r):InkDrawOutline.deserialize(t,e,i,n,s,r)}static async deserialize(t,e,i){const n=await super.deserialize(t,e,i);n.#Yl=t.areContours;n.description=t.accessibilityData?.alt||"";n.#Zl=t.uuid;return n}}class StampEditor extends AnnotationEditor{#th=null;#eh=null;#ih=null;#nh=null;#sh=null;#rh="";#ah=null;#oh=!1;#lh=null;#hh=!1;#dh=!1;static _type="stamp";static _editorType=p.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#nh=t.bitmapUrl;this.#sh=t.bitmapFile;this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e)}static isHandlingMimeForPasting(t){return $.includes(t)}static paste(t,e){e.pasteEditor({mode:p.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#ch(t,e=!1){if(t){this.#th=t.bitmap;if(!e){this.#eh=t.id;this.#hh=t.isSvg}t.file&&(this.#rh=t.file.name);this.#uh()}else this.remove()}#ph(){this.#ih=null;this._uiManager.enableWaiting(!1);if(this.#ah)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#th)this.addEditToolbar().then(()=>{this._editToolbar.hide();this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#th){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:n,width:s,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await i.guess({name:"altText",request:{data:n,width:s,height:r,channels:n.length/(s*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const o=a.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#gh(){if(this.#eh){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#eh).then(t=>this.#ch(t,!0)).finally(()=>this.#ph());return}if(this.#nh){const t=this.#nh;this.#nh=null;this._uiManager.enableWaiting(!0);this.#ih=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#ch(t)).finally(()=>this.#ph());return}if(this.#sh){const t=this.#sh;this.#sh=null;this._uiManager.enableWaiting(!0);this.#ih=this._uiManager.imageManager.getFromFile(t).then(t=>this.#ch(t)).finally(()=>this.#ph());return}const t=document.createElement("input");t.type="file";t.accept=$.join(",");const e=this._uiManager._signal;this.#ih=new Promise(i=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#ch(e)}else this.remove();i()},{signal:e});t.addEventListener("cancel",()=>{this.remove();i()},{signal:e})}).finally(()=>this.#ph());t.click()}remove(){if(this.#eh){this.#th=null;this._uiManager.imageManager.deleteId(this.#eh);this.#ah?.remove();this.#ah=null;if(this.#lh){clearTimeout(this.#lh);this.#lh=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#eh&&null===this.#ah&&this.#gh();this.isAttachedToDOM||this.parent.add(this)}}else this.#eh&&this.#gh()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#ih||this.#th||this.#nh||this.#sh||this.#eh||this.#oh)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.createAltText();this.#oh||(this.#th?this.#uh():this.#gh());this._isCopy&&this._moveAfterPaste(t,e);this._uiManager.addShouldRescale(this);return this.div}setCanvas(t,e){const{id:i,bitmap:n}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove();if(i&&this._uiManager.imageManager.isValidId(i)){this.#eh=i;n&&(this.#th=n);this.#oh=!1;this.#uh()}}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#lh&&clearTimeout(this.#lh);this.#lh=setTimeout(()=>{this.#lh=null;this.#mh()},200)}#uh(){const{div:t}=this;let{width:e,height:i}=this.#th;const[n,s]=this.pageDimensions,r=.75;if(this.width){e=this.width*n;i=this.height*s}else if(e>r*n||i>r*s){const t=Math.min(r*n/e,r*s/i);e*=t;i*=t}this._uiManager.enableWaiting(!1);const a=this.#ah=document.createElement("canvas");a.setAttribute("role","img");this.addContainer(a);this.width=e/n;this.height=i/s;this.setDims();this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#mh();if(!this.#dh){this.parent.addUndoableEditor(this);this.#dh=!0}this._reportTelemetry({action:"inserted_image"});this.#rh&&this.div.setAttribute("aria-description",this.#rh);this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")}copyCanvas(t,e,i=!1){t||(t=224);const{width:n,height:s}=this.#th,r=new OutputScale;let a=this.#th,o=n,l=s,h=null;if(e){if(n>e||s>e){const t=Math.min(e/n,e/s);o=Math.floor(n*t);l=Math.floor(s*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*r.sx),i=h.height=Math.ceil(l*r.sy);this.#hh||(a=this.#fh(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(ColorScheme.isDarkMode){c="#8f8f9d";u="#42414d"}const p=15,g=p*r.sx,m=p*r.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c;b.fillRect(0,0,2*g,2*m);b.fillStyle=u;b.fillRect(0,0,g,m);b.fillRect(g,m,g,m);d.fillStyle=d.createPattern(f,"repeat");d.fillRect(0,0,t,i);d.drawImage(a,0,0,a.width,a.height,0,0,t,i)}let d=null;if(i){let e,i;if(r.symmetric&&a.widtht||s>t){const r=Math.min(t/n,t/s);e=Math.floor(n*r);i=Math.floor(s*r);this.#hh||(a=this.#fh(e,i))}}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(a,0,0,a.width,a.height,0,0,e,i);d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#fh(t,e){const{width:i,height:n}=this.#th;let s=i,r=n,a=this.#th;for(;s>2*t||r>2*e;){const i=s,n=r;s>2*t&&(s=s>=16384?Math.floor(s/2)-1:Math.ceil(s/2));r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const o=new OffscreenCanvas(s,r);o.getContext("2d").drawImage(a,0,0,i,n,0,0,s,r);a=o.transferToImageBitmap()}return a}#mh(){const[t,e]=this.parentDimensions,{width:i,height:n}=this,s=new OutputScale,r=Math.ceil(i*t*s.sx),a=Math.ceil(n*e*s.sy),o=this.#ah;if(!o||o.width===r&&o.height===a)return;o.width=r;o.height=a;const l=this.#hh?this.#th:this.#fh(r,a),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,r,a)}#bh(t){if(t){if(this.#hh){const t=this._uiManager.imageManager.getSvgUrl(this.#eh);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#th);t.getContext("2d").drawImage(this.#th,0,0);return t.toDataURL()}if(this.#hh){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),n=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),s=new OffscreenCanvas(i,n);s.getContext("2d").drawImage(this.#th,0,0,this.#th.width,this.#th.height,0,0,i,n);return s.transferToImageBitmap()}return structuredClone(this.#th)}static async deserialize(t,e,i){let n=null,s=!1;if(t instanceof StampAnnotationElement){const{data:{rect:r,rotation:a,id:o,structParent:l,popupRef:h,richText:d,contentsObj:c,creationDate:u,modificationDate:g},container:m,parent:{page:{pageNumber:f}},canvas:b}=t;let w,y;if(b){delete t.canvas;({id:w,bitmap:y}=i.imageManager.getFromCanvas(m.id,b));b.remove()}else{s=!0;t._hasNoCanvas=!0}const A=(await e._structTree.getAriaAttributes(`${V}${o}`))?.get("aria-label")||"";n=t={annotationType:p.STAMP,bitmapId:w,bitmap:y,pageIndex:f-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:A},isSvg:!1,structParent:l,popupRef:h,richText:d,comment:c?.str||null,creationDate:u,modificationDate:g}}const r=await super.deserialize(t,e,i),{rect:a,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:d,accessibilityData:c}=t;if(s){i.addMissingCanvas(t.id,r);r.#oh=!0}else if(h&&i.imageManager.isValidId(h)){r.#eh=h;o&&(r.#th=o)}else r.#nh=l;r.#hh=d;const[u,g]=r.pageDimensions;r.width=(a[2]-a[0])/u;r.height=(a[3]-a[1])/g;c&&(r.altTextData=c);r._initialData=n;t.comment&&r.setCommentData(t);r.#dh=!!n;return r}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:this.#eh,isSvg:this.#hh});this.addComment(i);if(t){i.bitmapUrl=this.#bh(!0);i.accessibilityData=this.serializeAltText(!0);i.isCopy=!0;return i}const{decorative:n,altText:s}=this.serializeAltText(!1);!n&&s&&(i.accessibilityData={type:"Figure",alt:s});if(this.annotationElementId){const t=this.#ro(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1;i.id=this.annotationElementId;delete i.bitmapId;return i}if(null===e)return i;e.stamps||=new Map;const r=this.#hh?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#eh)){if(this.#hh){const t=e.stamps.get(this.#eh);if(r>t.area){t.area=r;t.serialized.bitmap.close();t.serialized.bitmap=this.#bh(!1)}}}else{e.stamps.set(this.#eh,{area:r,serialized:i});i.bitmap=this.#bh(!1)}return i}#ro(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,n=t.pageIndex===e,s=(t.accessibilityData?.alt||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&n&&s,isSameAltText:s}}renderAnnotationElement(t){if(this.deleted){t.hide();return null}t.updateEdited({rect:this.getPDFRect(),popup:this.comment});return null}}class AnnotationEditorLayer{#za;#wh=!1;#yh=null;#Ah=null;#vh=null;#xh=new Map;#Eh=!1;#Ch=!1;#Sh=!1;#Th=null;#_h=null;#Dh=null;#Ph=null;#Mh=null;#kh=-1;#P;static _initialized=!1;static#ot=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor,SignatureEditor].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:n,accessibilityManager:s,annotationLayer:r,drawLayer:a,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#ot.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#P=t;this.pageIndex=e;this.div=i;this.#za=s;this.#yh=r;this.viewport=l;this.#Dh=o;this.drawLayer=a;this._structTree=n;this.#P.addLayer(this)}updatePageIndex(t){for(const e of this.#Ih)e.updatePageIndex(t);this.pageIndex=t;this.#P.addLayer(this)}async setClonedFrom(t){if(!t)return;const e=[];for(const i of t.#Ih){const t=i.serialize(!0);if(t){t.isCopy=!1;e.push(this.deserialize(t).then(t=>{t&&this.addOrRebuild(t)}))}}await Promise.all(e)}get isEmpty(){return 0===this.#xh.size}get isInvisible(){return this.isEmpty&&this.#P.getMode()===p.NONE}updateToolbar(t){this.#P.updateToolbar(t)}updateMode(t=this.#P.getMode()){this.#Fh();switch(t){case p.NONE:this.div.classList.toggle("nonEditing",!0);this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case p.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case p.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;e.toggle("nonEditing",!1);if(t===p.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const i of AnnotationEditorLayer.#ot.values())e.toggle(`${i._type}Editing`,t===i._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#Dh?.div}setEditingState(t){this.#P.setEditingState(t)}addCommands(t){this.#P.addCommands(t)}cleanUndoStack(t){this.#P.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#yh?.togglePointerEvents(t)}get#Ih(){return 0!==this.#xh.size?this.#xh.values():this.#P.getEditors(this.pageIndex)}async enable(){this.#Sh=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);this.div.classList.toggle("nonEditing",!1);this.#Mh?.abort();this.#Mh=null;const t=new Set;for(const e of this.#Ih){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#P.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}const e=this.#yh;if(e)for(const i of e.getEditableAnnotations()){i.hide();if(this.#P.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#Sh=!1;this.#P._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){this.#Ch=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);this.div.classList.toggle("nonEditing",!0);if(this.#Dh&&!this.#Mh){this.#Mh=new AbortController;const t=this.#P.combinedSignal(this.#Mh);this.#Dh.div.addEventListener("pointerdown",t=>{const{clientX:e,clientY:i,timeStamp:n}=t;if(n-this.#kh>500){this.#kh=n;return}this.#kh=-1;const{classList:s}=this.div;s.toggle("getElements",!0);const r=document.elementsFromPoint(e,i);s.toggle("getElements",!1);if(!this.div.contains(r[0]))return;let a;const o=new RegExp(`^${u}[0-9]+$`);for(const t of r)if(o.test(t.id)){a=t.id;break}if(!a)return;const l=this.#xh.get(a);if(null===l?.annotationElementId){t.stopPropagation();t.preventDefault();l.dblclick(t)}},{signal:t,capture:!0})}const t=this.#yh,e=[];if(t){const i=new Map,n=new Map;for(const t of this.#Ih){t.disableEditing();if(t.annotationElementId)if(null===t.serialize()){n.set(t.annotationElementId,t);this.getEditableAnnotation(t.annotationElementId)?.show();t.remove()}else i.set(t.annotationElementId,t);else e.push(t)}const s=t.getEditableAnnotations();for(const t of s){const{id:e}=t.data;if(this.#P.isDeletedAnnotationElement(e)){t.updateEdited({deleted:!0});continue}let s=n.get(e);if(s){s.resetAnnotationElement(t);s.show(!1);t.show()}else{s=i.get(e);if(s){this.#P.addChangedExistingAnnotation(s);s.renderAnnotationElement(t)&&s.show(!1)}t.show()}}}this.#Fh();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#ot.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);t?.updateFakeAnnotations(e);this.#Ch=!1}getEditableAnnotation(t){return this.#yh?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#P.getActive()!==t&&this.#P.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#Dh?.div&&!this.#Ph){this.#Ph=new AbortController;const t=this.#P.combinedSignal(this.#Ph);this.#Dh.div.addEventListener("pointerdown",this.#Rh.bind(this),{signal:t});this.#Dh.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#Dh?.div&&this.#Ph){this.#Ph.abort();this.#Ph=null;this.#Dh.div.classList.remove("highlighting")}}#Rh(t){this.#P.unselectAll();const{target:e}=t;if(e===this.#Dh.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Dh.div.contains(e)){const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#P.showAllEditors("highlight",!0,!0);this.#Dh.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#P.direction,{target:this.#Dh.div,x:t.x,y:t.y});this.#Dh.div.addEventListener("pointerup",()=>{this.#Dh.div.classList.remove("free");this.toggleDrawing(!0)},{once:!0,signal:this.#P._signal});t.preventDefault()}}enableClick(){if(this.#Ah)return;this.#Ah=new AbortController;const t=this.#P.combinedSignal(this.#Ah);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#Ah?.abort();this.#Ah=null}attach(t){this.#xh.set(t.id,t);const{annotationElementId:e}=t;e&&this.#P.isDeletedAnnotationElement(e)&&this.#P.removeDeletedAnnotationElement(t)}detach(t){this.#xh.delete(t.id);this.#za?.removePointerInTextLayer(t.contentDiv);!this.#Ch&&t.annotationElementId&&this.#P.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#P.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#P.addDeletedAnnotationElement(t);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#P.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#Sh);this.#P.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#vh){t._focusEventsAllowed=!1;this.#vh=setTimeout(()=>{this.#vh=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#P._signal});e.focus()}},0)}t._structTreeParentId=this.#za?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getEditorByUID(t){for(const e of this.#xh.values())if(e.uid===t)return e;return null}getNextId(){return this.#P.getId()}get#Bh(){return AnnotationEditorLayer.#ot.get(this.#P.getMode())}combinedSignal(t){return this.#P.combinedSignal(t)}#Lh(t){const e=this.#Bh;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Bh?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t);await this.#P.updateMode(t.mode);const{offsetX:i,offsetY:n}=this.#Oh(),s=this.getNextId(),r=this.#Lh({parent:this,id:s,x:i,y:n,uiManager:this.#P,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await(AnnotationEditorLayer.#ot.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#P))||null}createAndAddNewEditor(t,e,i={}){const n=this.getNextId(),s=this.#Lh({parent:this,id:n,x:t.offsetX,y:t.offsetY,uiManager:this.#P,isCentered:e,...i});s&&this.add(s);return s}get boundingClientRect(){return this.div.getBoundingClientRect()}#Oh(){const{x:t,y:e,width:i,height:n}=this.boundingClientRect,s=Math.max(0,t),r=Math.max(0,e),a=(s+Math.min(window.innerWidth,t+i))/2-t,o=(r+Math.min(window.innerHeight,e+n))/2-e,[l,h]=this.viewport.rotation%180==0?[a,o]:[o,a];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#Oh(),!0,t)}setSelected(t){this.#P.setSelected(t)}toggleSelected(t){this.#P.toggleSelected(t)}unselect(t){this.#P.unselect(t)}pointerup(t){const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#Eh)return;this.#Eh=!1;if(this.#Bh?.isDrawer&&this.#Bh.supportMultipleDrawings)return;if(!this.#wh){this.#wh=!0;return}const i=this.#P.getMode();i!==p.STAMP&&i!==p.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#P.unselectAll()}pointerdown(t){this.#P.getMode()===p.HIGHLIGHT&&this.enableTextSelection();if(this.#Eh){this.#Eh=!1;return}const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#Eh=!0;if(this.#Bh?.isDrawer){this.startDrawingSession(t);return}const i=this.#P.getActive();this.#wh=!i||i.isEmpty()}startDrawingSession(t){this.div.focus({preventScroll:!0});if(this.#Th){this.#Bh.startDrawing(this,this.#P,!1,t);return}this.#P.setCurrentDrawingSession(this);this.#Th=new AbortController;const e=this.#P.combinedSignal(this.#Th);this.div.addEventListener("blur",({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#_h=null;this.commitOrRemove()}},{signal:e});this.#Bh.startDrawing(this,this.#P,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#_h=t);return}this.#_h&&setTimeout(()=>{this.#_h?.focus();this.#_h=null},0)}endDrawingSession(t=!1){if(!this.#Th)return null;this.#P.setCurrentDrawingSession(null);this.#Th.abort();this.#Th=null;this.#_h=null;return this.#Bh.endDrawing(t)}findNewParent(t,e,i){const n=this.#P.findParent(e,i);if(null===n||n===this)return!1;n.changeParent(t);return!0}commitOrRemove(){if(this.#Th){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#Th&&this.#Bh.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#P.getActive()?.parent===this){this.#P.commitOrRemove();this.#P.setActiveEditor(null)}if(this.#vh){clearTimeout(this.#vh);this.#vh=null}for(const t of this.#xh.values()){this.#za?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#xh.clear();this.#P.removeLayer(this)}#Fh(){for(const t of this.#xh.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#P.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#P.commitOrRemove();this.#Fh();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#xh.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#P.viewParameters.realScale}}class DrawLayer{#ca=null;#Nh=new Map;#Uh=new Map;static#O=0;setParent(t){if(this.#ca){if(this.#ca!==t){if(this.#Nh.size>0)for(const e of this.#Nh.values()){e.remove();t.append(e)}this.#ca=t}}else this.#ca=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#Hh(t,[e,i,n,s]){const{style:r}=t;r.top=100*i+"%";r.left=100*e+"%";r.width=100*n+"%";r.height=100*s+"%"}#zh(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#ca.append(t);t.setAttribute("aria-hidden",!0);return t}#Gh(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const n=`clip_${e}`;i.setAttribute("id",n);i.setAttribute("clipPathUnits","objectBoundingBox");const s=DrawLayer._svgFactory.createElement("use");i.append(s);s.setAttribute("href",`#${e}`);s.classList.add("clip");return n}#Wh(t,e){for(const[i,n]of Object.entries(e))null===n?t.removeAttribute(i):t.setAttribute(i,n)}draw(t,e=!1,i=!1){const n=DrawLayer.#O++,s=this.#zh(),r=DrawLayer._svgFactory.createElement("defs");s.append(r);const a=DrawLayer._svgFactory.createElement("path");r.append(a);const o=`path_${n}`;a.setAttribute("id",o);a.setAttribute("vector-effect","non-scaling-stroke");e&&this.#Uh.set(n,a);const l=i?this.#Gh(r,o):null,h=DrawLayer._svgFactory.createElement("use");s.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(s,t);this.#Nh.set(n,s);return{id:n,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=DrawLayer.#O++,n=this.#zh(),s=DrawLayer._svgFactory.createElement("defs");n.append(s);const r=DrawLayer._svgFactory.createElement("path");s.append(r);const a=`path_${i}`;r.setAttribute("id",a);r.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");s.append(t);o=`mask_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const n=DrawLayer._svgFactory.createElement("use");t.append(n);n.setAttribute("href",`#${a}`);n.setAttribute("stroke","none");n.setAttribute("fill","black");n.setAttribute("fill-rule","nonzero");n.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");n.append(l);l.setAttribute("href",`#${a}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();n.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(n,t);this.#Nh.set(i,n);return i}finalizeDraw(t,e){this.#Uh.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:n,rootClass:s,path:r}=e,a="number"==typeof t?this.#Nh.get(t):t;if(a){i&&this.#Wh(a,i);n&&DrawLayer.#Hh(a,n);if(s){const{classList:t}=a;for(const[e,i]of Object.entries(s))t.toggle(e,i)}if(r){const t=a.firstElementChild.firstElementChild;this.#Wh(t,r)}}}updateParent(t,e){if(e===this)return;const i=this.#Nh.get(t);if(i){e.#ca.append(i);this.#Nh.delete(t);e.#Nh.set(t,i)}}remove(t){this.#Uh.delete(t);if(null!==this.#ca){this.#Nh.get(t).remove();this.#Nh.delete(t)}}destroy(){this.#ca=null;for(const t of this.#Nh.values())t.remove();this.#Nh.clear();this.#Uh.clear()}}globalThis._pdfjsTestingUtils={HighlightOutliner};globalThis.pdfjsLib={AbortException,AnnotationEditorLayer,AnnotationEditorParamsType:g,AnnotationEditorType:p,AnnotationEditorUIManager,AnnotationLayer,AnnotationMode:c,AnnotationType:S,applyOpacity,build:Lt,ColorPicker,createValidAbsoluteUrl,CSSConstants,DOMSVGFactory,DrawLayer,FeatureTest,fetchData,findContrastColor,getDocument,getFilenameFromUrl,getPdfFilenameFromUrl,getRGB,getUuid,getXfaPageViewport,GlobalWorkerOptions,ImageKind:C,InvalidPDFException,isDataScheme,isPdfFile,isValidExplicitDest:J,makeArr,makeMap,makeObj,MathClamp,noContextMenu,normalizeUnicode,OPS:I,OutputScale,PasswordResponses:N,PDFDataRangeTransport,PDFDateString,PDFWorker,PermissionFlag:m,PixelsPerInch,RenderingCancelledException,renderRichText,ResponseException,setLayerDimensions,shadow,SignatureExtractor,stopEvent,SupportedImageMimeTypes:$,TextLayer,TouchManager,updateUrlHash,Util,VerbosityLevel:k,version:Bt,XfaLayer};export{AbortException,AnnotationEditorLayer,g as AnnotationEditorParamsType,p as AnnotationEditorType,AnnotationEditorUIManager,AnnotationLayer,c as AnnotationMode,S as AnnotationType,CSSConstants,ColorPicker,DOMSVGFactory,DrawLayer,FeatureTest,GlobalWorkerOptions,C as ImageKind,InvalidPDFException,MathClamp,I as OPS,OutputScale,PDFDataRangeTransport,PDFDateString,PDFWorker,N as PasswordResponses,m as PermissionFlag,PixelsPerInch,RenderingCancelledException,ResponseException,SignatureExtractor,$ as SupportedImageMimeTypes,TextLayer,TouchManager,Util,k as VerbosityLevel,XfaLayer,applyOpacity,Lt as build,createValidAbsoluteUrl,fetchData,findContrastColor,getDocument,getFilenameFromUrl,getPdfFilenameFromUrl,getRGB,getUuid,getXfaPageViewport,isDataScheme,isPdfFile,J as isValidExplicitDest,makeArr,makeMap,makeObj,noContextMenu,normalizeUnicode,renderRichText,setLayerDimensions,shadow,stopEvent,updateUrlHash,Bt as version};