/** * @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.7.284 * pdfjsBuild = 7e5b36c2d */const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),e=[1/0,1/0,-1/0,-1/0],i=new Float32Array(e),s=[.001,0,0,.001,0,0],n=1.35,r=1,a=2,o=4,l=16,h=32,d=64,c=128,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g="pdfjs_internal_editor_",m={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},f={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},b={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},y=0,A=1,v=2,w=3,x=3,C=4,E={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},T={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},S=1,_=2,P=3,D=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,B=1,R=2,O=3,L=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 s=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}}(s)?s:null}function updateUrlHash(t,e,i=!1){const s=URL.parse(t);if(s){s.hash=e;return s.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,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,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 s=0;s{if("undefined"==typeof document)return!1;const t=document.createElement("input");t.type="color";t.setAttribute("alpha","");t.value="#ff000080";return"#ff0000"!==t.value})())}}class Util{static get hexNums(){return shadow(this,"hexNums",Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0")))}static makeHexColor(t,e,i){return`#${this.hexNums[t]}${this.hexNums[e]}${this.hexNums[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 s=t[i],n=t[i+1];t[i]=s*e[0]+n*e[2]+e[4];t[i+1]=s*e[1]+n*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const s=e[0],n=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*s+d*r+o;t[i+e+1]=h*n+d*a+l}}static applyInverseTransform(t,e){const i=t[0],s=t[1],n=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-s*e[2]+e[2]*e[5]-e[4]*e[3])/n;t[1]=(-i*e[1]+s*e[0]+e[4]*e[1]-e[5]*e[0])/n}static axialAlignedBoundingBox(t,e,i){const s=e[0],n=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=s*h+o,g=p,m=s*c+o,f=m,b=a*d+l,y=b,A=a*u+l,v=A;if(0!==n||0!==r){const t=n*h,e=n*c,i=r*d,s=r*u;p+=i;f+=i;m+=s;g+=s;b+=t;v+=t;A+=e;y+=e}i[0]=Math.min(i[0],p,m,g,f);i[1]=Math.min(i[1],b,A,y,v);i[2]=Math.max(i[2],p,m,g,f);i[3]=Math.max(i[3],b,A,y,v)}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],s=t[1],n=t[2],r=t[3],a=i**2+s**2,o=i*n+s*r,l=n**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])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=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 n>r?null:[i,n,s,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,s,n){n[0]=Math.min(n[0],t,i);n[1]=Math.min(n[1],e,s);n[2]=Math.max(n[2],t,i);n[3]=Math.max(n[3],e,s)}static#t(t,e,i,s,n,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*s,g=d*(d*(d*n+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,s,n,r,a,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,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,s,n,r,a,o,(-h+p)/g,c);this.#t(t,e,i,s,n,r,a,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,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,n,a,e,s,r,o,3*(3*(i-n)-t+a),6*(t-2*i+n),3*(i-t),l);this.#e(t,i,n,a,e,s,r,o,3*(3*(s-r)-e+o),6*(e-2*s+r),3*(s-e),l)}}let z=null,G=null;function normalizeUnicode(t){if(!z){z=/([\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;G=new Map([["ſt","ſt"]])}return t.replaceAll(z,(t,e,i)=>e?e.normalize("NFKC"):G.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)}class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))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,s,n){const r=s.getValue(e,{value:null});switch(i.name){case"textarea":null!==r.value&&(t.textContent=r.value);if("print"===n)break;t.addEventListener("input",t=>{s.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"===n)break;t.addEventListener("change",t=>{s.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"===n)break;t.addEventListener("input",t=>{s.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:Object.hasOwn(t.attributes,"selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})})}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${s}`);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&&n.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,s=t.xfaHtml,n=t.intent||"display",r=document.createElement(s.name);s.attributes&&this.setAttributes({html:r,element:s,intent:n,linkService:i});const a="richText"!==n,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===s.children.length){if(s.value){const t=document.createTextNode(s.value);r.append(t);a&&XfaText.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,r]];for(;h.length>0;){const[t,s,r]=h.at(-1);if(s+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:n,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 V="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,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0);n.responseType="bytes"===e?"arraybuffer":e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"bytes":i(new Uint8Array(n.response));return;case"blob":case"json":i(n.response);return}i(n.responseText)}};n.send(null)})}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=s;this.offsetX=n;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;(s%=360)<0&&(s+=360);switch(s){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+n;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+n;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:s=this.offsetY,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}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}},s=/\.pdf$/i,n=stripPath(i.pathname);if(s.test(n))return decode(n);if(i.searchParams.size>0){const getLast=t=>[...t].findLast(t=>s.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{#i=new Map;times=[];time(t){this.#i.has(t)&&warn(`Timer is already running for ${t}`);this.#i.set(t,Date.now())}timeEnd(t){this.#i.has(t)||warn(`Timer has not been started for ${t}`);this.times.push({name:t,start:this.#i.get(t),end:Date.now()});this.#i.delete(t)}toString(){const t=Math.max(...this.times.map(t=>t.name.length));return this.times.map(e=>`${e.name.padEnd(t)} ${e.end-e.start}ms\n`).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()}class PDFDateString{static#s;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#s||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#s.exec(t);if(!e)return null;const i=parseInt(e[1],10);let s=parseInt(e[2],10);s=s>=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n: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,s,n,r,a,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,r=[0,0,parseInt(s,10),parseInt(n,10)];return new PageViewport({viewBox:r,userUnit:1,scale:e,rotation:i})}function getRGBA(t){if(t.startsWith("#")){const e=t.slice(1);return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16),e.length>=8?parseInt(e.slice(6,8),16)/255:1]}if(t.startsWith("rgb(")){const[e,i,s]=t.slice(4,-1).split(",").map(t=>parseInt(t,10));return[e,i,s,1]}if(t.startsWith("rgba(")){const e=t.slice(5,-1).split(",");return[parseInt(e[0],10),parseInt(e[1],10),parseInt(e[2],10),parseFloat(e[3])]}const e=t.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return e?[Math.round(255*parseFloat(e[1])),Math.round(255*parseFloat(e[2])),Math.round(255*parseFloat(e[3])),void 0!==e[4]&&"none"!==e[4]?parseFloat(e[4]):1]:null}function getRGB(t){const e=getRGBA(t);if(!e){warn(`Not a valid color format: "${t}"`);return[0,0,0]}return e.slice(0,3)}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:r,f:a}=t.getTransform();return[e,i,s,n,r,a]}function getCurrentTransformInverse(t){const{a:e,b:i,c:s,d:n,e:r,f:a}=t.getTransform().invertSelf();return[e,i,s,n,r,a]}function setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:r}=t,a=FeatureTest.isCSSRoundSupported,o=`var(--total-scale-factor) * ${s}px`,l=`var(--total-scale-factor) * ${n}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}}s&&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,s,n=-1){let r=1/0,a=1/0,o=1/0;(i=OutputScale.capPixels(i,n))>0&&(r=Math.sqrt(i/(t*e)));if(-1!==s){a=s/t;o=s/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 j=["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){const i=255*(1-(e=MathClamp(e??1,0,1)));return t.map(t=>Math.round(t*e+i))}function RGBToHSL(t,e){const i=t[0]/255,s=t[1]/255,n=t[2]/255,r=Math.max(i,s,n),a=Math.min(i,s,n),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*((s-n)/t+(sn?(s+.05)/(n+.05):(n+.05)/(s+.05)}const $=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 s=$.get(i);if(s)return s;const n=new Float32Array(9),r=n.subarray(0,3),a=n.subarray(3,6);RGBToHSL(t,a);const o=n.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){e.delete()},{signal:e._signal});this.#o.append(i)}get#b(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#f(e);this.#o.append(e,this.#b);this.#l=t}addComment(t,e=null){if(this.#h)return;const i=t.renderForToolbar();if(!i)return;this.#f(i);const s=this.#d=this.#b;if(e){this.#o.insertBefore(i,e);this.#o.insertBefore(s,e)}else this.#o.append(i,s);this.#h=t;t.toolbar=this}addColorPicker(t){if(this.#r)return;this.#r=t;const e=t.renderButton();this.#f(e);this.#o.append(e,this.#b)}async addEditSignatureButton(t){const e=this.#c=await t.renderEditButton(this.#a);this.#f(e);this.#o.append(e,this.#b)}removeButton(t){if("comment"===t){this.#h?.removeToolbarCommentButton();this.#h=null;this.#d?.remove();this.#d=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 s=this.#o.querySelector(i);s&&"comment"===t&&this.addComment(e,s)}updateEditSignatureButton(t){this.#c&&(this.#c.title=t)}remove(){this.#n.remove();this.#r?.destroy();this.#r=null}}class FloatingToolbar{#o=null;#n=null;#y;constructor(t){this.#y=t}#A(){const t=this.#n=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");const e=this.#y._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",noContextMenu,{signal:e});const i=this.#o=document.createElement("div");i.className="buttons";t.append(i);this.#y.hasCommentManager()&&this.#v("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#y.commentSelection("floating_button")});this.#v("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#y.highlightSelection("floating_button")});return t}#w(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti){s=r;i=t}else e?r>s&&(s=r):r=1}static clearPointerType(){CurrentPointers.#T=null}static clearPointerIds(){CurrentPointers.#x=NaN;CurrentPointers.#C=null}static clearTimeStamp(){CurrentPointers.#E=NaN}}class IdManager{#S=0;get id(){return`${g}${this.#S++}`}}class ImageManager{#_=getUuid();#S=0;#P=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#D(t,e){this.#P||=new Map;let i=this.#P.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#_}_${this.#S++}`,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,s=new FileReader,n=new Image,r=new Promise((t,r)=>{n.onload=()=>{i.bitmap=n;i.isSvg=!0;t()};s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=s.onerror=r});s.readAsDataURL(t);await r}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#P.set(t,i);i&&this.#P.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#D(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#D(t,t)}async getFromBlob(t,e){const i=await e;return this.#D(t,i)}async getFromId(t){this.#P||=new Map;const e=this.#P.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.#P||=new Map;let i=this.#P.get(t);if(i?.bitmap){i.refCounter+=1;return i}const s=new OffscreenCanvas(e.width,e.height);s.getContext("2d").drawImage(e,0,0);i={bitmap:s.transferToImageBitmap(),id:`image_${this.#_}_${this.#S++}`,refCounter:1,isSvg:!1};this.#P.set(t,i);this.#P.set(i.id,i);return i}getSvgUrl(t){const e=this.#P.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#P||=new Map;const e=this.#P.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.#_}_`)}}class CommandManager{#M=[];#k=!1;#I;#F=-1;constructor(t=128){this.#I=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){s&&t();if(this.#k)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#F){this.#M.length>0&&(this.#M.length=0);this.#F=0;this.#M.push(o);return}if(r&&this.#M[this.#F].type===n){a&&(o.undo=this.#M[this.#F].undo);this.#M[this.#F]=o;return}const l=this.#F+1;if(l===this.#I)this.#M.splice(0,1);else{this.#F=l;l=0;e--)if(this.#M[e].type!==t){this.#M.splice(e+1,this.#F-e);this.#F=e;return}this.#M.length=0;this.#F=-1}}destroy(){this.#M=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#B(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.#B(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:r=[],checker:a=null}}=i;if(!a||a(t,e)){s.bind(t,...r,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!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 s=window.getComputedStyle(e).color;t.set(i,getRGB(s))}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{#R=new AbortController;#O=null;#L=null;#N=new Map;#U=new Map;#H=null;#z=null;#G=null;#W=null;#V=new CommandManager;#j=null;#$=null;#X=null;#q=0;#K=new Set;#Y=null;#Q=null;#J=new Set;_editorUndoBar=null;#Z=!1;#tt=!1;#et=!1;#it=null;#st=null;#nt=null;#rt=null;#at=!1;#ot=null;#lt=new IdManager;#ht=!1;#dt=!1;#ct=!1;#ut=null;#pt=null;#gt=null;#mt=null;#ft=null;#bt=m.NONE;#yt=new Set;#At=null;#vt=null;#wt=null;#xt=null;#Ct=null;#Et={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Tt=[0,0];#St=null;#_t=null;#Pt=null;#Dt=null;#Mt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#_t.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.#_t.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#_t.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,s,n,r,a,o,l,h,d,c,u,p,g,m){const f=this._signal=this.#R.signal;this.#_t=t;this.#Pt=e;this.#Dt=i;this.#z=s;this.#j=n;this.#vt=r;this.#Ct=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.#dt=!0},{capture:!0,signal:f});window.addEventListener("pointerup",()=>{this.#dt=!1},{capture:!0,signal:f});window.addEventListener("beforeunload",this.#kt.bind(this),{capture:!0,signal:f});this.#It();this.#Ft();this.#Bt();this.#G=o.annotationStorage;this.#it=o.filterFactory;this.#wt=l;this.#rt=h||null;this.#Z=d;this.#tt=c;this.#et=u;this.#ft=p||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=g||null;this._supportsPinchToZoom=!1!==m;n?.setSidebarUiManager(this)}destroy(){this.#Mt?.resolve();this.#Mt=null;this.#R?.abort();this.#R=null;this._signal=null;for(const t of this.#U.values())t.destroy();this.#U.clear();this.#N.clear();this.#J.clear();this.#mt?.clear();this.#O=null;this.#yt.clear();this.#V.destroy();this.#z?.destroy();this.#j?.destroy();this.#vt?.destroy();this.#ot?.hide();this.#ot=null;this.#gt?.destroy();this.#gt=null;this.#L=null;if(this.#st){clearTimeout(this.#st);this.#st=null}if(this.#St){clearTimeout(this.#St);this.#St=null}this._editorUndoBar?.destroy();this.#Ct=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#ft}get useNewAltTextFlow(){return this.#tt}get useNewAltTextWhenAddingImage(){return this.#et}get hcmFilter(){return shadow(this,"hcmFilter",this.#wt?this.#it.addHCMFilter(this.#wt.foreground,this.#wt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#_t).direction)}get _highlightColors(){return shadow(this,"_highlightColors",this.#rt?new Map(this.#rt.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.#wt;for(const[s,n]of t){const t=s.endsWith("_HCM");i&&t?e.set(s.replace("_HCM",""),n):i||t||e.set(s,n)}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.#X=t}setMainHighlightColorPicker(t){this.#gt=t}editAltText(t,e=!1){this.#z?.editAltText(this,t,e)}hasCommentManager(){return!!this.#j}editComment(t,e,i,s){this.#j?.showDialog(this,t,e,i,s)}selectComment(t,e){const i=this.#U.get(t),s=i?.getEditorByUID(e);s?.toggleComment(!0,!0)}updateComment(t){this.#j?.updateComment(t.getData())}updatePopupColor(t){this.#j?.updatePopupColor(t)}removeComment(t){this.#j?.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.#j?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#j?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#j?.dialogElement||null}async waitForEditorsRendered(t){if(this.#U.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.#vt?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#vt}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.#et=e}onPageChanging({pageNumber:t}){this.#q=t-1}deletePage(t){for(const e of this.getEditors(t))e.remove();this.#U.delete(t);this.#q===t&&(this.#q=0)}focusMainContainer(){this.#_t.focus()}findParent(t,e){for(const i of this.#U.values()){const{x:s,y:n,width:r,height:a}=i.div.getBoundingClientRect();if(t>=s&&t<=s+r&&e>=n&&e<=n+a)return i}return null}disableUserSelect(t=!1){this.#Pt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#J.add(t)}removeShouldRescale(t){this.#J.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#J)t.onScaleChanging();this.#X?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#Rt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Ot(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#U.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t="",e=!1){const i=document.getSelection();if(!i||i.isCollapsed)return;const{anchorNode:s,anchorOffset:n,focusNode:r,focusOffset:a}=i,o=i.toString(),l=this.#Rt(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();const d=this.#Ot(l),c=this.#bt===m.NONE,callback=()=>{const i=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:s,anchorOffset:n,focusNode:r,focusOffset:a,text:o});c&&this.showAllEditors("highlight",!0,!0);e&&i?.editComment()};c?this.switchToMode(m.HIGHLIGHT,callback):callback()}commentSelection(t=""){this.highlightSelection(t,!0)}#kt(t){this.commitOrRemove();this.currentLayer?.endDrawingSession(!1)}#Lt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Rt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#ot||=new FloatingToolbar(this);this.#ot.show(e,i,"ltr"===this.direction)}}getAndRemoveDataFromAnnotationStorage(t){if(!this.#G)return null;const e=`${g}${t}`,i=this.#G.getRawValue(e);i&&this.#G.remove(e);return i}addToAnnotationStorage(t){t.isEmpty()||!this.#G||this.#G.has(t.id)||this.#G.setValue(t.id,t)}a11yAlert(t,e=null){const i=this.#Dt;if(i){i.setAttribute("data-l10n-id",t);e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args")}}#Nt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#At){this.#ot?.hide();this.#At=null;this.#Ut({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#At)return;const i=this.#Rt(t).closest(".textLayer");if(i){this.#ot?.hide();this.#At=e;this.#Ut({hasSelectedText:!0});if(this.#bt===m.HIGHLIGHT||this.#bt===m.NONE){this.#bt===m.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#at=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#bt===m.HIGHLIGHT?this.#Ot(i):null;t?.toggleDrawing();if(this.#dt){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.#Ht("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:i});window.addEventListener("blur",pointerup,{signal:i})}else{t?.toggleDrawing(!0);this.#Ht("main_toolbar")}}}}else if(this.#At){this.#ot?.hide();this.#At=null;this.#Ut({hasSelectedText:!1})}}#Ht(t=""){this.#bt===m.HIGHLIGHT?this.highlightSelection(t):this.#Z&&this.#Lt()}#It(){document.addEventListener("selectionchange",this.#Nt.bind(this),{signal:this._signal})}#zt(){if(this.#nt)return;this.#nt=new AbortController;const t=this.combinedSignal(this.#nt);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Gt(){this.#nt?.abort();this.#nt=null}blur(){this.isShiftKeyDown=!1;if(this.#at){this.#at=!1;this.#Ht("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#yt)if(e.div.contains(t)){this.#pt=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#pt)return;const[t,e]=this.#pt;this.#pt=null;e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal});e.focus()}#Bt(){if(this.#ut)return;this.#ut=new AbortController;const t=this.combinedSignal(this.#ut);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Wt(){this.#ut?.abort();this.#ut=null}#Vt(){if(this.#$)return;this.#$=new AbortController;const t=this.combinedSignal(this.#$);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})}#jt(){this.#$?.abort();this.#$=null}#Ft(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Bt();this.setEditingState(!0)}removeEditListeners(){this.#Wt();this.setEditingState(!1)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#Q)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.#Q)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#O?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#yt){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.#Q)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 s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#$t(e);this.#Xt(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.#bt===m.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#at){this.#at=!1;this.#Ht("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}updatePageIndex(t,e){for(const i of this.getEditors(t))i.pageIndex=e;const i=this.#H.get(t);if(i){i.pageIndex=e;this.#U.set(e,i);this.#ht?i.enable():i.disable()}}startUpdatePages(){this.#H=new Map(this.#U);this.#U.clear()}endUpdatePages(){this.#H=null}clonePage(t,e){for(const i of this.getEditors(t)){const t=i.serialize(i.mode!==m.HIGHLIGHT);if(t){t.pageIndex=e;t.id=this.getId();t.isClone=!0;delete t.popupRef;this.#G.setValue(t.id,t)}}}findClonesForPage(t){const e=[],{pageIndex:i}=t;for(const[s,n]of this.#G)if(n.pageIndex===i&&n.isClone){this.#G.remove(s);e.push(t.deserialize(n).then(e=>{if(e){e.isClone=!0;t.addOrRebuild(e)}}))}return Promise.all(e)}#Ut(t){if(Object.entries(t).some(([t,e])=>this.#Et[t]!==e)){this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(this.#Et,t)});this.#bt===m.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#qt([[f.HIGHLIGHT_FREE,!0]])}}#qt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#zt();this.#Vt();this.#Ut({isEditing:this.#bt!==m.NONE,isEmpty:this.#Kt(),hasSomethingToUndo:this.#V.hasSomethingToUndo(),hasSomethingToRedo:this.#V.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Gt();this.#jt();this.#Ut({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#Q){this.#Q=t;for(const t of this.#Q)this.#qt(t.defaultPropertiesToUpdate)}}getId(){return this.#lt.id}get currentLayer(){return this.#U.get(this.#q)}getLayer(t){return this.#U.get(t)}get currentPageIndex(){return this.#q}addLayer(t){this.#U.set(t.pageIndex,t);this.#ht?t.enable():t.disable()}removeLayer(t){this.#U.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,s=!1,n=!1,r=!1){if(this.#bt!==t){if(this.#Mt){await this.#Mt.promise;if(!this.#Mt)return}this.#Mt=Promise.withResolvers();this.#X?.commitOrRemove();this.#bt===m.POPUP&&this.#j?.hideSidebar();this.#j?.destroyPopup();this.#bt=t;if(t!==m.NONE){for(const t of this.#N.values())t.addStandaloneCommentButton();t===m.SIGNATURE&&await(this.#vt?.loadSignatures());i&&CurrentPointers.clearPointerType();this.setEditingState(!0);await this.#Yt();this.unselectAll();for(const e of this.#U.values())e.updateMode(t);if(t===m.POPUP){this.#L||=await this.#Ct.getAnnotationsByType(new Set(this.#Q.map(t=>t._editorType)));const t=new Set,e=[];for(const i of this.#N.values()){const{annotationElementId:s,hasComment:n,deleted:r}=i;s&&t.add(s);n&&!r&&e.push(i.getData())}for(const i of this.#L){const{id:s,popupRef:n,contentsObj:r}=i;n&&r?.str&&!t.has(s)&&!this.#K.has(s)&&e.push(i)}this.#j?.showSidebar(e)}if(e){for(const t of this.#N.values())if(t.uid===e){this.setSelected(t);r?t.editComment():n?t.enterInEditMode():t.focus()}else t.unselect();this.#Mt.resolve()}else{s&&this.addNewEditorFromKeyboard();this.#Mt.resolve()}}else{this.setEditingState(!1);this.#Qt();for(const t of this.#N.values())t.hideStandaloneCommentButton();this._editorUndoBar?.hide();this.toggleComment(null);this.#Mt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#bt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#Q){switch(t){case f.CREATE:this.currentLayer.addNewEditor(e);return;case f.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#xt||=new Map).set(t,e);this.showAllEditors("highlight",e)}if(this.hasSelection)for(const i of this.#yt)i.updateParams(t,e);else for(const i of this.#Q)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#N.values())i.editorType===t&&i.show(e);(this.#xt?.get(f.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#qt([[f.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#ct!==t){this.#ct=t;for(const e of this.#U.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Yt(){if(!this.#ht){this.#ht=!0;const t=[];for(const e of this.#U.values())t.push(e.enable());await Promise.all(t);for(const t of this.#N.values())t.enable()}}#Qt(){this.unselectAll();if(this.#ht){this.#ht=!1;for(const t of this.#U.values())t.disable();for(const t of this.#N.values())t.disable()}}*getEditors(t){for(const e of this.#N.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#N.get(t)}addEditor(t){this.#N.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#st&&clearTimeout(this.#st);this.#st=setTimeout(()=>{this.focusMainContainer();this.#st=null},0)}this.#N.delete(t.id);t.annotationElementId&&this.#mt?.delete(t.annotationElementId);this.unselect(t);t.annotationElementId&&this.#K.has(t.annotationElementId)||this.#G?.remove(t.id)}addDeletedAnnotationElement(t){this.#K.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#K.has(t)}removeDeletedAnnotationElement(t){this.#K.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#$t(t){const e=this.#U.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#O!==t){this.#O=t;t&&this.#qt(t.propertiesToUpdate)}}get#Jt(){let t=null;for(t of this.#yt);return t}updateUI(t){this.#Jt===t&&this.#qt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#qt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#yt.has(t)){this.#yt.delete(t);t.unselect();this.#Ut({hasSelectedEditor:this.hasSelection})}else{this.#yt.add(t);t.select();this.#qt(t.propertiesToUpdate);this.#Ut({hasSelectedEditor:!0})}}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid});this.#X?.commitOrRemove();for(const e of this.#yt)e!==t&&e.unselect();this.#j?.destroyPopup();this.#yt.clear();this.#yt.add(t);t.select();this.#qt(t.propertiesToUpdate);this.#Ut({hasSelectedEditor:!0})}isSelected(t){return this.#yt.has(t)}get firstSelectedEditor(){return this.#yt.values().next().value}unselect(t){t.unselect();this.#yt.delete(t);this.#Ut({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#yt.size}get isEnterHandled(){return 1===this.#yt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#V.undo();this.#Ut({hasSomethingToUndo:this.#V.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Kt()});this._editorUndoBar?.hide()}redo(){this.#V.redo();this.#Ut({hasSomethingToUndo:!0,hasSomethingToRedo:this.#V.hasSomethingToRedo(),isEmpty:this.#Kt()})}addCommands(t){this.#V.add(t);this.#Ut({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Kt()})}cleanUndoStack(t){this.#V.cleanType(t)}#Kt(){if(0===this.#N.size)return!0;if(1===this.#N.size)for(const t of this.#N.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.#yt],undo=()=>{for(const t of e)this.#$t(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.#O?.commitOrRemove()}hasSomethingToControl(){return this.#O||this.hasSelection}#Xt(t){for(const t of this.#yt)t.unselect();this.#yt.clear();for(const e of t)if(!e.isEmpty()){this.#yt.add(e);e.select()}this.#Ut({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#yt)t.commit();this.#Xt(this.#N.values())}unselectAll(){if(this.#O){this.#O.commitOrRemove();if(this.#bt!==m.NONE)return}if(!this.#X?.commitOrRemove()){this.#j?.destroyPopup();if(this.hasSelection){for(const t of this.#yt)t.unselect();this.#yt.clear();this.#Ut({hasSelectedEditor:!1})}}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#Tt[0]+=t;this.#Tt[1]+=e;const[s,n]=this.#Tt,r=[...this.#yt];this.#St&&clearTimeout(this.#St);this.#St=setTimeout(()=>{this.#St=null;this.#Tt[0]=this.#Tt[1]=0;this.addCommands({cmd:()=>{for(const t of r)if(this.#N.has(t.id)){t.translateInPage(s,n);t.translationDone()}},undo:()=>{for(const t of r)if(this.#N.has(t.id)){t.translateInPage(-s,-n);t.translationDone()}},mustExec:!1})},1e3);for(const i of r){i.translateInPage(t,e);i.translationDone()}}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#Y=new Map;for(const t of this.#yt)this.#Y.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#Y)return!1;this.disableUserSelect(!1);const t=this.#Y;this.#Y=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},r]of t){r.newX=i;r.newY=s;r.newPageIndex=n;e||=i!==r.savedX||s!==r.savedY||n!==r.savedPageIndex}if(!e)return!1;const move=(t,e,i,s)=>{if(this.#N.has(t.id)){const n=this.#U.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n}]of t)move(e,i,s,n)},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#Y)for(const i of this.#Y.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.#yt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#O===t}getActive(){return this.#O}getMode(){return this.#bt}isEditingMode(){return this.#bt!==m.NONE}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/r,y:1-(t+a-i)/n,width:o/r,height:a/n});break;case"180":a=(t,e,a,o)=>({x:1-(t+a-i)/n,y:1-(e+o-s)/r,width:a/n,height:o/r});break;case"270":a=(t,e,a,o)=>({x:1-(e+o-s)/r,y:(t-i)/n,width:o/r,height:a/n});break;default:a=(t,e,a,o)=>({x:(t-i)/n,y:(e-s)/r,width:a/n,height:o/r})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation(),{signal:i});const onClick=t=>{t.preventDefault();this.#a._uiManager.editAltText(this.#a);this.#le&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#de}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",e=>{if(e.target===t&&"Enter"===e.key){this.#ne=!0;onClick(e)}},{signal:i});await this.#ce();return t}get#de(){return(this.#l?"added":null===this.#l&&this.guessedText&&"review")||"missing"}finish(){if(this.#te){this.#te.focus({focusVisible:this.#ne});this.#ne=!1}}isEmpty(){return this.#le?null===this.#l:!this.#l&&!this.#Zt}hasData(){return this.#le?null!==this.#l||!!this.#ae:this.isEmpty()}get guessedText(){return this.#ae}async setGuessedText(t){if(null===this.#l){this.#ae=t;this.#oe=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#ce()}}toggleAltTextBadge(t=!1){if(this.#le&&!this.#l){if(!this.#re){const t=this.#re=document.createElement("div");t.className="noAltTextBadge";this.#a.div.append(t)}this.#re.classList.toggle("hidden",!t)}else{this.#re?.remove();this.#re=null}}serialize(t){let e=this.#l;t||this.#ae!==e||(e=this.#oe);return{altText:e,decorative:this.#Zt,guessedText:this.#ae,textWithDisclaimer:this.#oe}}get data(){return{altText:this.#l,decorative:this.#Zt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){if(i){this.#ae=i;this.#oe=s}if(this.#l!==t||this.#Zt!==e){if(!n){this.#l=t;this.#Zt=e}this.#ce()}}toggle(t=!1){if(this.#te){if(!t&&this.#se){clearTimeout(this.#se);this.#se=null}this.#te.disabled=!t}}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#de}})}destroy(){this.#te?.remove();this.#te=null;this.#ee=null;this.#ie=null;this.#re?.remove();this.#re=null}async#ce(){const t=this.#te;if(!t)return;if(this.#le){t.classList.toggle("done",!!this.#l);t.setAttribute("data-l10n-id",AltText.#he[this.#de]);this.#ee?.setAttribute("data-l10n-id",AltText.#he[`${this.#de}-label`]);if(!this.#l){this.#ie?.remove();return}}else{if(!this.#l&&!this.#Zt){t.classList.remove("done");this.#ie?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#ie;if(!e){this.#ie=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",()=>{clearTimeout(this.#se);this.#se=null},{once:!0});t.addEventListener("mouseenter",()=>{this.#se=setTimeout(()=>{this.#se=null;this.#ie.classList.add("show");this.#a._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:s});t.addEventListener("mouseleave",()=>{if(this.#se){clearTimeout(this.#se);this.#se=null}this.#ie?.classList.remove("show")},{signal:s})}if(this.#Zt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#l}e.parentNode||t.append(e);const i=this.#a.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class Comment{#ue=null;#pe=null;#ge=!1;#a=null;#me=null;#fe=null;#be=null;#ye=null;#Ae=!1;#ve=null;constructor(t){this.#a=t}renderForToolbar(){const t=this.#pe=document.createElement("button");t.className="comment";return this.#A(t,!1)}renderForStandalone(){const t=this.#ue=document.createElement("button");t.className="annotationCommentButton";const e=this.#a.commentButtonPosition;if(e){const{style:i}=t;i.insetInlineEnd=`calc(${100*("ltr"===this.#a._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`;i.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const s=this.#a.commentButtonColor;s&&(i.backgroundColor=s)}return this.#A(t,!0)}focusButton(){setTimeout(()=>{(this.#ue??this.#pe)?.focus()},0)}onUpdatedColor(){if(!this.#ue)return;const t=this.#a.commentButtonColor;t&&(this.#ue.style.backgroundColor=t);this.#a._uiManager.updatePopupColor(this.#a)}get commentButtonWidth(){return(this.#ue?.getBoundingClientRect().width??0)/this.#a.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#ve)return this.#ve;if(!this.#ue)return null;const{x:t,y:e,height:i}=this.#ue.getBoundingClientRect(),{x:s,y:n,width:r,height:a}=this.#a.parent.boundingClientRect;return[(t-s)/r,(e+i-n)/a]}set commentPopupPositionInLayer(t){this.#ve=t}hasDefaultPopupPosition(){return null===this.#ve}removeStandaloneCommentButton(){this.#ue?.remove();this.#ue=null}removeToolbarCommentButton(){this.#pe?.remove();this.#pe=null}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#ue){this.#ue.classList.toggle("selected",t);this.#ue.ariaExpanded=e}}#A(t,e){if(!this.#a._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.#a._uiManager.getCommentDialogElement()];t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button")}const i=this.#a._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",noContextMenu,{signal:i});if(e){t.addEventListener("focusin",t=>{this.#a._focusEventsAllowed=!1;stopEvent(t)},{capture:!0,signal:i});t.addEventListener("focusout",t=>{this.#a._focusEventsAllowed=!0;stopEvent(t)},{capture:!0,signal:i})}t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const onClick=e=>{e.preventDefault();t===this.#pe?this.edit():this.#a.toggleComment(!0)};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});t.addEventListener("pointerenter",()=>{this.#a.toggleComment(!1,!0)},{signal:i});t.addEventListener("pointerleave",()=>{this.#a.toggleComment(!1,!1)},{signal:i});return t}edit(t){const e=this.commentPopupPositionInLayer;let i,s;if(e)[i,s]=e;else{[i,s]=this.#a.commentButtonPosition;const{width:t,height:e,x:n,y:r}=this.#a;i=n+i*t;s=r+s*e}const n=this.#a.parent.boundingClientRect,{x:r,y:a,width:o,height:l}=n;this.#a._uiManager.editComment(this.#a,r+i*o,a+s*l,{...t,parentDimensions:n})}finish(){if(this.#pe){this.#pe.focus({focusVisible:this.#ge});this.#ge=!1}}isDeleted(){return this.#Ae||""===this.#be}isEmpty(){return null===this.#be}hasBeenEdited(){return this.isDeleted()||this.#be!==this.#me}serialize(){return this.data}get data(){return{text:this.#be,richText:this.#fe,date:this.#ye,deleted:this.isDeleted()}}set data(t){t!==this.#be&&(this.#fe=null);if(null!==t){this.#be=t;this.#ye=new Date;this.#Ae=!1}else{this.#be="";this.#Ae=!0}}restoreData({text:t,richText:e,date:i}){this.#be=t;this.#fe=e;this.#ye=i;this.#Ae=!1}setInitialText(t,e=null){this.#me=t;this.data=t;this.#ye=null;this.#fe=e}shown(){}destroy(){this.#pe?.remove();this.#pe=null;this.#ue?.remove();this.#ue=null;this.#be="";this.#fe=null;this.#ye=null;this.#a=null;this.#ge=!1;this.#Ae=!1}}class TouchManager{#_t;#we=!1;#xe=null;#Ce;#Ee;#Te;#Se;#_e=null;#Pe;#De=null;#Me;#ke=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:r=null,signal:a}){this.#_t=t;this.#xe=i;this.#Ce=e;this.#Ee=s;this.#Te=n;this.#Se=r;this.#Me=new AbortController;this.#Pe=AbortSignal.any([a,this.#Me.signal]);t.addEventListener("touchstart",this.#Ie.bind(this),{passive:!1,signal:this.#Pe})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/OutputScale.pixelRatio}#Ie(t){if(this.#Ce?.())return;if(1===t.touches.length){if(this.#_e)return;const t=this.#_e=new AbortController,e=AbortSignal.any([this.#Pe,t.signal]),i=this.#_t,s={capture:!0,signal:e,passive:!1},cancelPointerDown=t=>{if("touch"===t.pointerType){this.#_e?.abort();this.#_e=null}};i.addEventListener("pointerdown",t=>{if("touch"===t.pointerType){stopEvent(t);cancelPointerDown(t)}},s);i.addEventListener("pointerup",cancelPointerDown,s);i.addEventListener("pointercancel",cancelPointerDown,s);return}if(!this.#ke){this.#ke=new AbortController;const t=AbortSignal.any([this.#Pe,this.#ke.signal]),e=this.#_t,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Fe.bind(this),i);const s=this.#Be.bind(this);e.addEventListener("touchend",s,i);e.addEventListener("touchcancel",s,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.#Ee?.()}stopEvent(t);if(2!==t.touches.length||this.#xe?.()){this.#De=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#De={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#Fe(t){if(!this.#De||2!==t.touches.length)return;stopEvent(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:r,screenY:a}=i,o=this.#De,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=r-s,m=a-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#we&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=s;o.touch0Y=n;o.touch1X=r;o.touch1Y=a;if(!this.#we){this.#we=!0;return}const y=[(s+r)/2,(n+a)/2];this.#Te?.(y,b,f)}#Be(t){if(!(t.touches.length>=2)){if(this.#ke){this.#ke.abort();this.#ke=null;this.#Se?.()}if(this.#De){stopEvent(t);this.#De=null;this.#we=!1}}}destroy(){this.#Me?.abort();this.#Me=null;this.#_e?.abort();this.#_e=null}}class AnnotationEditor{#Re=null;#Oe=null;#l=null;#h=null;#ue=null;#Le=!1;#Ne=null;#Ue="";#He=null;#ze=null;#Ge=null;#We=null;#Ve=null;#je="";#$e=!1;#Xe=null;#qe=!1;#Ke=!1;#Ye=!1;#Qe=null;#Je=0;#Ze=0;#ti=null;#ei=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;#ii=!1;#si=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:s,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[n,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._uiManager.getId(),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.#ii}set _isDraggable(t){this.#ii=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.#si}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else{this.#ni();this.#We?.remove();this.#We=null}this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#$e?this.#$e=!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,s){const[n,r]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.x=(t+i)/n;this.y=(e+s)/r;this.fixAndSetPosition()}_moveAfterPaste(t,e){if(this.isClone){delete this.isClone;return}const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s);this._onTranslated()}#ri([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s);this.x+=i/t;this.y+=s/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#ri(this.parentDimensions,t,e)}translateInPage(t,e){this.#Xe||=[this.x,this.y,this.width,this.height];this.#ri(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Xe||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;this.x+=t/s;this.y+=e/n;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.#Xe&&(this.#Xe[0]!==this.x||this.#Xe[1]!==this.y)}get _hasBeenResized(){return!!this.#Xe&&(this.#Xe[2]!==this.width||this.#Xe[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:r,width:a,height:o}=this;a*=i;o*=s;n*=i;r*=s;if(this._mustFixPosition)switch(t){case 0:n=MathClamp(n,0,i-a);r=MathClamp(r,0,s-o);break;case 90:n=MathClamp(n,0,i-o);r=MathClamp(r,a,s);break;case 180:n=MathClamp(n,a,i);r=MathClamp(r,o,s);break;case 270:n=MathClamp(n,o,i);r=MathClamp(r,0,s-a)}this.x=n/=i;this.y=r/=s;const[l,h]=this.getBaseTranslation();n+=l;r+=h;e.left=`${(100*n).toFixed(2)}%`;e.top=`${(100*r).toFixed(2)}%`;this.moveInDOM()}static#ai(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.#ai(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#ai(t,e,360-this.parentRotation)}#oi(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]}#li(){if(this.#He)return;this.#He=document.createElement("div");this.#He.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.#He.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#hi.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#He)}#hi(t,e){e.preventDefault();const{isMac:i}=FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#l?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;this.#ze=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#di.bind(this,t),{passive:!0,capture:!0,signal:r});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:r});window.addEventListener("contextmenu",noContextMenu,{signal:r});this.#Ge={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=()=>{n.abort();this.parent.togglePointerEvents(!0);this.#l?.toggle(!0);this._isDraggable=s;this.parent.div.style.cursor=a;this.div.style.cursor=o;this.#ci()};window.addEventListener("pointerup",pointerUpCallback,{signal:r});window.addEventListener("blur",pointerUpCallback,{signal:r})}#ui(t,e,i,s){this.width=i;this.height=s;this.x=t;this.y=e;this.setDims();this.fixAndSetPosition();this._onResized()}_onResized(){}#ci(){if(!this.#Ge)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#Ge;this.#Ge=null;const n=this.x,r=this.y,a=this.width,o=this.height;n===t&&r===e&&a===i&&o===s||this.addCommands({cmd:this.#ui.bind(this,n,r,a,o),undo:this.#ui.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#di(t,e){const[i,s]=this.parentDimensions,n=this.x,r=this.y,a=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/s,d=this.#oi(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#oi(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 y=transf(...b);const A=AnnotationEditor._round(n+y[0]),v=AnnotationEditor._round(r+y[1]);let w,x,C=1,E=1;if(e.fromKeyboard)({deltaX:w,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#ze;[w,x]=this.screenToPageTranslation(t-s,i-n);this.#ze[0]=t;this.#ze[1]=i}[w,x]=(T=w/i,S=x/s,[c[0]*T+c[2]*S,c[1]*T+c[3]*S]);var T,S;if(g){const t=Math.hypot(a,o);C=E=Math.max(Math.min(Math.hypot(b[0]-f[0]-w,b[1]-f[1]-x)/t,1/a,1/o),l/a,h/o)}else m?C=MathClamp(Math.abs(b[0]-f[0]-w),l,1)/a:E=MathClamp(Math.abs(b[1]-f[1]-x),h,1)/o;const _=AnnotationEditor._round(a*C),P=AnnotationEditor._round(o*E);y=transf(...p(_,P));const D=A-y[0],M=v-y[1];this.#Xe||=[this.x,this.y,this.width,this.height];this.width=_;this.height=P;this.x=D;this.y=M;this.setDims();this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#l?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#Ke)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.#l?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){if(!this.#l){AltText.initialize(AnnotationEditor._l10n);this.#l=new AltText(this);if(this.#Re){this.#l.data=this.#Re;this.#Re=null}}return this.#l}get altTextData(){return this.#l?.data}set altTextData(t){this.#l&&(this.#l.data=t)}get guessedAltText(){return this.#l?.guessedText}async setGuessedAltText(t){await(this.#l?.setGuessedText(t))}serializeAltText(t){return this.#l?.serialize(t)}hasAltText(){return!!this.#l&&!this.#l.isEmpty()}hasAltTextData(){return this.#l?.hasData()??!1}focusCommentButton(){this.#h?.focusButton()}addCommentButton(){return this.canAddComment?this.#h||=new Comment(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager())if(this.#ue)this._uiManager.isEditingMode()&&this.#ue.classList.remove("hidden");else if(this.hasComment){this.#ue=this.#h.renderForStandalone();this.div.append(this.#ue)}}removeStandaloneCommentButton(){this.#h.removeStandaloneCommentButton();this.#ue=null}hideStandaloneCommentButton(){this.#ue?.classList.add("hidden")}get comment(){if(!this.#h)return null;const{data:{richText:t,text:e,date:i,deleted:s}}=this.#h;return{text:e,richText:t,date:i,deleted:s,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#h||=new Comment(this);"object"==typeof t&&null!==t?this.#h.restoreData(t):this.#h.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.#h||=new Comment(this);this.#h.setInitialText(t,i);if(!this.annotationElementId)return;const s=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);s&&this.updateFromAnnotationLayer(s)}get hasEditedComment(){return this.#h?.hasBeenEdited()}get hasDeletedComment(){return this.#h?.isDeleted()}get hasComment(){return!!this.#h&&!this.#h.isEmpty()&&!this.#h.isDeleted()}async editComment(t){this.#h||=new Comment(this);this.#h.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#h.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,i=100,[,,,s]=t.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,a=r+n+1,o=s-i,l=a+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,o,l,s]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#h.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.#Le?-1:0;t.setAttribute("role","application");this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId);this._isVisible||t.classList.add("hidden");this.setInForeground();this.#pi();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[s,n]=this.getInitialTranslation();this.translate(s,n);bindEvents(this,t,["keydown","pointerdown","dblclick"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#ei||=new TouchManager({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#gi.bind(this),onPinching:this.#mi.bind(this),onPinchEnd:this.#fi.bind(this),signal:this._uiManager._signal}));this.addStandaloneCommentButton();this._uiManager._editorUndoBar?.hide();return t}#gi(){this.#Ge={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#l?.toggle(!1);this.parent.togglePointerEvents(!1)}#mi(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#oi(this.rotation),transf=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[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;s=Math.max(Math.min(s,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*s),g=AnnotationEditor._round(d*s);if(p===h&&g===d)return;this.#Xe||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),y=transf(p/2,g/2);this.x=f-y[0];this.y=b-y[1];this.width=p;this.height=g;this.setDims();this.fixAndSetPosition();this._onResizing()}#fi(){this.#l?.toggle(!0);this.parent.togglePointerEvents(!0);this.#ci()}pointerdown(t){const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#$e=!0;this._isDraggable?this.#bi(t):this.#yi(t)}}#yi(t){const{isMac:e}=FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#bi(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),r={capture:!0,passive:!1,signal:n},cancelDrag=t=>{s.abort();this.#Ne=null;this.#$e=!1;this._uiManager.endDragSession()||this.#yi(t);i&&this._onStopDragging()};if(e){this.#Je=t.clientX;this.#Ze=t.clientY;this.#Ne=t.pointerId;this.#Ue=t.pointerType;window.addEventListener("pointermove",t=>{if(!i){i=!0;this._uiManager.toggleComment(this,!0,!1);this._onStartDragging()}const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#Ne){stopEvent(t);return}const[r,a]=this.screenToPageTranslation(e-this.#Je,s-this.#Ze);this.#Je=e;this.#Ze=s;this._uiManager.dragSelectedEditors(r,a)},r);window.addEventListener("touchmove",stopEvent,r);window.addEventListener("pointerdown",t=>{t.pointerType===this.#Ue&&(this.#ei||t.isPrimary)&&cancelDrag(t);stopEvent(t)},r)}const pointerUpCallback=t=>{this.#Ne&&this.#Ne!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Qe&&clearTimeout(this.#Qe);this.#Qe=setTimeout(()=>{this.#Qe=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 s=this.parentScale,[n,r]=this.pageDimensions,[a,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*r,u=this.width*n,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,s,n,r]=t,a=n-i,o=r-s;switch(this.rotation){case 0:return[i,e-r,a,o];case 90:return[i,e-s,o,a];case 180:return[n,e-s,a,o];case 270:return[n,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.#h?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:i,opacity:s,deleted:n,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:!n,color:e,opacity:s}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){if(this.isInEditMode())return!1;this.parent.setEditingState(!1);this.#Ke=!0;return!0}disableEditMode(){if(!this.isInEditMode())return!1;this.parent.setEditingState(!0);this.#Ke=!1;return!0}isInEditMode(){return this.#Ke}shouldGetKeyboardEvents(){return this.#Ye}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e0&&t0}#pi(){if(this.#Ve||!this.div)return;this.#Ve=new AbortController;const t=this._uiManager.combinedSignal(this.#Ve);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#pi()}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 s=new this.prototype.constructor({parent:e,id:i.getId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});s.rotation=t.rotation;s.#Re=t.accessibilityData;s._isCopy=t.isCopy||!1;const[n,r]=s.pageDimensions,[a,o,l,h]=s.getRectInCurrentCoords(t.rect,r);s.x=a/n;s.y=o/r;s.width=l/n;s.height=h/r;return s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#Ve?.abort();this.#Ve=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);this.hideCommentPopup();if(this.#Qe){clearTimeout(this.#Qe);this.#Qe=null}this.#ni();this.removeEditToolbar();if(this.#ti){for(const t of this.#ti.values())clearTimeout(t);this.#ti=null}this.parent=null;this.#ei?.destroy();this.#ei=null;this.#We?.remove();this.#We=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#li();this.#He.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,s,n,r]=this.getPDFRect();return[AnnotationEditor._round(i+(n-i)*t),AnnotationEditor._round(s+(r-s)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#h.commentPopupPositionInLayer}set commentPopupPosition(t){this.#h.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#h.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#h.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#h?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#Ge={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#He.children;if(!this.#Oe){this.#Oe=Array.from(e);const t=this.#Ai.bind(this),i=this.#vi.bind(this),s=this._uiManager._signal;for(const e of this.#Oe){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:s});e.addEventListener("blur",i,{signal:s});e.addEventListener("focus",this.#wi.bind(this,n),{signal:s});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const i=this.#Oe[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Oe.length/4);if(n!==s){if(ns)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.#He?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#l?.toggleAltTextBadge(!0);this.hideCommentPopup()}}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,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.#qe}set isEditing(t){this.#qe=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.#ti||=new Map;const{action:e}=t;let i=this.#ti.get(e);i&&clearTimeout(i);i=setTimeout(()=>{this._reportTelemetry(t);this.#ti.delete(e);0===this.#ti.size&&(this.#ti=null)},AnnotationEditor._telemetryTimeout);this.#ti.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.#Le=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#Le=!0}updateFakeAnnotationElement(t){if(this.#We||this.deleted)if(this.deleted){this.#We.remove();this.#We=null}else(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#We.updateEdited({rect:this.getPDFRect(),popup:this.comment});else this.#We=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 X=3285377520,q=4294901760,K=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:X;this.h2=t?4294967295&t:X}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let s=0,n=t.length;s>>8;e[i++]=255&n}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const s=i>>2,n=i-4*s,r=new Uint32Array(e.buffer,0,s);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&q|a*p&K;l^=a;l=l<<13|l>>>19;l=5*l+3864292196}else{o=r[t];o=o*d&q|o*u&K;o=o<<15|o>>>17;o=o*c&q|o*p&K;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}a=0;switch(n){case 3:a^=e[4*s+2]<<16;case 2:a^=e[4*s+1]<<8;case 1:a^=e[4*s];a=a*d&q|a*u&K;a=a<<15|a>>>17;a=a*c&q|a*p&K;1&s?l^=a:h^=a}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&q|36045*t&K;e=4283543511*e&q|(2950163797*(e<<16|t>>>16)&q)>>>16;t^=e>>>1;t=444984403*t&q|60499*t&K;e=3301882366*e&q|(3120437893*(e<<16|t>>>16)&q)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Y=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Ci=!1;#Ei=null;#Ti=null;#Si=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(t,e){const i=this.#Si.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Si.get(t)}remove(t){const e=this.#Si.get(t);if(void 0!==e){e instanceof AnnotationEditor&&this.#Ti.delete(e.annotationElementId);this.#Si.delete(t);0===this.#Si.size&&this.resetModified();this.#Si.values().some(t=>t instanceof AnnotationEditor)||this.onAnnotationEditor?.(null)}}setValue(t,e){const i=this.#Si.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#Si.set(t,e)}s&&this.#_i();if(e instanceof AnnotationEditor){(this.#Ti||=new Map).set(e.annotationElementId,e);this.onAnnotationEditor?.(e.constructor._type)}}has(t){return this.#Si.has(t)}get size(){return this.#Si.size}#_i(){if(!this.#Ci){this.#Ci=!0;this.onSetModified?.()}}resetModified(){if(this.#Ci){this.#Ci=!1;this.onResetModified?.()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Si.size)return Y;const t=new Map,e=new MurmurHash3_64,i=[],s=Object.create(null);let n=!1;for(const[i,r]of this.#Si){const a=r instanceof AnnotationEditor?r.serialize(!1,s):r;if(r.page){r.pageIndex=r.page._pageIndex;delete r.page}if(a){t.set(i,a);e.update(`${i}:${JSON.stringify(a)}`);n||=!!a.bitmap}}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:Y}get editorStats(){let t=null;const e=new Map;let i=0,s=0;for(const n of this.#Si.values()){if(!(n instanceof AnnotationEditor)){n.popup&&(n.popup.deleted?s+=1:i+=1);continue}n.isCommentDeleted?s+=1:n.hasEditedComment&&(i+=1);const r=n.telemetryFinalData;if(!r)continue;const{type:a}=r;e.has(a)||e.set(a,Object.getPrototypeOf(n).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(s>0||i>0){t||=Object.create(null);t.comments={deleted:s,edited:i}}if(!t)return null;for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Ei=null}updateEditor(t,e){const i=this.#Ti?.get(t);if(i){i.updateFromAnnotationLayer(e);return!0}return!1}getEditor(t){return this.#Ti?.get(t)||null}get modifiedIds(){if(this.#Ei)return this.#Ei;const t=[];if(this.#Ti)for(const e of this.#Ti.values())e.serialize()&&t.push(e.annotationElementId);let e="";if(t.length){const i=new MurmurHash3_64;i.update(t.join(","));e=i.hexdigest()}return this.#Ei={ids:new Set(t),hash:e}}[Symbol.iterator](){return this.#Si.entries()}}class PrintAnnotationStorage extends AnnotationStorage{#Pi=Y;constructor(t){super();const{serializable:e}=t;if(e===Y)return;const{map:i,hash:s,transfer:n}=e,r=structuredClone(i,n?{transfer:n}:null);this.#Pi={map:r,hash:s,transfer:[]}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Pi}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}const Q="__forcedDependency",{floor:J,ceil:Z}=Math;function expandBBox(t,e,i,s,n,r){t[4*e+0]=Math.min(t[4*e+0],i);t[4*e+1]=Math.min(t[4*e+1],s);t[4*e+2]=Math.max(t[4*e+2],n);t[4*e+3]=Math.max(t[4*e+3],r)}const tt=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class BBoxReader{#Di;#Mi;constructor(t,e){this.#Di=t;this.#Mi=e}get length(){return this.#Di.length}isEmpty(t){return this.#Di[t]===tt}minX(t){return this.#Mi[4*t+0]/256}minY(t){return this.#Mi[4*t+1]/256}maxX(t){return(this.#Mi[4*t+2]+1)/256}maxY(t){return(this.#Mi[4*t+3]+1)/256}}const ensureDebugMetadata=(t,e)=>t?.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));class CanvasBBoxTracker{#ki=[[1,0,0,1,0,0]];#Ii=[-1/0,-1/0,1/0,1/0];#Fi=new Float64Array(e);_pendingBBoxIdx=-1;#Bi;#Ri;#Oi;#Di;_savesStack=[];_markedContentStack=[];constructor(t,e){this.#Bi=t.width;this.#Ri=t.height;this.#Li(e)}growOperationsCount(t){t>=this.#Di.length&&this.#Li(t,this.#Di)}#Li(t,e){const i=new ArrayBuffer(4*t);this.#Oi=new Uint8ClampedArray(i);this.#Di=new Uint32Array(i);if(e&&e.length>0){this.#Di.set(e);this.#Di.fill(tt,e.length)}else this.#Di.fill(tt)}get clipBox(){return this.#Ii}save(t){this.#Ii={__proto__:this.#Ii};this._savesStack.push(t);return this}restore(t,e){const i=Object.getPrototypeOf(this.#Ii);if(null===i)return this;this.#Ii=i;const s=this._savesStack.pop();if(void 0!==s){e?.(s,t);this.#Di[t]=this.#Di[s]}return this}recordOpenMarker(t){this._savesStack.push(t);return this}getOpenMarker(){return 0===this._savesStack.length?null:this._savesStack.at(-1)}recordCloseMarker(t,e){const i=this._savesStack.pop();if(void 0!==i){e?.(i,t);this.#Di[t]=this.#Di[i]}return this}beginMarkedContent(t){this._markedContentStack.push(t);return this}endMarkedContent(t,e){const i=this._markedContentStack.pop();if(void 0!==i){e?.(i,t);this.#Di[t]=this.#Di[i]}return this}pushBaseTransform(t){this.#ki.push(Util.multiplyByDOMMatrix(this.#ki.at(-1),t.getTransform()));return this}popBaseTransform(){this.#ki.length>1&&this.#ki.pop();return this}resetBBox(t){if(this._pendingBBoxIdx!==t){this._pendingBBoxIdx=t;this.#Fi.set(e,0)}return this}recordClipBox(t,i,s,n,r,a){const o=Util.multiplyByDOMMatrix(this.#ki.at(-1),i.getTransform()),l=e.slice();Util.axialAlignedBoundingBox([s,r,n,a],o,l);const h=Util.intersect(this.#Ii,l);if(h){this.#Ii[0]=h[0];this.#Ii[1]=h[1];this.#Ii[2]=h[2];this.#Ii[3]=h[3]}else{this.#Ii[0]=this.#Ii[1]=1/0;this.#Ii[2]=this.#Ii[3]=-1/0}return this}recordBBox(t,i,s,n,r,a){const o=this.#Ii;if(o[0]===1/0)return this;const l=Util.multiplyByDOMMatrix(this.#ki.at(-1),i.getTransform());if(o[0]===-1/0){Util.axialAlignedBoundingBox([s,r,n,a],l,this.#Fi);return this}const h=e.slice();Util.axialAlignedBoundingBox([s,r,n,a],l,h);this.#Fi[0]=MathClamp(h[0],o[0],this.#Fi[0]);this.#Fi[1]=MathClamp(h[1],o[1],this.#Fi[1]);this.#Fi[2]=MathClamp(h[2],this.#Fi[2],o[2]);this.#Fi[3]=MathClamp(h[3],this.#Fi[3],o[3]);return this}recordFullPageBBox(t){this.#Fi[0]=Math.max(0,this.#Ii[0]);this.#Fi[1]=Math.max(0,this.#Ii[1]);this.#Fi[2]=Math.min(this.#Bi,this.#Ii[2]);this.#Fi[3]=Math.min(this.#Ri,this.#Ii[3]);return this}recordOperation(t,e=!1,i){if(this._pendingBBoxIdx!==t)return this;const s=J(256*this.#Fi[0]/this.#Bi),n=J(256*this.#Fi[1]/this.#Ri),r=Z(256*this.#Fi[2]/this.#Bi),a=Z(256*this.#Fi[3]/this.#Ri);expandBBox(this.#Oi,t,s,n,r,a);if(i)for(const e of i)for(const i of e)i!==t&&expandBBox(this.#Oi,i,s,n,r,a);e||(this._pendingBBoxIdx=-1);return this}bboxToClipBoxDropOperation(t){if(this._pendingBBoxIdx===t){this._pendingBBoxIdx=-1;this.#Ii[0]=Math.max(this.#Ii[0],this.#Fi[0]);this.#Ii[1]=Math.max(this.#Ii[1],this.#Fi[1]);this.#Ii[2]=Math.min(this.#Ii[2],this.#Fi[2]);this.#Ii[3]=Math.min(this.#Ii[3],this.#Fi[3])}return this}take(){return new BBoxReader(this.#Di,this.#Oi)}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(t,e){return this}recordIncrementalData(t,e){return this}resetIncrementalData(t,e){return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){return this}recordFutureForcedDependency(t,e){return this}inheritSimpleDataAsFutureForcedDependencies(t){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(t,e,i,s=1,n=0,r=0,a){return this}getSimpleIndex(t){}recordDependencies(t,e){return this}recordNamedDependency(t,e){return this}recordShowTextOperation(t,e=!1){return this}}class CanvasDependencyTracker{#Ni={__proto__:null};#Ui={__proto__:null,transform:[],moveText:[],sameLineText:[],[Q]:[]};#Hi=new Map;#zi=new Set;#Gi=new Map;#Wi;#Vi;#ji;constructor(t,e=!1){this.#ji=t;if(e){this.#Wi=new Map;this.#Vi=(t,e)=>{ensureDebugMetadata(this.#Wi,e).dependencies.add(t)}}}get clipBox(){return this.#ji.clipBox}growOperationsCount(t){this.#ji.growOperationsCount(t)}save(t){this.#Ni={__proto__:this.#Ni};this.#Ui={__proto__:this.#Ui,transform:{__proto__:this.#Ui.transform},moveText:{__proto__:this.#Ui.moveText},sameLineText:{__proto__:this.#Ui.sameLineText},[Q]:{__proto__:this.#Ui[Q]}};this.#ji.save(t);return this}restore(t){this.#ji.restore(t,this.#Vi);const e=Object.getPrototypeOf(this.#Ni);if(null===e)return this;this.#Ni=e;this.#Ui=Object.getPrototypeOf(this.#Ui);return this}recordOpenMarker(t){this.#ji.recordOpenMarker(t,this.#Vi);return this}getOpenMarker(){return this.#ji.getOpenMarker()}recordCloseMarker(t){this.#ji.recordCloseMarker(t,this.#Vi);return this}beginMarkedContent(t){this.#ji.beginMarkedContent(t);return this}endMarkedContent(t){this.#ji.endMarkedContent(t,this.#Vi);return this}pushBaseTransform(t){this.#ji.pushBaseTransform(t);return this}popBaseTransform(){this.#ji.popBaseTransform();return this}recordSimpleData(t,e){this.#Ni[t]=e;return this}recordIncrementalData(t,e){this.#Ui[t].push(e);return this}resetIncrementalData(t,e){this.#Ui[t].length=0;return this}recordNamedData(t,e){this.#Hi.set(t,e);return this}recordSimpleDataFromNamed(t,e,i){this.#Ni[t]=this.#Hi.get(e)??i}recordFutureForcedDependency(t,e){this.recordIncrementalData(Q,e);return this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Ni&&this.recordFutureForcedDependency(e,this.#Ni[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#zi)this.recordFutureForcedDependency(Q,t);return this}resetBBox(t){this.#ji.resetBBox(t);return this}recordClipBox(t,e,i,s,n,r){this.#ji.recordClipBox(t,e,i,s,n,r);return this}recordBBox(t,e,i,s,n,r){this.#ji.recordBBox(t,e,i,s,n,r);return this}recordCharacterBBox(t,e,i,s=1,n=0,r=0,a){const o=i.bbox;let l,h;if(o){l=o[2]!==o[0]&&o[3]!==o[1]&&this.#Gi.get(i);if(!1!==l){h=[0,0,0,0];Util.axialAlignedBoundingBox(o,i.fontMatrix,h);1===s&&0===n&&0===r||Util.scaleMinMax([s,0,0,-s,n,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]<=n-d.actualBoundingBoxLeft&&h[2]>=n+d.actualBoundingBoxRight&&h[1]<=r-d.actualBoundingBoxAscent&&h[3]>=r+d.actualBoundingBoxDescent;this.#Gi.set(i,l);if(l)return this.recordBBox(t,e,h[0],h[2],h[1],h[3])}return this.recordBBox(t,e,n-d.actualBoundingBoxLeft,n+d.actualBoundingBoxRight,r-d.actualBoundingBoxAscent,r+d.actualBoundingBoxDescent)}recordFullPageBBox(t){this.#ji.recordFullPageBBox(t);return this}getSimpleIndex(t){return this.#Ni[t]}recordDependencies(t,e){const i=this.#zi,s=this.#Ni,n=this.#Ui;for(const t of e)t in this.#Ni?i.add(s[t]):t in n&&n[t].forEach(i.add,i);return this}recordNamedDependency(t,e){this.#Hi.has(e)&&this.#zi.add(this.#Hi.get(e));return this}recordOperation(t,e=!1){this.recordDependencies(t,[Q]);if(this.#Wi){const e=ensureDebugMetadata(this.#Wi,t),{dependencies:i}=e;this.#zi.forEach(i.add,i);this.#ji._savesStack.forEach(i.add,i);this.#ji._markedContentStack.forEach(i.add,i);i.delete(t);e.isRenderingOperation=!0}const i=!e&&t===this.#ji._pendingBBoxIdx;this.#ji.recordOperation(t,e,[this.#zi,this.#ji._savesStack,this.#ji._markedContentStack]);i&&this.#zi.clear();return this}recordShowTextOperation(t,e=!1){const i=Array.from(this.#zi);this.recordOperation(t,e);this.recordIncrementalData("sameLineText",t);for(const t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){const i=!e&&t===this.#ji._pendingBBoxIdx;this.#ji.bboxToClipBoxDropOperation(t);i&&this.#zi.clear();return this}take(){this.#Gi.clear();return this.#ji.take()}takeDebugMetadata(){return this.#Wi}}class CanvasNestedDependencyTracker{#$i;#Xi;#qi;#Ki=0;#Yi=0;constructor(t,e,i){if(t instanceof CanvasNestedDependencyTracker&&t.#qi===!!i)return t;this.#$i=t;this.#Xi=e;this.#qi=!!i}get clipBox(){return this.#$i.clipBox}growOperationsCount(){throw new Error("Unreachable")}save(t){this.#Yi++;this.#$i.save(this.#Xi);return this}restore(t){if(this.#Yi>0){this.#$i.restore(this.#Xi);this.#Yi--}return this}recordOpenMarker(t){this.#Ki++;return this}getOpenMarker(){return this.#Ki>0?this.#Xi:this.#$i.getOpenMarker()}recordCloseMarker(t){this.#Ki--;return this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){this.#$i.pushBaseTransform(t);return this}popBaseTransform(){this.#$i.popBaseTransform();return this}recordSimpleData(t,e){this.#$i.recordSimpleData(t,this.#Xi);return this}recordIncrementalData(t,e){this.#$i.recordIncrementalData(t,this.#Xi);return this}resetIncrementalData(t,e){this.#$i.resetIncrementalData(t,this.#Xi);return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){this.#$i.recordSimpleDataFromNamed(t,e,this.#Xi);return this}recordFutureForcedDependency(t,e){this.#$i.recordFutureForcedDependency(t,this.#Xi);return this}inheritSimpleDataAsFutureForcedDependencies(t){this.#$i.inheritSimpleDataAsFutureForcedDependencies(t);return this}inheritPendingDependenciesAsFutureForcedDependencies(){this.#$i.inheritPendingDependenciesAsFutureForcedDependencies();return this}resetBBox(t){this.#qi||this.#$i.resetBBox(this.#Xi);return this}recordClipBox(t,e,i,s,n,r){this.#qi||this.#$i.recordClipBox(this.#Xi,e,i,s,n,r);return this}recordBBox(t,e,i,s,n,r){this.#qi||this.#$i.recordBBox(this.#Xi,e,i,s,n,r);return this}recordCharacterBBox(t,e,i,s,n,r,a){this.#qi||this.#$i.recordCharacterBBox(this.#Xi,e,i,s,n,r,a);return this}recordFullPageBBox(t){this.#qi||this.#$i.recordFullPageBBox(this.#Xi);return this}getSimpleIndex(t){return this.#$i.getSimpleIndex(t)}recordDependencies(t,e){this.#$i.recordDependencies(this.#Xi,e);return this}recordNamedDependency(t,e){this.#$i.recordNamedDependency(this.#Xi,e);return this}recordOperation(t){this.#$i.recordOperation(this.#Xi,!0);return this}recordShowTextOperation(t){this.#$i.recordShowTextOperation(this.#Xi,!0);return this}bboxToClipBoxDropOperation(t){this.#qi||this.#$i.bboxToClipBoxDropOperation(this.#Xi,!0);return this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const et=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],it=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],st=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],nt=["filter","fillColor","fillAlpha"],rt=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],at=["transform"],ot=["transform","fillColor"];class CanvasImagesTracker{#Bi;#Ri;#Qi=4;#Ji=0;#Mi=new CanvasImagesTracker.#Zi(6*this.#Qi);static#Zi=FeatureTest.isFloat16ArraySupported?Float16Array:Float32Array;constructor(t){this.#Bi=t.width;this.#Ri=t.height}record(t,i,s,n){if(this.#Ji===this.#Qi){this.#Qi*=2;const t=new CanvasImagesTracker.#Zi(6*this.#Qi);t.set(this.#Mi);this.#Mi=t}const r=Util.domMatrixToTransform(t.getTransform());let a;if(n[0]!==1/0){const t=e.slice();Util.axialAlignedBoundingBox([0,-s,i,0],r,t);const o=Util.intersect(n,t);if(!o)return;const[l,h,d,c]=o;if(l!==t[0]||h!==t[1]||d!==t[2]||c!==t[3]){const t=Math.atan2(r[1],r[0]),e=Math.abs(Math.sin(t)),i=Math.abs(Math.cos(t));if(e<1e-6||i<1e-6||Math.abs(e-i)<1e-6)a=[l,h,l,c,d,h];else{const t=d-l,s=c-h,n=e*e,r=i*i,o=i*e,u=r-n,p=(s*r-t*o)/u;a=[l+(s*o-t*n)/u,h,l,h+p,d,c-p]}}}if(!a){a=[0,-s,0,0,i,-s];Util.applyTransform(a,r,0);Util.applyTransform(a,r,2);Util.applyTransform(a,r,4)}a[0]/=this.#Bi;a[1]/=this.#Ri;a[2]/=this.#Bi;a[3]/=this.#Ri;a[4]/=this.#Bi;a[5]/=this.#Ri;this.#Mi.set(a,6*this.#Ji);this.#Ji++}take(){return this.#Mi.subarray(0,6*this.#Ji)}}class FontLoader{#ts=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.#ts.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#ts.has(t.loadedName)){assert(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:e,src:s,style:n}=t,r=new FontFace(e,s,n);this.addNativeFontFace(r);try{await r.load();this.#ts.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,s){return t.substring(0,e)+s+t.substring(e+i)}let i,s;const n=this._document.createElement("canvas");n.width=1;n.height=1;const r=n.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,s=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{compiledGlyphs=Object.create(null);#es;constructor(t,e=null,i,s){this.#es=t;this._inspectFont=e;i&&(this.charProcOperatorList=i);s&&Object.assign(this,s)}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 s;try{s=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=makePathFromDrawOPS(s?.path);this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=n}get black(){return this.#es.black}get bold(){return this.#es.bold}get disableFontFace(){return this.#es.disableFontFace}set disableFontFace(t){shadow(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#es.fontExtraProperties}get isInvalidPDFjsFont(){return this.#es.isInvalidPDFjsFont}get isType3Font(){return this.#es.isType3Font}get italic(){return this.#es.italic}get missingFile(){return this.#es.missingFile}get remeasure(){return this.#es.remeasure}get vertical(){return this.#es.vertical}get ascent(){return this.#es.ascent}get defaultWidth(){return this.#es.defaultWidth}get descent(){return this.#es.descent}get bbox(){return this.#es.bbox}get fontMatrix(){return this.#es.fontMatrix}get fallbackName(){return this.#es.fallbackName}get loadedName(){return this.#es.loadedName}get mimetype(){return this.#es.mimetype}get name(){return this.#es.name}get data(){return this.#es.data}clearData(){this.#es.clearData()}get cssFontInfo(){return this.#es.cssFontInfo}get systemFontInfo(){return this.#es.systemFontInfo}get defaultVMetrics(){return this.#es.defaultVMetrics}}class CSS_FONT_INFO{static strings=["fontFamily","fontWeight","italicAngle"]}class SYSTEM_FONT_INFO{static strings=["css","loadedName","baseFontName","src"]}class FONT_INFO{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static OFFSET_NUMBERS=Math.ceil(2*this.bools.length/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+8*this.numbers.length;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6}class PATTERN_INFO{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16}class CssFontInfo{#is;#ss=new TextDecoder;#ns;constructor(t){this.#is=t;this.#ns=new DataView(t)}#rs(t){assert(t>i&3;return 0===s?void 0:2===s}get black(){return this.#as(0)}get bold(){return this.#as(1)}get disableFontFace(){return this.#as(2)}get fontExtraProperties(){return this.#as(3)}get isInvalidPDFjsFont(){return this.#as(4)}get isType3Font(){return this.#as(5)}get italic(){return this.#as(6)}get missingFile(){return this.#as(7)}get remeasure(){return this.#as(8)}get vertical(){return this.#as(9)}#os(t){assert(t0){i=e.slice();for(let t=0,e=h.length;t"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,lt=function _isValidExplicitDest(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[s,n,...r]=i;if(!t(s)&&!Number.isInteger(s))return!1;if(!e(n))return!1;const a=r.length;let o=!0;switch(n.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{#ds=new Map;#cs=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#cs.then(()=>{for(const[t]of this.#ds)t.call(this,i)})}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#ds.set(e,s)}removeEventListener(t,e){const i=this.#ds.get(e);i?.();this.#ds.delete(e)}terminate(){for(const[,t]of this.#ds)t?.();this.#ds.clear()}}const ht=1,dt=2,ct=1,ut=2,pt=3,gt=4,mt=5,ft=6,bt=7,yt=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{#us=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.#ps.bind(this),{signal:this.#us.signal})}#ps({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#gs(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===ht)i.resolve(t.data);else{if(t.callback!==dt)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,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then(function(e){n.postMessage({sourceName:i,targetName:s,callback:ht,callbackId:t.callbackId,data:e})},function(e){n.postMessage({sourceName:i,targetName:s,callback:dt,callbackId:t.callbackId,reason:wrapReason(e)})});return}t.streamId?this.#ms(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 s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:r,targetName:a,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;o.postMessage({sourceName:r,targetName:a,stream:ft,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=!0;o.postMessage({sourceName:r,targetName:a,stream:ct,streamId:n,reason:wrapReason(t)});return e.promise}},i)}#ms(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=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}n.postMessage({sourceName:i,targetName:s,stream:gt,streamId:e,chunk:t},a)},close(){if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:pt,streamId:e});delete r.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:mt,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(){n.postMessage({sourceName:i,targetName:s,stream:yt,streamId:e,success:!0})},function(t){n.postMessage({sourceName:i,targetName:s,stream:yt,streamId:e,reason:wrapReason(t)})})}#gs(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case yt:t.success?r.startCall.resolve():r.startCall.reject(wrapReason(t.reason));break;case bt:t.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(t.reason));break;case ft:if(!a){n.postMessage({sourceName:i,targetName:s,stream:bt,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(){n.postMessage({sourceName:i,targetName:s,stream:bt,streamId:e,success:!0})},function(t){n.postMessage({sourceName:i,targetName:s,stream:bt,streamId:e,reason:wrapReason(t)})});break;case gt:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(t.chunk);break;case pt:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#fs(r,e);break;case mt:assert(r,"error should have stream controller");r.controller.error(wrapReason(t.reason));this.#fs(r,e);break;case ut:t.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(t.reason));this.#fs(r,e);break;case ct:if(!a)break;const o=wrapReason(t.reason);Promise.try(a.onCancel||onFn,o).then(function(){n.postMessage({sourceName:i,targetName:s,stream:ut,streamId:e,success:!0})},function(t){n.postMessage({sourceName:i,targetName:s,stream:ut,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#fs(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#us?.abort();this.#us=null}}class BaseBinaryDataFactory{#bs=Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"});constructor({cMapUrl:t=null,standardFontDataUrl:e=null,wasmUrl:i=null}){this.cMapUrl=t;this.standardFontDataUrl=e;this.wasmUrl=i}async fetch({kind:t,filename:e}){switch(t){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:unreachable(`Not implemented: ${t}`)}const i=this[t];if(!i)throw new Error(`Ensure that the \`${t}\` API parameter is provided.`);const s=`${i}${e}`;return this._fetch(s,t).catch(e=>{throw new Error(`Unable to load ${this.#bs[t]} data at: ${s}`)})}async _fetch(t,e){unreachable("Abstract method `_fetch` called.")}}class DOMBinaryDataFactory extends BaseBinaryDataFactory{async _fetch(t,e){const i="cMapUrl"!==e||t.endsWith(".bcmap")?"bytes":"text",s=await fetchData(t,i);return s instanceof Uint8Array?s:stringToBytes(s)}}class BaseCanvasFactory{#ys=!1;constructor({enableHWA:t=!1}){this.#ys=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.#ys})}}reset({canvas:t},e,i){if(!t)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.width=e;t.height=i}destroy(t){const{canvas:e}=t;if(!e)throw new Error("Canvas is not specified");e.width=e.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 BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class DOMFilterFactory extends BaseFilterFactory{#As;#vs;#ws;#xs;#Cs;#Es;#S=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#xs=t;this.#Cs=e}get#P(){return this.#vs||=new Map}get#Ts(){return this.#Es||=new Map}get#Ss(){if(!this.#ws){const t=this.#Cs.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.#Cs.createElementNS(V,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#ws=this.#Cs.createElementNS(V,"defs");t.append(i);i.append(this.#ws);this.#Cs.body.append(t)}return this.#ws}#_s(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 s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),r=new Array(256),a=new Array(256);for(let t=0;t<256;t++){n[t]=e[t]/255;r[t]=i[t]/255;a[t]=s[t]/255}return[n.join(","),r.join(","),a.join(",")]}#Ps(t){if(void 0===this.#As){this.#As="";const t=this.#Cs.URL;t!==this.#Cs.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#As=updateUrlHash(t,""))}return`url(${this.#As}#${t})`}addFilter(t){if(!t)return"none";let e=this.#P.get(t);if(e)return e;const[i,s,n]=this.#_s(t),r=1===t.length?i:`${i}${s}${n}`;e=this.#P.get(r);if(e){this.#P.set(t,e);return e}const a=`g_${this.#xs}_transfer_map_${this.#S++}`,o=this.#Ps(a);this.#P.set(t,o);this.#P.set(r,o);const l=this.#Ds(a);this.#Ms(i,s,n,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#Ts.get(s);if(n?.key===i)return n.url;if(n){n.filter?.remove();n.key=i;n.url="none";n.filter=null}else{n={key:i,url:"none",filter:null};this.#Ts.set(s,n)}if(!t||!e)return n.url;const r=this.#ks(t);t=Util.makeHexColor(...r);const a=this.#ks(e);e=Util.makeHexColor(...a);this.#Ss.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return n.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.#xs}_hcm_filter`,d=n.filter=this.#Ds(h);this.#Ms(l,l,l,d);this.#Is(d);const getSteps=(t,e)=>{const i=r[t]/255,s=a[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};this.#Ms(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);n.url=this.#Ps(h);return n.url}addAlphaFilter(t){let e=this.#P.get(t);if(e)return e;const[i]=this.#_s([t]),s=`alpha_${i}`;e=this.#P.get(s);if(e){this.#P.set(t,e);return e}const n=`g_${this.#xs}_alpha_map_${this.#S++}`,r=this.#Ps(n);this.#P.set(t,r);this.#P.set(s,r);const a=this.#Ds(n);this.#Fs(i,a);return r}addLuminosityFilter(t){let e,i,s=this.#P.get(t||"luminosity");if(s)return s;if(t){[e]=this.#_s([t]);i=`luminosity_${e}`}else i="luminosity";s=this.#P.get(i);if(s){this.#P.set(t,s);return s}const n=`g_${this.#xs}_luminosity_map_${this.#S++}`,r=this.#Ps(n);this.#P.set(t,r);this.#P.set(i,r);const a=this.#Ds(n);this.#Bs(a);t&&this.#Fs(e,a);return r}addHighlightHCMFilter(t,e,i,s,n){const r=`${e}-${i}-${s}-${n}`;let a=this.#Ts.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.#Ts.set(t,a)}if(!e||!i)return a.url;const[o,l]=[e,i].map(this.#ks.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]=[s,n].map(this.#ks.bind(this));d{const s=new Array(256),n=(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*n),i=r+t*a;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},p=`g_${this.#xs}_hcm_${t}_filter`,g=a.filter=this.#Ds(p);this.#Is(g);this.#Ms(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);a.url=this.#Ps(p);return a.url}destroy(t=!1){if(!t||!this.#Es?.size){this.#ws?.parentNode.parentNode.remove();this.#ws=null;this.#vs?.clear();this.#vs=null;this.#Es?.clear();this.#Es=null;this.#S=0}}#Bs(t){const e=this.#Cs.createElementNS(V,"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)}#Is(t){const e=this.#Cs.createElementNS(V,"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)}#Ds(t){const e=this.#Cs.createElementNS(V,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#Ss.append(e);return e}#Rs(t,e,i){const s=this.#Cs.createElementNS(V,e);s.setAttribute("type","discrete");s.setAttribute("tableValues",i);t.append(s)}#Ms(t,e,i,s){const n=this.#Cs.createElementNS(V,"feComponentTransfer");s.append(n);this.#Rs(n,"feFuncR",t);this.#Rs(n,"feFuncG",e);this.#Rs(n,"feFuncB",i)}#Fs(t,e){const i=this.#Cs.createElementNS(V,"feComponentTransfer");e.append(i);this.#Rs(i,"feFuncA",t)}#ks(t){this.#Ss.style.color=t;return getRGB(getComputedStyle(this.#Ss).getPropertyValue("color"))}}t&&warn("Please use the `legacy` build in Node.js environments.");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 NodeBinaryDataFactory extends BaseBinaryDataFactory{async _fetch(t,e){return async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs/promises"),i=await e.readFile(t);return new Uint8Array(i)}(t)}}const At=new class WebGPU{#Os=null;#Ls=null;#Ns=null;#Us=null;async#Hs(){if(!globalThis.navigator?.gpu)return!1;try{const t=await navigator.gpu.requestAdapter();if(!t)return!1;this.#Us=navigator.gpu.getPreferredCanvasFormat();this.#Ls=await t.requestDevice();return!0}catch{return!1}}init(){return this.#Os||=this.#Hs()}get isReady(){return null!==this.#Ls}loadMeshShader(){if(!this.#Ls||this.#Ns)return;const t=this.#Ls.createShaderModule({code:"\nstruct Uniforms {\n offsetX : f32,\n offsetY : f32,\n scaleX : f32,\n scaleY : f32,\n paddedWidth : f32,\n paddedHeight : f32,\n borderSize : f32,\n _pad : f32,\n};\n\n@group(0) @binding(0) var u : Uniforms;\n\nstruct VertexInput {\n @location(0) position : vec2,\n @location(1) color : vec4,\n};\n\nstruct VertexOutput {\n @builtin(position) position : vec4,\n @location(0) color : vec3,\n};\n\n@vertex\nfn vs_main(in : VertexInput) -> VertexOutput {\n var out : VertexOutput;\n let cx = (in.position.x + u.offsetX) * u.scaleX;\n let cy = (in.position.y + u.offsetY) * u.scaleY;\n out.position = vec4(\n ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,\n 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,\n 0.0,\n 1.0\n );\n out.color = in.color.rgb;\n return out;\n}\n\n@fragment\nfn fs_main(in : VertexOutput) -> @location(0) vec4 {\n return vec4(in.color, 1.0);\n}\n"});this.#Ns=this.#Ls.createRenderPipeline({layout:"auto",vertex:{module:t,entryPoint:"vs_main",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:t,entryPoint:"fs_main",targets:[{format:this.#Us}]},primitive:{topology:"triangle-list"}})}draw(t,e,i,s,n,r,a,o){this.loadMeshShader();const l=this.#Ls,{offsetX:h,offsetY:d,scaleX:c,scaleY:u}=s,p=l.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&l.queue.writeBuffer(p,0,t);const g=l.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&l.queue.writeBuffer(g,0,e);const m=l.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});l.queue.writeBuffer(m,0,new Float32Array([h,d,c,u,r,a,o,0]));const f=l.createBindGroup({layout:this.#Ns.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:m}}]}),b=new OffscreenCanvas(r,a),y=b.getContext("webgpu");y.configure({device:l,format:this.#Us,alphaMode:n?"opaque":"premultiplied"});const A=n?{r:n[0]/255,g:n[1]/255,b:n[2]/255,a:1}:{r:0,g:0,b:0,a:0},v=l.createCommandEncoder(),w=v.beginRenderPass({colorAttachments:[{view:y.getCurrentTexture().createView(),clearValue:A,loadOp:"clear",storeOp:"store"}]});if(i>0){w.setPipeline(this.#Ns);w.setBindGroup(0,f);w.setVertexBuffer(0,p);w.setVertexBuffer(1,g);w.draw(i)}w.end();l.queue.submit([v.finish()]);p.destroy();g.destroy();m.destroy();return b.transferToImageBitmap()}};const vt="Fill",wt="Stroke",xt="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s);t.clip(n)}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}areConic(){if(!this.isRadial())return!1;const t=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return t+this._r1>this._r0&&t+this._r0>this._r1}_createGradient(t,e=null){let i,s=this._p0,n=this._p1;if(e){s=s.slice();n=n.slice();Util.applyTransform(s,e);Util.applyTransform(n,e)}if("axial"===this._type)i=t.createLinearGradient(s[0],s[1],n[0],n[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(s[0],s[1],r,n[0],n[1],a)}for(const t of this._colorStops)i.addColorStop(t[0],t[1]);return i}_createReversedGradient(t,e=null){let i=this._p1,s=this._p0;if(e){i=i.slice();s=s.slice();Util.applyTransform(i,e);Util.applyTransform(s,e)}let n=this._r1,r=this._r0;if(e){const t=new Float32Array(2);Util.singularValueDecompose2dScale(e,t);n*=t[0];r*=t[0]}const a=t.createRadialGradient(i[0],i[1],n,s[0],s[1],r),o=this._colorStops.map(([t,e])=>[1-t,e]).reverse();for(const[t,e]of o)a.addColorStop(t,e);return a}getPattern(t,e,i,s){let n;if(s===wt||s===vt){if(this.isOriginBased()){let s=Util.transform(i,e.baseTransform);this.matrix&&(s=Util.transform(s,this.matrix));const n=.001,r=Math.hypot(s[0],s[1]),a=Math.hypot(s[2],s[3]),o=(s[0]*s[2]+s[1]*s[3])/(r*a);if(Math.abs(o)l[2*s+1]){u=i;i=s;s=u;u=r;r=a;a=u}if(l[2*s+1]>l[2*n+1]){u=s;s=n;n=u;u=a;a=o;o=u}if(l[2*i+1]>l[2*s+1]){u=i;i=s;s=u;u=r;r=a;a=u}const p=(l[2*i]+e.offsetX)*e.scaleX,g=(l[2*i+1]+e.offsetY)*e.scaleY,m=(l[2*s]+e.offsetX)*e.scaleX,f=(l[2*s+1]+e.offsetY)*e.scaleY,b=(l[2*n]+e.offsetX)*e.scaleX,y=(l[2*n+1]+e.offsetY)*e.scaleY;if(g>=y)return;const A=h[4*r],v=h[4*r+1],w=h[4*r+2],x=h[4*a],C=h[4*a+1],E=h[4*a+2],T=h[4*o],S=h[4*o+1],_=h[4*o+2],P=Math.round(g),D=Math.round(y);let M,k,I,F,B,R,O,L;for(let t=P;t<=D;t++){if(ty?1:f===y?0:(f-t)/(f-y);M=m-(m-b)*e;k=x-(x-T)*e;I=C-(C-S)*e;F=E-(E-_)*e}let e;e=ty?1:(g-t)/(g-y);B=p-(p-b)*e;R=A-(A-T)*e;O=v-(v-S)*e;L=w-(w-_)*e;const i=Math.round(Math.min(M,B)),s=Math.round(Math.max(M,B));let n=c*t+4*i;for(let t=i;t<=s;t++){e=(M-t)/(M-B);e<0?e=0:e>1&&(e=1);d[n++]=k-(k-R)*e|0;d[n++]=I-(I-O)*e|0;d[n++]=F-(F-L)*e|0;d[n++]=255}}}class MeshShadingPattern extends BaseShadingPattern{constructor(t){super();this._posData=t[2];this._colData=t[3];this._vertexCount=t[4];this._bounds=t[5];this._bbox=t[6];this._background=t[7];this.matrix=null;!function loadMeshShader(){At.loadMeshShader()}()}_createMeshCanvas(t,e,i){const s=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),r=Math.ceil(this._bounds[2])-s,a=Math.ceil(this._bounds[3])-n,o=Math.min(Math.ceil(Math.abs(r*t[0]*1.1)),3e3)||1,l=Math.min(Math.ceil(Math.abs(a*t[1]*1.1)),3e3)||1,h=r?r/o:1,d=a?a/l:1,c={coords:this._posData,colors:this._colData,offsetX:-s,offsetY:-n,scaleX:1/h,scaleY:1/d},u=o+4,p=l+4,g=i.create(u,p);if(function isGPUReady(){return At.isReady}()&&this._vertexCount>48)g.context.drawImage(function drawMeshWithGPU(t,e,i,s,n,r,a,o){return At.draw(t,e,i,s,n,r,a,o)}(this._posData,this._colData,this._vertexCount,c,e,u,p,2),0,0);else{const t=g.context.createImageData(o,l);if(e){const i=t.data;for(let t=0,s=i.length;tl+1e-6||e>h+1e-6)return null;const d=Math.floor((i-a)/l)+1,c=Math.ceil((i+t-n)/l)-1,u=Math.floor((s-o)/h)+1,p=Math.ceil((s+e-r)/h)-1;return c<=d&&p<=u?[d,u]:null}updatePatternDims(t,e){const i=Util.inverseTransform(this.patternBaseMatrix),s=[t[0],t[1]],n=[t[2],t[3]];Util.applyTransform(s,i);Util.applyTransform(n,i);e[0]=Math.abs(n[0]-s[0]);e[1]=Math.abs(n[1]-s[1]);e[2]=Math.min(s[0],n[0]);e[3]=Math.min(s[1],n[1])}_renderTileCanvas(t,e,i,s){const[n,r,a,o]=this.bbox,l=t.canvasFactory.create(i.size,s.size),h=l.context,d=this.canvasGraphicsFactory.createCanvasGraphics(h,e);d.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(d,this.paintType,this.color);h.translate(-i.scale*n,-s.scale*r);d.transform(0,i.scale,0,0,s.scale,0,0);h.save();d.dependencyTracker?.save();this.clipBbox(d,n,r,a,o);d.baseTransform=getCurrentTransform(d.ctx);d.executeOperatorList(this.operatorList);d.endDrawing();d.dependencyTracker?.restore();h.restore();return l}_getCombinedScales(){const t=new Float32Array(2);Util.singularValueDecompose2dScale(this.matrix,t);const[e,i]=t;Util.singularValueDecompose2dScale(this.baseTransform,t);return[e*t[0],i*t[1]]}drawPattern(t,e,i=!1,[s,n],r){const[a,o,l,h]=this.bbox,d=t.dependencyTracker;d&&(t.dependencyTracker=new CanvasNestedDependencyTracker(d,r));t.save();i?t.ctx.clip(e,"evenodd"):t.ctx.clip(e);t.ctx.setTransform(...this.patternBaseMatrix);t.ctx.translate(s*this.xstep,n*this.ystep);if(this.needsIsolation||1!==t.ctx.globalAlpha||"source-over"!==t.ctx.globalCompositeOperation||t.inSMaskMode){const e=l-a,i=h-o,[s,n]=this._getCombinedScales(),d=this.getSizeAndScale(e,this.ctx.canvas.width,s),c=this.getSizeAndScale(i,this.ctx.canvas.height,n),u=this._renderTileCanvas(t,r,d,c);t.ctx.drawImage(u.canvas,a,o,e,i);t.canvasFactory.destroy(u)}else{this.setFillAndStrokeStyleToContext(t,this.paintType,this.color);this.clipBbox(t,a,o,l,h);t.baseTransformStack.push(t.baseTransform);t.baseTransform=getCurrentTransform(t.ctx);t.executeOperatorList(this.operatorList);t.baseTransform=t.baseTransformStack.pop()}t.restore();d&&(t.dependencyTracker=d)}createPatternCanvas(t,e){const[i,s,n,r]=this.bbox,a=n-i,o=r-s;let{xstep:l,ystep:h}=this;l=Math.abs(l);h=Math.abs(h);info("TilingType: "+this.tilingType);const[d,c]=this._getCombinedScales();let u=a,p=o,g=!1,m=!1;Math.ceil(l*d)>=Math.ceil(a*d)?u=l:g=!0;Math.ceil(h*c)>=Math.ceil(o*c)?p=h:m=!0;const f=this.getSizeAndScale(u,this.ctx.canvas.width,d),b=this.getSizeAndScale(p,this.ctx.canvas.height,c),y=this._renderTileCanvas(t,e,f,b);if(g||m){const e=y.canvas;g&&(u=l);m&&(p=h);const n=this.getSizeAndScale(u,this.ctx.canvas.width,d),r=this.getSizeAndScale(p,this.ctx.canvas.height,c),f=n.size,b=r.size,A=t.canvasFactory.create(f,b),v=A.context,w=g?Math.floor(a/l):0,x=m?Math.floor(o/h):0;for(let t=0;t<=w;t++)for(let i=0;i<=x;i++)v.drawImage(e,f*t,b*i,f,b,0,0,f,b);t.canvasFactory.destroy(y);return{canvas:A.canvas,canvasEntry:A,scaleX:n.scale,scaleY:r.scale,offsetX:i,offsetY:s}}return{canvas:y.canvas,canvasEntry:y,scaleX:f.scale,scaleY:b.scale,offsetX:i,offsetY:s}}getSizeAndScale(t,e,i){const s=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);n>=s?n=s:i=n/t;return{scale:i,size:n}}clipBbox(t,e,i,s,n){const r=s-e,a=n-i,o=new Path2D;o.rect(e,i,r,a);Util.axialAlignedBoundingBox([e,i,s,n],getCurrentTransform(t.ctx),t.current.minMax);t.ctx.clip(o);t.current.updateClipFromPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;n.patternFill=n.patternStroke=!1;switch(e){case Ct:const{fillStyle:t,strokeStyle:r}=this.ctx;s.fillStyle=n.fillColor=t;s.strokeStyle=n.strokeColor=r;break;case Et:s.fillStyle=s.strokeStyle=i;n.fillColor=n.strokeColor=i;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,s,n){const r=s!==xt?Util.transform(i,this.patternBaseMatrix):i,a=this.createPatternCanvas(e,n);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");e.canvasFactory.destroy(a.canvasEntry);l.setTransform(o);return l}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:r=4294967295,inverseDecode:a=!1}){const o=FeatureTest.isLittleEndian?4278190080:255,[l,h]=a?[r,o]:[o,r],d=s>>3,c=7&s,u=l^h,p=t.length;i=new Uint32Array(i.buffer);let g=0;for(let s=0;s>7&1)&u;i[g+1]=l^-(s>>6&1)&u;i[g+2]=l^-(s>>5&1)&u;i[g+3]=l^-(s>>4&1)&u;i[g+4]=l^-(s>>3&1)&u;i[g+5]=l^-(s>>2&1)&u;i[g+6]=l^-(s>>1&1)&u;i[g+7]=l^-(1&s)&u}if(0===c)continue;const s=e>7-t&1)&u}return{srcPos:e,destPos:g}}const Tt=16,St=new DOMMatrix,_t=new Float32Array(2);function drawImageAtIntegerCoords(t,e,i,s,n,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),y=o*p+m,A=Math.round(y),v=(a+l)*d+g,w=Math.abs(Math.round(v)-b)||1,x=(o+h)*p+m,C=Math.abs(Math.round(x)-A)||1;t.setTransform(Math.sign(d),0,0,Math.sign(p),b,A);t.drawImage(e,i,s,n,r,0,0,w,C);t.setTransform(d,c,u,p,g,m);return[w,C]}if(0===d&&0===p){const f=o*u+g,b=Math.round(f),y=a*c+m,A=Math.round(y),v=(o+h)*u+g,w=Math.abs(Math.round(v)-b)||1,x=(a+l)*c+m,C=Math.abs(Math.round(x)-A)||1;t.setTransform(0,Math.sign(c),Math.sign(u),0,b,A);t.drawImage(e,i,s,n,r,0,0,C,w);t.setTransform(d,c,u,p,g,m);return[C,w]}t.drawImage(e,i,s,n,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=s;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=y;textRise=0;fillColor="#000000";strokeColor="#000000";tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";minMax=i.slice();constructor(t,e){this.clipBox=new Float32Array([0,0,t,e])}clone(){const t=Object.create(this);t.clipBox=this.clipBox.slice();t.minMax=this.minMax.slice();t.tilingPatternDims=this.tilingPatternDims?.slice();return t}getPathBoundingBox(t=vt,e=null){const i=this.minMax.slice();if(t===wt){e||unreachable("Stroke bounding box must include transform.");Util.singularValueDecompose2dScale(e,_t);const t=_t[0]*this.lineWidth/2,s=_t[1]*this.lineWidth/2;i[0]-=t;i[1]-=s;i[2]+=t;i[3]+=s}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(i,0)}getClippedPathBoundingBox(t=vt,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,s=e.width,n=i%Tt,r=(i-n)/Tt,a=0===n?r:r+1,o=t.createImageData(s,Tt);let l,h=0;const d=e.data,c=o.data;let u,p,g,m;if(e.kind===E.GRAYSCALE_1BPP){const e=d.byteLength,i=new Uint32Array(c.buffer,0,c.byteLength>>2),m=i.length,f=s+7>>3,b=4294967295,y=FeatureTest.isLittleEndian?4278190080:255;for(u=0;uf?s:8*t-7,a=-8&r;let o=0,c=0;for(;n>=1}}for(;l=r){g=n;m=s*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*Tt)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,s=e.width,n=i%Tt,r=(i-n)/Tt,a=0===n?r:r+1,o=t.createImageData(s,Tt);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!==s){if(o===s.nextBreakPoint){s.breakIt(o,i);return o}if(s.shouldSkip(o)){if(++o===l)return o;continue}}if(!n||n(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}}}#zs(){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.canvasFactory.destroy(this.transparentCanvasEntry);this.transparentCanvas=null;this.transparentCanvasEntry=null}}endDrawing(){this.#zs();for(const t of this.smaskGroupCanvases)this.canvasFactory.destroy(t);this.smaskGroupCanvases.length=0;this._clearPreparedSMask();this.tempSMask=null;this.smaskStack.length=0;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.#Gs()}#Gs(){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,s=t.height??t.displayHeight,n=[];let r=Math.max(Math.hypot(e[0],e[1]),1),a=Math.max(Math.hypot(e[2],e[3]),1),o=i,l=s;for(;r>2&&o>1||a>2&&l>1;){let t=o,e=l;if(r>2&&o>1){t=Math.ceil(o/2);r/=o/t}if(a>2&&l>1){e=Math.ceil(l/2);a/=l/e}n.push({newWidth:t,newHeight:e});o=t;l=e}if(0===n.length)return{img:t,paintWidth:i,paintHeight:s,tmpCanvas:null};if(1===n.length){const{newWidth:e,newHeight:r}=n[0],a=this.canvasFactory.create(e,r);a.context.drawImage(t,0,0,i,s,0,0,e,r);return{img:a.canvas,paintWidth:e,paintHeight:r,tmpCanvas:a}}let h=this.canvasFactory.create(1,1),d=this.canvasFactory.create(1,1),c=i,u=s,p=t;for(const{newWidth:t,newHeight:e}of n){this.canvasFactory.reset(d,t,e);d.context.drawImage(p,0,0,c,u,0,0,t,e);[h,d]=[d,h];p=h.canvas;c=t;u=e}this.canvasFactory.destroy(d);return{img:h.canvas,paintWidth:c,paintHeight:u,tmpCanvas:h}}_createMaskCanvas(t,e){const s=this.ctx,{width:n,height:r}=e,a=this.current.fillColor,o=this.current.patternFill,l=getCurrentTransform(s);let h,d,c,u;if((e.bitmap||e.data)&&e.count>1){const i=e.bitmap||e.data.buffer;d=JSON.stringify(o?l:[l.slice(0,4),a]);h=this._cachedBitmapsMap.getOrInsertComputed(i,makeMap);const s=h.get(d);if(s&&!o){const e=Math.round(Math.min(l[0],l[2])+l[4]),i=Math.round(Math.min(l[1],l[3])+l[5]);this.dependencyTracker?.recordDependencies(t,ot);return{canvas:s,offsetX:e,offsetY:i}}c=s}if(!c){u=this.canvasFactory.create(n,r);putBinaryImageMask(u.context,e)}let p=Util.transform(l,[1/n,0,0,-1/r,0,0]);p=Util.transform(p,[1,0,0,1,0,-r]);const g=i.slice();Util.axialAlignedBoundingBox([0,0,n,r],p,g);const[m,f,b,y]=g,A=Math.round(b-m)||1,v=Math.round(y-f)||1,w=this.canvasFactory.create(A,v),x=w.context,C=m,E=f;x.translate(-C,-E);x.transform(...p);let T=null;if(!c){const t=this._scaleImage(u.canvas,getCurrentTransformInverse(x));c=t.img;T=t.tmpCanvas;if(c!==u.canvas){this.canvasFactory.destroy(u);u=null}if(h&&o){h.set(d,c);T=null;u=null}}x.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(x),e.interpolate);drawImageAtIntegerCoords(x,c,0,0,c.width,c.height,0,0,n,r);T&&this.canvasFactory.destroy(T);u&&this.canvasFactory.destroy(u);x.globalCompositeOperation="source-in";const S=Util.transform(getCurrentTransformInverse(x),[1,0,0,1,-C,-E]);x.fillStyle=o?a.getPattern(s,this,S,vt,t):a;x.fillRect(0,0,n,r);h&&!o&&h.set(d,w.canvas);this.dependencyTracker?.recordDependencies(t,ot);return{canvas:w.canvas,canvasEntry:h&&!o?null:w,offsetX:Math.round(C),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=Dt[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t);this.ctx.miterLimit=e}setDash(t,e,i){this.dependencyTracker?.recordSimpleData("dash",t);const s=this.ctx;if(void 0!==s.setLineDash){s.setLineDash(e);s.lineDashOffset=i}}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[i,s]of e)switch(i){case"LW":this.setLineWidth(t,s);break;case"LC":this.setLineCap(t,s);break;case"LJ":this.setLineJoin(t,s);break;case"ML":this.setMiterLimit(t,s);break;case"D":this.setDash(t,s[0],s[1]);break;case"RI":this.setRenderingIntent(t,s);break;case"FL":this.setFlatness(t,s);break;case"Font":this.setFont(t,s[0],s[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t);this.current.strokeAlpha=s;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t);this.ctx.globalAlpha=this.current.fillAlpha=s;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t);this.ctx.globalCompositeOperation=s;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t);this.current.activeSMask=s?this.tempSMask:null;this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation);this.tempSMask=null;this.checkSMaskState(t);break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t);this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s)}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){if(this.smaskPreparedEntry){this.canvasFactory.destroy(this.smaskPreparedEntry);this.smaskPreparedEntry=null}this.smaskPreparedFor=null;this.smaskPreparedOffsetX=0;this.smaskPreparedOffsetY=0}_ensurePreparedSMask(t,e,i){if(t!==this.smaskPreparedFor){this._clearPreparedSMask();this._prepareSMaskCanvas(t,e,i)}}checkSMaskState(t){const e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode(t):!this.current.activeSMask&&e?this.endSMaskMode():this.current.activeSMask&&e&&this._ensurePreparedSMask(this.current.activeSMask,this.ctx.canvas.width,this.ctx.canvas.height)}_prepareSMaskCanvas(t,e,i){const{canvas:s,subtype:n,backdrop:r,transferMap:a}=t,o="Luminosity"===n||"Alpha"===n&&a;if(!r&&!o){this.smaskPreparedFor=t;return}let l,h,d;if(r&&o){const o=this.canvasFactory.create(e,i),c=o.context;c.drawImage(s,t.offsetX,t.offsetY);c.globalCompositeOperation="destination-atop";c.fillStyle=r;c.fillRect(0,0,e,i);c.globalCompositeOperation="source-over";l=this.canvasFactory.create(e,i);const u=l.context;u.filter="Alpha"===n?this.filterFactory.addAlphaFilter(a):this.filterFactory.addLuminosityFilter(a);u.drawImage(o.canvas,0,0);u.filter="none";this.canvasFactory.destroy(o);h=d=0}else if(o){l=this.canvasFactory.create(s.width,s.height);const e=l.context;e.filter="Alpha"===n?this.filterFactory.addAlphaFilter(a):this.filterFactory.addLuminosityFilter(a);e.drawImage(s,0,0);e.filter="none";({offsetX:h,offsetY:d}=t)}else{l=this.canvasFactory.create(e,i);const n=l.context;n.drawImage(s,t.offsetX,t.offsetY);n.globalCompositeOperation="destination-atop";n.fillStyle=r;n.fillRect(0,0,e,i);n.globalCompositeOperation="source-over";h=d=0}this.smaskPreparedEntry=l;this.smaskPreparedFor=t;this.smaskPreparedOffsetX=h;this.smaskPreparedOffsetY=d}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:e,height:i}=this.ctx.canvas,s=this.canvasFactory.create(e,i);this.smaskScratchCanvas=s;this.suspendedCtx=this.ctx;const n=this.ctx=s.context;n.setTransform(this.suspendedCtx.getTransform());copyCtxState(this.suspendedCtx,n);!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,s,n,r,a){e.transform(t,i,s,n,r,a);this.__originalTransform(t,i,s,n,r,a)};t.setTransform=function(t,i,s,n,r,a){if(void 0===i){e.setTransform(t);this.__originalSetTransform(t)}else{e.setTransform(t,i,s,n,r,a);this.__originalSetTransform(t,i,s,n,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,s,n,r,a){e.bezierCurveTo(t,i,s,n,r,a);this.__originalBezierCurveTo(t,i,s,n,r,a)};t.rect=function(t,i,s,n){e.rect(t,i,s,n);this.__originalRect(t,i,s,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(n,this.suspendedCtx);this._ensurePreparedSMask(this.current.activeSMask,e,i);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;this.canvasFactory.destroy(this.smaskScratchCanvas);this.smaskScratchCanvas=null;this._clearPreparedSMask()}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(t[0],t[1],t[2]-t[0],t[3]-t[1]);this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],r=s[1],a=s[2]-n,o=s[3]-r;if(0===a||0===o)return;const l=this.smaskPreparedEntry;if(l){const t=n-this.smaskPreparedOffsetX,e=r-this.smaskPreparedOffsetY;i.save();i.globalAlpha=1;i.setTransform(1,0,0,1,0,0);const s=new Path2D;s.rect(n,r,a,o);i.clip(s);i.globalCompositeOperation="destination-in";i.drawImage(l.canvas,t,e,a,o,n,r,a,o);i.restore()}else this.genericComposeSMask(e.context,i,a,o,n,r,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation=e.blendMode||"source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,n,r,a,o,n,r,a,o);t.restore()}genericComposeSMask(t,e,i,s,n,r,a,o){const l=t.canvas,h=n-a,d=r-o;e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);const c=new Path2D;c.rect(n,r,i,s);e.clip(c);e.globalCompositeOperation="destination-in";e.drawImage(l,h,d,i,s,n,r,i,s);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();if(this.inSMaskMode){copyCtxState(this.suspendedCtx,this.ctx);this.ctx.setTransform(this.suspendedCtx.getTransform())}this.checkSMaskState(t);this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}else this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,s,n,r,a){this.dependencyTracker?.recordIncrementalData("transform",t);this.ctx.transform(e,i,s,n,r,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,s){let[n]=i;if(!s){n||=i[0]=new Path2D;e!==I.stroke&&e!==I.closeStroke&&(this.current.tilingPatternDims=null);this[e](t,n);return}if(null!==this.dependencyTracker){const i=e===I.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,s[0]-i,s[2]+i,s[1]-i,s[3]+i).recordDependencies(t,["transform"])}n instanceof Path2D||(n=i[0]=makePathFromDrawOPS(n));Util.axialAlignedBoundingBox(s,getCurrentTransform(this.ctx),this.current.minMax);const r=this.current.tilingPatternDims;if(r&&e!==I.stroke&&e!==I.closeStroke&&this.current.fillColor instanceof TilingPattern){const t=Util.intersect(this.current.clipBox,this.current.minMax);t?this.current.fillColor.updatePatternDims(t,r):this.current.tilingPatternDims=null}this[e](t,n);this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){const s=this.ctx,n=this.current.strokeColor;s.globalAlpha=this.current.strokeAlpha;if(this.contentVisible)if("object"==typeof n&&n?.getPattern){const i=n.isModifyingCurrentTransform()?s.getTransform():null;s.save();s.strokeStyle=n.getPattern(s,this,getCurrentTransformInverse(s),wt,t);if(i){const t=new Path2D;t.addPath(e,s.getTransform().invertSelf().multiplySelf(i));e=t}this.rescaleAndStroke(e,!1);s.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,et);i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(wt,getCurrentTransform(this.ctx)));s.globalAlpha=this.current.fillAlpha}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){const s=this.ctx,n=this.current.fillColor,r=this.current.patternFill;let a=!1;const o=this.current.getClippedPathBoundingBox();this.dependencyTracker?.recordDependencies(t,it);if(r){const r=this.current.tilingPatternDims,l=r&&n.canSkipPatternCanvas(r);if(l){n.drawPattern(this,e,this.pendingEOFill,l,t);this.pendingEOFill=!1;i&&this.consumePath(t,e,o);this.current.tilingPatternDims=null;return}const h=n.isModifyingCurrentTransform()?s.getTransform():null;this.dependencyTracker?.save(t);s.save();s.fillStyle=n.getPattern(s,this,getCurrentTransformInverse(s),vt,t);if(h){const t=new Path2D;t.addPath(e,s.getTransform().invertSelf().multiplySelf(h));e=t}a=!0}if(this.contentVisible&&null!==o)if(this.pendingEOFill){s.fill(e,"evenodd");this.pendingEOFill=!1}else s.fill(e);if(a){s.restore();this.dependencyTracker?.restore(t)}i&&this.consumePath(t,e,o)}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,nt).recordOperation(t)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=Mt}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=kt}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,s=i.getTransform().invertSelf();for(const{transform:i,x:n,y:r,fontSize:a,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(s).translate(n,r).scale(a,-a));i.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t);this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t);this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t);this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t);this.current.leading=-e}setFont(t,e,i){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);const n=this.commonObjs.get(e),r=this.current;if(!n)throw new Error(`Can't find font for ${e}`);r.fontMatrix=n.fontMatrix||s;0!==r.fontMatrix[0]&&0!==r.fontMatrix[3]||warn("Invalid font matrix for font "+e);if(i<0){i=-i;r.fontDirection=-1}else r.fontDirection=1;this.current.font=n;this.current.fontSize=i;if(n.isType3Font)return;const a=n.loadedName||"sans-serif",o=n.systemFontInfo?.css||`"${a}", ${n.fallbackName}`;let l="normal";n.black?l="900":n.bold&&(l="bold");const h=n.italic?"italic":"normal";let d=i;i<16?d=16:i>100&&(d=100);this.current.fontSizeScale=i/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)}#Ws(t,e,i){const s=new Path2D;s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return s}paintChar(t,e,i,s,n,r){const a=this.ctx,o=this.current,l=o.font,h=o.textRenderingMode,d=o.fontSize/o.fontSizeScale,c=h&x,u=!!(h&C),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,s);a.scale(d,-d);this.dependencyTracker?.recordCharacterBBox(t,a,l);let e;if(c===y||c===v)if(n){e=a.getTransform();a.setTransform(...n);const t=this.#Ws(m,e,n);a.fill(t)}else a.fill(m);if(c===A||c===v)if(r){e||=a.getTransform();a.setTransform(...r);const{a:t,b:i,c:s,d:n}=e,o=Util.inverseTransform(r),l=Util.transform([t,i,s,n,0,0],o);Util.singularValueDecompose2dScale(l,_t);a.lineWidth*=Math.max(_t[0],_t[1])/d;a.stroke(this.#Ws(m,e,r))}else{a.lineWidth/=d;a.stroke(m)}a.restore()}else{if(c===y||c===v){a.fillText(e,i,s);this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,s,()=>a.measureText(e))}if(c===A||c===v){this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,s,()=>a.measureText(e)).recordDependencies(t,et);a.strokeText(e,i,s)}}if(u){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(a),x:i,y:s,fontSize:d,path:m});this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,s)}}get isFontSubpixelAAEnabled(){const t=this.canvasFactory.create(10,10),e=t.context;e.scale(1.5,1);e.fillText("I",0,10);const i=e.getImageData(0,0,10,10).data;this.canvasFactory.destroy(t);let s=!1;for(let t=3;t0&&i[t]<255){s=!0;break}return shadow(this,"isFontSubpixelAAEnabled",s)}showText(t,e){if(this.dependencyTracker){this.dependencyTracker.recordDependencies(t,rt).resetBBox(t);this.current.textRenderingMode&C&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies()}const i=this.current,s=i.font;if(s.isType3Font){this.showType3Text(t,e);this.dependencyTracker?.recordShowTextOperation(t);return}const n=i.fontSize;if(0===n){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=s.vertical,p=u?1:-1,g=s.defaultVMetrics,m=n*i.fontMatrix[0],f=i.textRenderingMode===y&&!s.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,w;const E=i.textRenderingMode&x,T=E===y||E===v,S=E===A||E===v;let _=i.lineWidth;const P=i.textMatrixScale;0===P||0===_?S&&(_=this.getSinglePixelWidth()):_/=P;if(1!==a){r.scale(a,a);_/=a}r.lineWidth=_;if(T&&i.patternFill){r.save();const e=i.fillColor.getPattern(r,this,getCurrentTransformInverse(r),vt,t);b=getCurrentTransform(r);r.restore();r.fillStyle=e}if(S&&i.patternStroke){r.save();const e=i.strokeColor.getPattern(r,this,getCurrentTransformInverse(r),wt,t);w=getCurrentTransform(r);r.restore();r.strokeStyle=e}if(s.isInvalidPDFjsFont){const s=[];let n=0;for(const t of e){s.push(t.unicode);n+=t.width}const a=s.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+=n*m*d;r.restore();this.compose();return}let D,M=0;for(D=0;D0){C=r.measureText(y);const t=1e3*C.width/n*a;if(EC??r.measureText(y))}else{this.paintChar(t,y,v,x,b,w);if(A){const e=v+n*A.offset.x/a,i=x-n*A.offset.y/a;this.paintChar(t,A.fontChar,e,i,b,w)}}M+=u?E*m-c*h:E*m+c*h;d&&r.restore()}u?i.y-=M:i.x+=M*d;r.restore();this.compose();this.dependencyTracker?.recordShowTextOperation(t)}showType3Text(t,e){const i=this.ctx,n=this.current,r=n.font,a=n.fontSize,o=n.fontDirection,l=r.vertical?1:-1,h=n.charSpacing,d=n.wordSpacing,c=n.textHScale*o,u=n.fontMatrix||s,p=e.length;let g,m,f,b;if(n.textRenderingMode===w||0===a)return;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null;i.save();n.textMatrix&&i.transform(...n.textMatrix);i.translate(n.x,n.y+n.textRise);i.scale(c,o);const y=this.dependencyTracker;this.dependencyTracker=y?new CanvasNestedDependencyTracker(y,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,s,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);const i=this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0;this.current.tilingPatternDims=i instanceof TilingPattern?[0,0,0,0]:null}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;this.current.tilingPatternDims=null}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t);this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1;this.current.tilingPatternDims=null}_getPattern(t,e,i=null){let s;if(this.cachedPatterns.has(e))s=this.cachedPatterns.get(e);else{s=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,s)}i&&(s.matrix=i);return s}shadingFill(t,e){if(!this.contentVisible)return;const s=this.ctx;this.save(t);const n=this._getPattern(t,e);s.fillStyle=n.getPattern(s,this,getCurrentTransformInverse(s),xt,t);const r=getCurrentTransformInverse(s);if(r){const{width:t,height:e}=s.canvas,n=i.slice();Util.axialAlignedBoundingBox([0,0,t,e],r,n);const[a,o,l,h]=n;this.ctx.fillRect(a,o,l-a,h-o)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,at).recordDependencies(t,it).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,s,n,r]=i,a=new Path2D;a.rect(e,s,n-e,r-s);this.ctx.clip(a);this.dependencyTracker?.recordClipBox(t,this.ctx,e,n,s,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);const{inSMaskMode:s}=this;if(s){this.endSMaskMode();this.current.activeSMask=null}const n=this.ctx;e.isolated||info("TODO: Support non-isolated groups.");e.knockout&&warn("Knockout groups not supported.");if(!e.needsIsolation&&1===n.globalAlpha&&"source-over"===n.globalCompositeOperation&&!s){if(e.bbox){let t=new Path2D;const[i,s,r,a]=e.bbox;t.rect(i,s,r-i,a-s);if(e.matrix){const i=new Path2D;i.addPath(t,new DOMMatrix(e.matrix));t=i}n.clip(t)}this.groupStack.push(null);this.groupLevel++;return}const r=getCurrentTransform(n);e.matrix&&n.transform(...e.matrix);const a=[0,0,n.canvas.width,n.canvas.height];let o;if(e.bbox){o=i.slice();Util.axialAlignedBoundingBox(e.bbox,getCurrentTransform(n),o);o=Util.intersect(o,a)||[0,0,0,0]}else o=a;const l=Math.floor(o[0]),h=Math.floor(o[1]),d=Math.max(Math.ceil(o[2])-l,1),c=Math.max(Math.ceil(o[3])-h,1);this.current.startNewPathAndClipBox([0,0,d,c]);const u=this.canvasFactory.create(d,c);e.smask&&this.smaskGroupCanvases.push(u);const p=u.context;p.translate(-l,-h);p.transform(...r);if(!e.isolated&&!e.smask&&s&&e.needsIsolation){p.save();p.setTransform(1,0,0,1,0,0);p.drawImage(n.canvas,-l,-h);p.restore()}if(e.bbox){let t=new Path2D;const[i,s,n,r]=e.bbox;t.rect(i,s,n-i,r-s);if(e.matrix){const i=new Path2D;i.addPath(t,new DOMMatrix(e.matrix));t=i}p.clip(t)}e.smask&&this.smaskStack.push({canvas:u.canvas,context:p,offsetX:l,offsetY:h,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null});if(!e.smask||this.dependencyTracker){n.setTransform(1,0,0,1,0,0);n.translate(l,h);n.save()}copyCtxState(n,p);this.ctx=p;this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(n);this.setGState(t,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]);this.groupStack.push(n);this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const s=this.ctx,n=this.groupStack.pop();if(null!==n){this.ctx=n;this.ctx.imageSmoothingEnabled=!1;this.dependencyTracker?.popBaseTransform();if(e.smask){this.tempSMask=this.smaskStack.pop();this.restore(t);if(this.dependencyTracker){this.ctx.restore();this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())}}else{this.ctx.restore();const e=getCurrentTransform(this.ctx);this.restore(t);this.ctx.save();this.ctx.setTransform(...e);const n=i.slice();Util.axialAlignedBoundingBox([0,0,s.canvas.width,s.canvas.height],e,n);this.ctx.drawImage(s.canvas,0,0);this.ctx.restore();this.canvasFactory.destroy({canvas:s.canvas,context:s});this.compose(n)}}else this.restore(t)}beginAnnotation(t,e,i,s,n,r){this.#zs();resetCtxToDefault(this.ctx);this.ctx.save();this.save(t);this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(i){const n=i[2]-i[0],a=i[3]-i[1];if(r&&this.annotationCanvasMap){(s=s.slice())[4]-=i[0];s[5]-=i[1];(i=i.slice())[0]=i[1]=0;i[2]=n;i[3]=a;Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx),_t);const{viewportScale:t}=this,r=Math.ceil(n*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],n,a);this.ctx.clip(e)}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.baseTransformStack.push(this.baseTransform);this.transform(t,...s);this.transform(t,...n);this.baseTransform=getCurrentTransform(this.ctx)}endAnnotation(t){if(this.annotationCanvas){this.ctx.restore();this.#Gs();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const i=e.count;(e=this.getObject(t,e.data,e)).count=i;const s=this.ctx,n=this._createMaskCanvas(t,e),r=n.canvas;s.save();s.setTransform(1,0,0,1,0,0);s.drawImage(r,n.offsetX,n.offsetY);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,n.offsetX,n.offsetX+r.width,n.offsetY,n.offsetY+r.height).recordOperation(t);s.restore();n.canvasEntry&&this.canvasFactory.destroy(n.canvasEntry);this.compose()}paintImageMaskXObjectRepeat(t,e,i,s=0,n=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,s,n,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:s}}=this,[n,r]=this.getScaleForStroking();if(n===r){i.lineWidth=(s||1)*n;i.stroke(t);return}const a=i.getLineDash();e&&i.save();i.scale(n,r);St.a=1/n;St.d=1/r;const o=new Path2D;o.addPath(t,St);if(a.length>0){const t=Math.max(n,r);i.setLineDash(a.map(e=>e/t));i.lineDashOffset/=t}i.lineWidth=s||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 BasePDFStream{#Vs=null;#js=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,e,i){this._source=t;this.#Vs=e;this.#js=i}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){assert(!this._fullReader,"BasePDFStream.getFullReader can only be called once.");return this._fullReader=new this.#Vs(this)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new this.#js(this,t,e);this._rangeReaders.add(i);return i}cancelAllRequests(t){this._fullReader?.cancel(t);for(const e of new Set(this._rangeReaders))e.cancel(t)}}class BasePDFStreamReader{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=t}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){unreachable("Abstract method `read` called")}cancel(t){unreachable("Abstract method `cancel` called")}}class BasePDFStreamRangeReader{_stream=null;constructor(t,e,i){this._stream=t}async read(){unreachable("Abstract method `read` called")}cancel(t){unreachable("Abstract method `cancel` called")}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function getResponseOrigin(t){return URL.parse(t)?.origin??null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={contentLength:0,isRangeSupported:!1},r=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(r))return n;n.contentLength=r;if(r<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;"identity"===(t.get("Content-Encoding")||"identity")&&(n.isRangeSupported=!0);return n}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 s=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,s,n]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[s,n]}const n=[];for(let t=0;t{t._responseOrigin=getResponseOrigin(i.url);ensureResponseStatus(i.status,n);this._reader=i.body.getReader();const r=i.headers,{contentLength:a,isRangeSupported:o}=validateRangeRequestCapabilities({responseHeaders:r,isHttp:!0,rangeChunkSize:s,disableRange:e});this._contentLength=a;this._isRangeSupported=o;this._filename=extractFilenameFromHeader(r);!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: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:s,withCredentials:n}=t._source,r=new Headers(t.headers);r.append("Range",`bytes=${e}-${i-1}`);fetchUrl(s,r,n,this._abortController).then(e=>{ensureResponseOrigin(getResponseOrigin(e.url),t._responseOrigin);ensureResponseStatus(e.status,s);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:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}function transport_stream_getArrayBuffer(t){return t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function endRequests(){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}class PDFDataTransportStream extends BasePDFStream{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,PDFDataTransportStreamReader,PDFDataTransportStreamRangeReader);const{pdfDataRangeTransport:e}=t,{initialData:i,progressiveDone:s}=e;if(i?.length>0){const t=transport_stream_getArrayBuffer(i);this._queuedChunks.push(t)}this._progressiveDone=s;e.transportReady(t=>{switch(t.type){case"range":case"progressiveRead":this.#$s(t.begin,t.chunk);break;case"progressiveDone":this._fullReader?.progressiveDone();this._progressiveDone=!0}})}#$s(t,e){const i=transport_stream_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{#Xs=endRequests.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:e,disableRange:i,disableStream:s}=t._source,{length:n,contentDispositionFilename:r}=e;this._queuedChunks=t._queuedChunks||[];for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._done=t._progressiveDone;this._contentLength=n;this._isStreamingSupported=!s;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.#Xs()}progressiveDone(){this._done||=!0;0===this._queuedChunks.length&&this.#Xs()}}class PDFDataTransportStreamRangeReader extends BasePDFStreamRangeReader{#Xs=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.#Xs()}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.#Xs();this.onDone?.()}}class PDFNetworkStream extends BasePDFStream{#qs=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.#qs.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.#Ks.bind(this,e);e.onprogress=this.#Ys.bind(this,e);e.send(null);return e}#Ys(t,e){const i=this.#qs.get(t);i?.onProgress?.(e)}#Ks(t,e){const i=this.#qs.get(t);if(!i)return;if(t.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==t.readyState)return;if(!this.#qs.has(t))return;this.#qs.delete(t);if(0===t.status&&this.isHttp){i.onError(t.status);return}const s=t.status||200;if(!i.validateStatus(s)){i.onError(t.status);return}const n=function network_getArrayBuffer(t){return"string"!=typeof t?t:stringToBytes(t).buffer}(t.response);if(206===s){const e=t.getResponseHeader("Content-Range");if(/bytes (\d+)-(\d+)\/(\d+)/.test(e))i.onDone(n);else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else n?i.onDone(n):i.onError(t.status)}_abortRequest(t){if(this.#qs.has(t)){this.#qs.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{#Xs=endRequests.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t);this._fullRequestXhr=t._request({onHeadersReceived:this.#Qs.bind(this),onDone:this.#Js.bind(this),onError:this.#Zs.bind(this),onProgress:this.#Ys.bind(this)})}#Qs(){const t=this._stream,{disableRange:e,rangeChunkSize:i}=t._source,s=this._fullRequestXhr;t._responseOrigin=getResponseOrigin(s.responseURL);const n=s.getAllResponseHeaders(),r=new Headers(n?n.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{contentLength:a,isRangeSupported:o}=validateRangeRequestCapabilities({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:i,disableRange:e});this._contentLength=a;this._isRangeSupported=o;this._filename=extractFilenameFromHeader(r);this._isRangeSupported&&t._abortRequest(s);this._headersCapability.resolve()}#Js(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.#Xs()}#Zs(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}#Ys(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.#Xs();this._stream._abortRequest(this._fullRequestXhr);this._fullRequestXhr=null}}class PDFNetworkStreamRangeReader extends BasePDFStreamRangeReader{#Xs=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.#Qs.bind(this),onDone:this.#Js.bind(this),onError:this.#Zs.bind(this),onProgress:null})}#Qs(){const t=getResponseOrigin(this._requestXhr?.responseURL);try{ensureResponseOrigin(t,this._stream._responseOrigin)}catch(t){this._storedError=t;this.#Zs(0)}}#Js(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunk=t;this._done=!0;this.#Xs();this.onClosed?.()}#Zs(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.#Xs();this._stream._abortRequest(this._requestXhr);this.onClosed?.()}}function getReadableStream(t,e=null){const i=process.getBuiltinModule("fs"),{Readable:s}=process.getBuiltinModule("stream"),n=i.createReadStream(t,e);return s.toWeb(n)}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,rangeChunkSize:s,url:n}=t._source;this._isStreamingSupported=!i;process.getBuiltinModule("fs/promises").lstat(n).then(t=>{const i=getReadableStream(n);this._reader=i.getReader();const{size:r}=t;this._contentLength=r;this._isRangeSupported=!e&&r>2*s;!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."));this._headersCapability.resolve()}).catch(t=>{"ENOENT"===t.code&&(t=createResponseError(0,n));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: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:s}=t._source;try{const t=getReadableStream(s,{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:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t)}}class GlobalWorkerOptions{static#tn=null;static#en="";static get workerPort(){return this.#tn}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#tn=t}static get workerSrc(){return this.#en}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#en=t}}class Metadata{#in;#sn;constructor({parsedData:t,rawData:e}){this.#in=t;this.#sn=e}getRaw(){return this.#sn}get(t){return this.#in.get(t)??null}[Symbol.iterator](){return this.#in.entries()}}const It=Symbol("INTERNAL");class OptionalContentGroup{#nn=!1;#rn=!1;#an=!1;#on=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#nn=!!(t&a);this.#rn=!!(t&o);this.name=e;this.intent=i;this.usage=s;this.rbGroups=n}get visible(){if(this.#an)return this.#on;if(!this.#on)return!1;const{print:t,view:e}=this.usage;return this.#nn?"OFF"!==e?.viewState:!this.#rn||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==It&&unreachable("Internal method `_setVisible` called.");this.#an=i;this.#on=e}}class OptionalContentConfig{#ln=null;#hn=new Map;#dn=null;#cn=null;constructor(t,e=a){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#cn=t.order;for(const i of t.groups)this.#hn.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#hn.values())t._setVisible(It,!1);for(const e of t.on)this.#hn.get(e)._setVisible(It,!0);for(const e of t.off)this.#hn.get(e)._setVisible(It,!1);this.#dn=this.getHash()}}#un(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;st===e+1)&&(this.#pn=null)}deletePages(t){this.#yn();const e=this.#pn,i=this.#An();this.#bn={pageNumberToId:e.slice(),pagesNumber:this.#mn,prevPageNumbers:this.#gn.slice()};const s=this.#mn-t.length;this.#mn=s;const n=this.#pn=new Uint32Array(s);this.#gn=new Int32Array(s);let r=0,a=0;for(const i of t){const t=i-1;if(t!==r){n.set(e.subarray(r,t),a);a+=t-r}r=t+1}rthis.#pn[t-1])}}cancelCopy(){this.#fn=null}pastePages(t){this.#yn();const e=this.#pn,i=this.#An(),{pageNumbers:s,pageIds:n}=this.#fn,r=this.#mn+s.length;this.#mn=r;const a=this.#pn=new Uint32Array(r);this.#gn=new Int32Array(r);a.set(e.subarray(0,t),0);a.set(n,t);a.set(e.subarray(t),t+s.length);this.#vn(i,null,t,s);this.#fn=null}#vn(t,e=null,i=-1,s=null){const n=this.#gn,r=this.#pn,a=i+(s?.length??0),o=new Map;for(let l=0,h=this.#mn;l=i&&lt[0]-e[0]);for(let i=0,s=t.length;it-e);const e=new Map;for(let i=0,s=t.length;i({...Promise.withResolvers(),data:Ft});class PDFObjects{#wn=new Map;get(t,e=null){if(e){const i=this.#wn.getOrInsertComputed(t,dataObj);i.promise.then(()=>e(i.data));return null}const i=this.#wn.get(t);if(!i||i.data===Ft)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#wn.get(t);return!!e&&e.data!==Ft}delete(t){const e=this.#wn.get(t);if(!e||e.data===Ft)return!1;this.#wn.delete(t);return!0}resolve(t,e=null){const i=this.#wn.getOrInsertComputed(t,dataObj);if(i.data!==Ft)throw new Error(`Object already resolved ${t}.`);i.data=e;i.resolve()}clear(){for(const{data:t}of this.#wn.values())t?.bitmap?.close();this.#wn.clear()}*[Symbol.iterator](){for(const[t,{data:e}]of this.#wn)e!==Ft&&(yield[t,e])}}class TextLayer{#xn=Promise.withResolvers();#_t=null;#Cn=!1;#En=!!globalThis.FontInspector?.enabled;#Tn=null;#Sn=null;#_n=null;#Pn=0;#Dn=0;#Mn=null;#kn=null;#In=0;#Fn=0;#Bn=Object.create(null);#Rn=[];#On=null;#Ln=[];#Nn=new WeakMap;#Un=null;static#Hn=new Map;static#zn=new Map;static#Gn=new WeakMap;static#Wn=null;static#Vn=new Set;constructor({textContentSource:t,images:e,container:i,viewport:s}){if(t instanceof ReadableStream)this.#On=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#On=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#_t=this.#kn=i;this.#Tn=e;this.#Fn=s.scale*OutputScale.pixelRatio;this.#In=s.rotation;this.#_n={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:r,pageX:a,pageY:o}=s.rawDims;this.#Un=[1,0,0,-1,-a,o+r];this.#Dn=n;this.#Pn=r;TextLayer.#jn();i.style.setProperty("--min-font-size",TextLayer.#Wn);setLayerDimensions(i,s);this.#xn.promise.finally(()=>{TextLayer.#Vn.delete(this);this.#_n=null;this.#Bn=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(){this.#Tn&&this.#_t.append(this.#Tn.render());const pump=()=>{this.#Mn.read().then(({value:t,done:e})=>{if(e)this.#xn.resolve();else{this.#Sn??=t.lang;Object.assign(this.#Bn,t.styles);this.#$n(t.items);pump()}},this.#xn.reject)};this.#Mn=this.#On.getReader();TextLayer.#Vn.add(this);pump();return this.#xn.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*OutputScale.pixelRatio,s=t.rotation;if(s!==this.#In){e?.();this.#In=s;setLayerDimensions(this.#kn,{rotation:s})}if(i!==this.#Fn){e?.();this.#Fn=i;const t={div:null,properties:null,ctx:TextLayer.#Xn(this.#Sn)};for(const e of this.#Ln){t.properties=this.#Nn.get(e);t.div=e;this.#qn(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Mn?.cancel(t).catch(()=>{});this.#Mn=null;this.#xn.reject(t)}get textDivs(){return this.#Ln}get textContentItemsStr(){return this.#Rn}#$n(t){if(this.#Cn)return;this.#_n.ctx??=TextLayer.#Xn(this.#Sn);const e=this.#Ln,i=this.#Rn;for(const s of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Cn=!0;return}if(void 0!==s.str){i.push(s.str);this.#Kn(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#_t;this.#_t=document.createElement("span");this.#_t.classList.add("markedContent");s.id&&this.#_t.setAttribute("id",`${s.id}`);"Artifact"===s.tag&&(this.#_t.ariaHidden=!0);t.append(this.#_t)}else"endMarkedContent"===s.type&&(this.#_t=this.#_t.parentNode)}}#Kn(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Ln.push(e);const s=Util.transform(this.#Un,t.transform);let n=Math.atan2(s[1],s[0]);const r=this.#Bn[t.fontName];r.vertical&&(n+=Math.PI/2);let a=this.#En&&r.fontSubstitution||r.fontFamily;a=TextLayer.fontFamilyMap.get(a)||a;const o=Math.hypot(s[2],s[3]),l=o*TextLayer.#Yn(a,r,this.#Sn);let h,d;if(0===n){h=s[4];d=s[5]-l}else{h=s[4]+l*Math.sin(n);d=s[5]-l*Math.cos(n)}const c=e.style;c.left=`${(100*h/this.#Dn).toFixed(2)}%`;c.top=`${(100*d/this.#Pn).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.#En&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName);0!==n&&(i.angle=n*(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.#Nn.set(e,i);this.#_n.div=e;this.#_n.properties=i;this.#qn(this.#_n);i.hasText&&this.#_t.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#_t.append(t)}}#qn(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:a}=i;TextLayer.#Qn(s,a*this.#Fn,t);const{width:o}=s.measureText(e.textContent);o>0&&n.setProperty("--scale-x",r*this.#Fn/o)}0!==i.angle&&n.setProperty("--rotate",`${i.angle}deg`)}static cleanup(){if(!(this.#Vn.size>0)){this.#Hn.clear();for(const{canvas:t}of this.#zn.values())t.remove();this.#zn.clear()}}static#Xn(t=null){let e=this.#zn.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.#zn.set(t,e);this.#Gn.set(e,{size:0,family:""})}return e}static#Qn(t,e,i){const s=this.#Gn.get(t);if(e!==s.size||i!==s.family){t.font=`${e}px ${i}`;s.size=e;s.family=i}}static#jn(){if(null!==this.#Wn)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.#Wn=t.getBoundingClientRect().height;t.remove()}static#Yn(t,e,i){const s=this.#Hn.get(t);if(s)return s;const n=this.#Xn(i);n.canvas.width=n.canvas.height=30;this.#Qn(n,30,t);const r=n.measureText(""),a=r.fontBoundingBoxAscent,o=Math.abs(r.fontBoundingBoxDescent);n.canvas.width=n.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.#Hn.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:s}=i,n=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=getFactoryUrlProp(e.iccUrl),b=getFactoryUrlProp(e.standardFontDataUrl),y=getFactoryUrlProp(e.wasmUrl),A=!0!==e.stopAtErrors,v=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,w="boolean"==typeof e.isOffscreenCanvasSupported?e.isOffscreenCanvasSupported:!t,x="boolean"==typeof e.isImageDecoderSupported?e.isImageDecoderSupported:!t&&(FeatureTest.platform.isFirefox||!globalThis.chrome),C=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,E="boolean"==typeof e.disableFontFace?e.disableFontFace:t,T=!0===e.fontExtraProperties,S=!0===e.enableXfa,_=e.ownerDocument||globalThis.document,P=!0===e.disableRange,D=!0===e.disableStream,M=!0===e.disableAutoFetch,k=!0===e.pdfBug,I=e.CanvasFactory||(t?NodeCanvasFactory:DOMCanvasFactory),F=e.FilterFactory||(t?NodeFilterFactory:DOMFilterFactory),B=e.BinaryDataFactory||(t?NodeBinaryDataFactory:DOMBinaryDataFactory),R=!0===e.enableHWA,O=!0===e.enableWebGPU?function initGPU(){return At.init()}():Promise.resolve(!1),L=!1!==e.useWasm,N=e.pagesMapper||new PagesMapper,U="boolean"==typeof e.useSystemFonts?e.useSystemFonts:!t&&!E,H="boolean"==typeof e.useWorkerFetch?e.useWorkerFetch:!!(B===DOMBinaryDataFactory&&g&&m&&b&&y&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(b,document.baseURI)&&isValidFetchUrl(y,document.baseURI));setVerbosityLevel(u);const z={canvasFactory:new I({ownerDocument:_,enableHWA:R}),filterFactory:new F({docId:s,ownerDocument:_}),binaryDataFactory:H?null:new B({cMapUrl:g,standardFontDataUrl:b,wasmUrl:y})};if(!c){c=PDFWorker.create({verbosity:u,port:GlobalWorkerOptions.workerPort});i._worker=c}const G={docId:s,apiVersion:"5.7.284",data:r,password:l,disableAutoFetch:M,rangeChunkSize:d,docBaseUrl:p,enableXfa:S,evaluatorOptions:{maxImageSize:v,disableFontFace:E,ignoreErrors:A,isOffscreenCanvasSupported:w,isImageDecoderSupported:x,canvasMaxAreaInBytes:C,fontExtraProperties:T,useSystemFonts:U,useWasm:L,useWorkerFetch:H,cMapUrl:g,cMapPacked:m,iccUrl:f,standardFontDataUrl:b,wasmUrl:y,hasGPU:!1}},W={ownerDocument:_,pdfBug:k,styleElement:null,enableHWA:R,loadingParams:{disableAutoFetch:M,enableXfa:S}};Promise.all([c.promise,O]).then(function([,e]){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");G.evaluatorOptions.hasGPU=e;const l=c.messageHandler.sendWithPromise("GetDocRequest",G,r?[r.buffer]:null);let u;if(r);else if(h)u=new PDFDataTransportStream({pdfDataRangeTransport:h,disableRange:P,disableStream:D});else{if(!n)throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");{const e=function getNetworkStream(e){return isValidFetchUrl(e)?PDFFetchStream:t?PDFNodeStream:PDFNetworkStream}(n);u=new e({url:n,httpHeaders:a,withCredentials:o,rangeChunkSize:d,disableRange:P,disableStream:D})}}return l.then(t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(s,t,c.port),n=new WorkerTransport(e,i,u,W,z,N);i._transport=n;e.send("Ready",null)})}).catch(i._capability.reject);return i}class PDFDocumentLoadingTask{static#xs=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+PDFDocumentLoadingTask.#xs++;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{#xn=Promise.withResolvers();#Jn=null;constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s;Object.defineProperty(this,"onDataProgress",{value:()=>{!function deprecated(t){console.log("Deprecated API usage: "+t)}("`PDFDataRangeTransport.prototype.onDataProgress` - method was removed, since loading progress is now reported automatically through the `PDFDataTransportStream` class (and related code).")}})}onDataRange(t,e){this.#Jn({type:"range",begin:t,chunk:e})}onDataProgressiveRead(t){this.#xn.promise.then(()=>{this.#Jn({type:"progressiveRead",chunk:t})})}onDataProgressiveDone(){this.#xn.promise.then(()=>{this.#Jn({type:"progressiveDone"})})}transportReady(t){this.#Jn=t;this.#xn.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}getRawData(t){return this._transport.getRawData(t)}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{#Zn=!1;#tr=null;constructor(t,e,i,s,n=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=n?new StatTimer:null;this._pdfBug=n;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._intentStates=new Map;this.destroyed=!1;this.recordedBBoxes=null;this.#tr=s;this.imageCoordinates=null}clone(t){const e=new PDFPageProxy(t,this._pageInfo,this._transport,this.#tr,this._pdfBug);e.clonedFromIndex=this.clonedFromIndex??this._pageIndex;this._transport.updatePage(e);return e}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1;this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}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:s="display",annotationMode:n=p.ENABLE,transform:r=null,background:a=null,optionalContentConfigPromise:l=null,annotationCanvasMap:h=null,pageColors:d=null,printAnnotationStorage:c=null,isEditing:u=!1,recordImages:g=!1,recordOperations:m=!1,operationsFilter:f=null}){this._stats?.time("Overall");const b=this._transport.getRenderingIntent(s,n,c,u),{renderingIntent:y,cacheKey:A}=b;this.#Zn=!1;l||=this._transport.getOptionalContentConfig(y);const v=this._intentStates.getOrInsertComputed(A,makeObj);if(v.streamReaderCancelTimeout){clearTimeout(v.streamReaderCancelTimeout);v.streamReaderCancelTimeout=null}const w=!!(y&o);if(!v.displayReadyCapability){v.displayReadyCapability=Promise.withResolvers();v.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(b)}const x=!(!this._pdfBug||!globalThis.StepperManager?.enabled),C=!!e&&!this.recordedBBoxes&&(m||x),E=!!e&&!this.imageCoordinates&&g,complete=t=>{v.renderTasks.delete(_);if(C){const t=_.gfx?.dependencyTracker.take();if(t){_.stepper?.setOperatorBBoxes(t,_.gfx.dependencyTracker.takeDebugMetadata());m&&(this.recordedBBoxes=t)}}E&&!t&&(this.imageCoordinates=_.gfx?.imagesTracker.take());w&&(this.#Zn=!0);this.#er();if(t){_.capability.reject(t);this._abortOperatorList({intentState:v,reason:t instanceof Error?t:new Error(t)})}else _.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}};let T=null,S=null;(C||E)&&(S=new CanvasBBoxTracker(e,v.operatorList.length));C&&(T=new CanvasDependencyTracker(S,x));const _=new InternalRenderTask({callback:complete,params:{canvas:e,canvasContext:t,dependencyTracker:T??S,imagesTracker:E?new CanvasImagesTracker(e):null,viewport:i,transform:r,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:v.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!w,pdfBug:this._pdfBug,pageColors:d,enableHWA:this._transport.enableHWA,operationsFilter:f});(v.renderTasks||=new Set).add(_);const P=_.task;Promise.all([v.displayReadyCapability.promise,l]).then(([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&y))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");_.initializeGraphics({transparency:t,optionalContentConfig:e});_.operatorListChanged()}}).catch(complete);return P}getOperatorList({intent:t="display",annotationMode:e=p.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0),r=this._intentStates.getOrInsertComputed(n.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(n)}return r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#tr.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.#Zn=!1;return Promise.all(t)}cleanup(t=!1){this.#Zn=!0;const e=this.#er();t&&e&&(this._stats&&=new StatTimer);return e}#er(){if(!this.#Zn||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.#Zn=!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,s=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.#er()}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{#xn=Promise.withResolvers();#ir=null;#tn=null;#sr=null;static#nr=0;static#rr=!1;static#ar=new WeakMap;static{if(t){this.#rr=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const s=new URL(e,i);return i.origin===s.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;if(e){if(PDFWorker.#ar.has(e))throw new Error("Cannot use more than one PDFWorker per port.");PDFWorker.#ar.set(e,this);this.#or(e)}else this.#lr()}get promise(){return this.#xn.promise}#hr(){this.#xn.resolve();this.#ir.send("configure",{verbosity:this.verbosity})}get port(){return this.#tn}get messageHandler(){return this.#ir}#or(t){this.#tn=t;this.#ir=new MessageHandler("main","worker",t);this.#ir.on("ready",()=>{});this.#hr()}#lr(){if(PDFWorker.#rr||PDFWorker.#dr){this.#cr();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=()=>{s.abort();i.destroy();e.terminate();this.destroyed?this.#xn.reject(new Error("Worker was destroyed")):this.#cr()},s=new AbortController;e.addEventListener("error",()=>{this.#sr||terminateEarly()},{signal:s.signal});i.on("test",t=>{s.abort();if(!this.destroyed&&t){this.#ir=i;this.#tn=e;this.#sr=e;this.#hr()}else terminateEarly()});i.on("ready",t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this.#cr()}});const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this.#cr()}#cr(){if(!PDFWorker.#rr){warn("Setting up fake worker.");PDFWorker.#rr=!0}PDFWorker._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this.#xn.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this.#tn=e;const i="fake"+PDFWorker.#nr++,s=new MessageHandler(i+"_worker",i,e);t.setup(s,e);this.#ir=new MessageHandler(i,i+"_worker",e);this.#hr()}).catch(t=>{this.#xn.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0;this.#sr?.terminate();this.#sr=null;PDFWorker.#ar.delete(this.#tn);this.#tn=null;this.#ir?.destroy();this.#ir=null}static create(t){const e=this.#ar.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#dr(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#dr)return this.#dr;return(await import( /*webpackIgnore: true*/ /*@vite-ignore*/ this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{downloadInfoCapability=Promise.withResolvers();#ur=null;#pr=new Map;#gr=null;#mr=new Map;#fr=new Map;#br=new Map;#yr=null;constructor(t,e,i,s,n,r){this.messageHandler=t;this.loadingTask=e;this.#gr=i;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:s.ownerDocument,styleElement:s.styleElement});this.enableHWA=s.enableHWA;this.loadingParams=s.loadingParams;this._params=s;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.binaryDataFactory=n.binaryDataFactory;this.pagesMapper=r;this.destroyed=!1;this.destroyCapability=null;this.setupMessageHandler()}updatePage(t){const{_pageIndex:e}=t;this.#mr.set(e,t);this.#fr.set(e,Promise.resolve(t))}#Ar(t,e=null){return this.#pr.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,e))}#Ys({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:e?MathClamp(Math.round(t/e*100),0,100):NaN})}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=p.ENABLE,i=null,s=!1,n=!1){let g=a,m=Y;switch(t){case"any":g=r;break;case"display":break;case"print":g=o;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&o&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case p.DISABLE:g+=d;break;case p.ENABLE:break;case p.ENABLE_FORMS:g+=l;break;case p.ENABLE_STORAGE:g+=h;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(g+=c);n&&(g+=u);const{ids:b,hash:y}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,y].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#yr?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#mr.values())t.push(e._destroy());this.#mr.clear();this.#fr.clear();this.#br.clear();Object.hasOwn(this,"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.#pr.clear();this.filterFactory.destroy();TextLayer.cleanup();this.#gr?.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.#gr,"GetReader - no `BasePDFStream` instance available.");this.#ur=this.#gr.getFullReader();this.#ur.onProgress=t=>this.#Ys(t);e.onPull=()=>{this.#ur.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.#ur.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}});t.on("ReaderHeadersReady",async t=>{await this.#ur.headersReady;const{isStreamingSupported:e,isRangeSupported:i,contentLength:s}=this.#ur;e&&i&&(this.#ur.onProgress=null);return{isStreamingSupported:e,isRangeSupported:i,contentLength:s}});t.on("GetRangeReader",(t,e)=>{assert(this.#gr,"GetRangeReader - no `BasePDFStream` instance available.");const i=this.#gr.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.#yr=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#yr.reject(t):this.#yr.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#yr.reject(t)}return this.#yr.promise});t.on("DataLoaded",t=>{this.#Ys({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)});t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#mr.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)});t.on("commonobj",([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in s){const t=s.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const n=new FontInfo(s),r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new FontFaceObject(n,r,s.charProcOperatorList,s.extra);this.fontLoader.bind(a).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{a.fontExtraProperties||a.clearData();this.commonObjs.resolve(e,a)});break;case"CopyLocalImage":const{imageRef:o}=s;assert(o,"The imageRef must be defined.");for(const t of this.#mr.values())for(const[,i]of t.objs){if(i?.ref!==o)continue;if(!i.dataLen)return null;const t=structuredClone(i);this.commonObjs.resolve(e,t);return i.dataLen}break;case"FontPath":this.commonObjs.resolve(e,new FontPathInfo(s));break;case"Image":this.commonObjs.resolve(e,s);break;case"Pattern":const l=new PatternInfo(s);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,s])=>{if(this.destroyed)return;const n=this.#mr.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()});t.on("DocProgress",t=>{this.destroyed||this.#Ys(t)});t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&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.#ur?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){const e={pageInfos:t};let i;if(this.annotationStorage.size>0){const{map:t,transfer:s}=this.annotationStorage.serializable;e.annotationStorage=t;i=s}return this.messageHandler.sendWithPromise("ExtractPages",e,i).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.pagesMapper.getPageId(t)-1,s=this.#fr.get(e);if(s)return s;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:i}).then(t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#br.set(t.refStr,i);const s=new PDFPageProxy(e,t,this,this.pagesMapper,this._params.pdfBug);this.#mr.set(e,s);return s});this.#fr.set(e,n);return n}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.#Ar("GetFieldObjects")}hasJSActions(){return this.#Ar("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.#Ar("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.#Ar("GetOptionalContentConfig").then(e=>new OptionalContentConfig(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata";return this.#pr.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this.#ur?.filename??null,contentLength:this.#ur?.contentLength??null,hasStructTree:t[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(t){return this.messageHandler.sendWithPromise("GetRawData",t)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#mr.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#pr.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.#br.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}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}class InternalRenderTask{#vr=null;static#wr=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,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=s;this.annotationCanvasMap=n;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._imagesTracker=e.imagesTracker;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.#wr.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.#wr.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:s,background:n,dependencyTracker:r,imagesTracker:a}=this.params,o=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new CanvasGraphics(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,r,a);this.gfx.beginDrawing({transform:s,viewport:i,transparency:t,background:n});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#vr){window.cancelAnimationFrame(this.#vr);this.#vr=null}InternalRenderTask.#wr.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.#vr=window.requestAnimationFrame(()=>{this.#vr=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.#wr.delete(this._canvas);this.callback()}}}}}const Bt="5.7.284",Rt="7e5b36c2d";class ColorPicker{#xr=null;#Cr=null;#Er;#Tr=null;#Sr=!1;#_r=!1;#a=null;#Pr;#Dr=null;#y=null;static#Mr=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.#_r=!1;this.#a=t}else this.#_r=!0;this.#y=t?._uiManager||e;this.#Pr=this.#y._eventBus;this.#Er=t?.color?.toUpperCase()||this.#y?.highlightColors.values().next().value||"#FFFF98";ColorPicker.#Mr||=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.#xr=document.createElement("button");t.className="colorPicker";t.tabIndex="0";t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button");t.ariaHasPopup="true";this.#a&&(t.ariaControls=`${this.#a.id}_colorpicker_dropdown`);const e=this.#y._signal;t.addEventListener("click",this.#kr.bind(this),{signal:e});t.addEventListener("keydown",this.#Ir.bind(this),{signal:e});const i=this.#Cr=document.createElement("span");i.className="swatch";i.ariaHidden="true";i.style.backgroundColor=this.#Er;t.append(i);return t}renderMainDropdown(){const t=this.#Tr=this.#Fr();t.ariaOrientation="horizontal";t.ariaLabelledBy="highlightColorPickerLabel";return t}#Fr(){const t=document.createElement("div"),e=this.#y._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.#a&&(t.id=`${this.#a.id}_colorpicker_dropdown`);for(const[i,s]of this.#y.highlightColors){const n=document.createElement("button");n.tabIndex="0";n.role="option";n.setAttribute("data-color",s);n.title=i;n.setAttribute("data-l10n-id",ColorPicker.#Mr[i]);const r=document.createElement("span");n.append(r);r.className="swatch";r.style.backgroundColor=s;n.ariaSelected=s===this.#Er;n.addEventListener("click",this.#Br.bind(this,s),{signal:e});t.append(n)}t.addEventListener("keydown",this.#Ir.bind(this),{signal:e});return t}#Br(t,e){e.stopPropagation();this.#Pr.dispatch("switchannotationeditorparams",{source:this,type:f.HIGHLIGHT_COLOR,value:t});this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#xr){this.#kr(t);return}const e=t.target.getAttribute("data-color");e&&this.#Br(e,t)}_moveToNext(t){this.#Rr?t.target!==this.#xr?t.target.nextSibling?.focus():this.#Tr.firstElementChild?.focus():this.#kr(t)}_moveToPrevious(t){if(t.target!==this.#Tr?.firstElementChild&&t.target!==this.#xr){this.#Rr||this.#kr(t);t.target.previousSibling?.focus()}else this.#Rr&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Rr?this.#Tr.firstElementChild?.focus():this.#kr(t)}_moveToEnd(t){this.#Rr?this.#Tr.lastElementChild?.focus():this.#kr(t)}#Ir(t){ColorPicker._keyboardManager.exec(this,t)}#kr(t){if(this.#Rr){this.hideDropdown();return}this.#Sr=0===t.detail;if(!this.#Dr){this.#Dr=new AbortController;window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#y.combinedSignal(this.#Dr)})}this.#xr.ariaExpanded="true";if(this.#Tr){this.#Tr.classList.remove("hidden");return}const e=this.#Tr=this.#Fr();this.#xr.append(e)}#p(t){this.#Tr?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#Tr?.classList.add("hidden");this.#xr.ariaExpanded="false";this.#Dr?.abort();this.#Dr=null}get#Rr(){return this.#Tr&&!this.#Tr.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#_r)if(this.#Rr){this.hideDropdown();this.#xr.focus({preventScroll:!0,focusVisible:this.#Sr})}else this.#a?.unselect()}updateColor(t){this.#Cr&&(this.#Cr.style.backgroundColor=t);if(!this.#Tr)return;const e=this.#y.highlightColors.values();for(const i of this.#Tr.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#xr?.remove();this.#xr=null;this.#Cr=null;this.#Tr?.remove();this.#Tr=null}}class BasicColorPicker{#Or=null;#Lr=!1;#a=null;#y=null;static#Mr=null;constructor(t){this.#a=t;this.#y=t._uiManager;BasicColorPicker.#Mr||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#Or)return this.#Or;const{editorType:t,colorType:e,colorAndOpacityType:i,opacityType:s,color:n,opacity:r}=this.#a,a=this.#Lr=FeatureTest.isAlphaColorInputSupported&&void 0!==s,o=this.#Or=document.createElement("input");o.type="color";if(a){o.setAttribute("alpha","");const t=Util.hexNums[Math.round(255*(r??1))];o.value=(n||"#000000")+t}else o.value=n||"#000000";o.className="basicColorPicker";o.tabIndex=0;o.setAttribute("data-l10n-id",BasicColorPicker.#Mr[t]);o.addEventListener("input",()=>{if(a){const t=getRGBA(o.value);if(!t)return;const[n,r,a,l]=t,h=Util.makeHexColor(n,r,a);if(void 0!==i)this.#y.updateParams(i,{color:h,opacity:l});else{this.#y.updateParams(e,h);this.#y.updateParams(s,l)}}else this.#y.updateParams(e,o.value)},{signal:this.#y._signal});return o}update(t){if(this.#Or)if(this.#Lr){const e=Util.hexNums[Math.round(255*this.#a.opacity)];this.#Or.value=t+e}else this.#Or.value=t}updateOpacity(t){if(!this.#Or||!this.#Lr)return;const e=Util.hexNums[Math.round(255*t)];this.#Or.value=this.#a.color+e}destroy(){this.#Or?.remove();this.#Or=null}hideDropdown(){}}function makeColorComp(t){return Math.floor(255*MathClamp(t,0,1)).toString(16).padStart(2,"0")}function scaleAndClamp(t){return 255*MathClamp(t,0,1)}class ColorConverters{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}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,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[scaleAndClamp(1-Math.min(1,t+s)),scaleAndClamp(1-Math.min(1,i+s)),scaleAndClamp(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,r=1-i;return["CMYK",s,n,r,Math.min(s,n,r)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}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(V,t)}}const Ot=new WeakSet,Lt=60*(new Date).getTimezoneOffset()*1e3;class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case T.LINK:return new LinkAnnotationElement(t);case T.TEXT:return new TextAnnotationElement(t);case T.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 T.POPUP:return new PopupAnnotationElement(t);case T.FREETEXT:return new FreeTextAnnotationElement(t);case T.LINE:return new LineAnnotationElement(t);case T.SQUARE:return new SquareAnnotationElement(t);case T.CIRCLE:return new CircleAnnotationElement(t);case T.POLYLINE:return new PolylineAnnotationElement(t);case T.CARET:return new CaretAnnotationElement(t);case T.INK:return new InkAnnotationElement(t);case T.POLYGON:return new PolygonAnnotationElement(t);case T.HIGHLIGHT:return new HighlightAnnotationElement(t);case T.UNDERLINE:return new UnderlineAnnotationElement(t);case T.SQUIGGLY:return new SquigglyAnnotationElement(t);case T.STRIKEOUT:return new StrikeOutAnnotationElement(t);case T.STAMP:return new StampAnnotationElement(t);case T.FILEATTACHMENT:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Nr=null;#Ur=!1;#Hr=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!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));s&&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:s}=this.data;let n=-1/0,r=-1/0;if(e?.length>=8){for(let t=0;tr){r=e[t+1];n=e[t+2]}else e[t+1]===r&&(n=Math.max(n,e[t+2]));return[n,r]}if(i?.length>=1){for(const t of i)for(let e=0,i=t.length;er){r=t[e+1];n=t[e]}else t[e+1]===r&&(n=Math.max(n,t[e]));if(n!==1/0)return[n,r]}return s?[s[2],s[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:r}}}=this.parent;t[1]=e[3]-t[1]+e[1];t[0]=100*(t[0]-n)/i;t[1]=100*(t[1]-r)/s;return t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${g}${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(`${g}${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.#Hr?.popup||this.popup)?.remove();this.#Hr=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#Nr||={rect:this.data.rect.slice(0)});const{rect:e,popup:i}=t;e&&this.#zr(e);let s=this.#Hr?.popup||this.popup;if(!s&&i?.text){this._createPopup(i);s=this.#Hr.popup}if(s){s.updateEdited(t);if(i?.deleted){s.remove();this.#Hr=null;this.popup=null}}}resetEdited(){if(this.#Nr){this.#zr(this.#Nr.rect);this.#Hr?.popup.resetEdited();this.#Nr=null}}#zr(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:o}}}}=this;i?.splice(0,4,...t);e.left=100*(t[0]-a)/n+"%";e.top=100*(r-t[3]+o)/r+"%";if(0===s){e.width=100*(t[2]-t[0])/n+"%";e.height=100*(t[3]-t[1])/r+"%"}else this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||this instanceof LinkAnnotationElement||(n.tabIndex=0);const{style:r}=n;r.zIndex=this.parent.zIndex;this.parent.zIndex+=2;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,n);return n}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 S:r.borderStyle="solid";break;case _:r.borderStyle="dashed";break;case P:warn("Unimplemented border style: beveled");break;case D:warn("Unimplemented border style: inset");break;case M:r.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#Ur=!0;r.borderColor=Util.makeHexColor(...s)}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}=s.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,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims;let{width:n,height:r}=this;t%180!=0&&([n,r]=[r,n]);e.style.width=100*n/i+"%";e.style.height=100*r/s+"%";e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const s=i.detail[t],n=s[0],r=s.slice(1);i.target.style[e]=ColorConverters[`${n}_HTML`](r);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_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 s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const r=i[s];if(r){r({detail:{[s]:n},target:t});delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[r,a,o,l]=t.subarray(2,6);if(s===r&&n===a&&e===o&&i===l)return}const{style:r}=this.container;let a;if(this.#Ur){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0;a=["url('data:image/svg+xml;utf8,",'',``];this.container.classList.add("hasBorder")}const o=s-e,l=n-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,s=t.length;i`)}if(this.#Ur){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,s;if(t){i={str:t.text};s=t.date}else{i=e.contentsObj;s=e.modificationDate}this.#Hr=new PopupAnnotationElement({data:{color:e.color,titleObj:e.titleObj,modificationDate:s,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.#Hr||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#Hr}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:r}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof r?r:null,a=document.querySelector(`[data-element-id="${n}"]`);!a||Ot.has(a)?i.push({id:n,exportValue:s,domElement:a}):warn(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Ot.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}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 s=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);s=!0}else if(t.action){this._bindNamedAction(i,t.action,t.overlaidText);s=!0}else if(t.attachment){this.#Gr(i,t.attachment,t.overlaidText,t.attachmentDest);s=!0}else if(t.setOCGState){this.#Wr(i,t.setOCGState,t.overlaidText);s=!0}else if(t.dest){this._bindLink(i,t.dest,t.overlaidText);s=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);s=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);s=!0}else if(this.isTooltipOnly&&!s){this._bindLink(i,"");s=!0}}this.container.classList.add("linkAnnotation");if(s){this.contentElement=i;this.container.append(i)}return this.container}#Vr(){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.#Vr();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.#Vr()}#Gr(t,e,i="",s=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,s);return!1};this.#Vr()}#Wr(t,e,i=""){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};i&&(t.title=i);this.#Vr()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}});return!1})}e.overlaidText&&(t.title=e.overlaidText);t.onclick||(t.onclick=()=>!1);this.#Vr()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#Vr();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,r=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&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,s,n){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(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}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})})}_setEventListeners(t,e,i,s){for(const[n,r]of i)if("Action"===r||this.data.actions?.[r]){"Focus"!==r&&"Blur"!==r||(e||={focused:!1});this._setEventListener(t,e,n,r,s);"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)}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=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/(n*s))||1);a=Math.min(s,roundToOneDecimal(e/n))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(s,roundToOneDecimal(t/n))}r.fontSize=`calc(${a}px * var(--total-scale-factor))`;r.color=Util.makeHexColor(...i);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,s){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id)){r.domElement&&(r.domElement[e]=i);n.setValue(r.id,{[s]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let a=s.formattedValue||this.data.textContent?.join("\n")||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=a??n;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type=this.data.password?"password":"text";i.setAttribute("value",a??n);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",s=>{t.setValue(e,{value:s.target.value});this.setPropertyOnSiblings(i,"value",s.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),s=[i.getHours(),i.getMinutes(),i.getSeconds()];e.value=s.map(t=>t.toString().padStart(2,"0")).join(":")}else e.value=new Date(t-Lt).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 s={value(i){o.userValue=i.detail.value??"";c||t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s;null!=s&&i.target!==document.activeElement&&(i.target.value=s);const n={formattedValue:s};c&&(n.value=s);t.setValue(e,n)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",s);let r=o.userValue;if(r&&!(r.length<=s)){r=r.slice(0,s);n.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:n.selectionStart,selEnd:n.selectionEnd}})}}};this._dispatchEventFromSandbox(s,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:s}=t.target;if(o.lastCommittedValue!==s){o.lastCommittedValue=s;o.userValue=s;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}});const s=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:n}=i;if(c){if(n&&"time"===h){const t=n.split(":").map(t=>parseInt(t,10));n=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf();i.step=""}else{n.includes("T")||(n=`${n}T00:00`);n=new Date(n).valueOf()}i.type="text"}o.userValue=n;o.lastCommittedValue!==n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});s(t)});this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:r,selectionEnd:a}=s;let l=r,h=a;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,r).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.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:n,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 s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof s){s="Off"!==s;t.setValue(i,{value:s})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");Ot.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="checkbox";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.setAttribute("exportValue",e.exportValue);n.tabIndex=0;n.addEventListener("change",s=>{const{name:n,checked:r}=s.target;for(const s of this._getElementsByName(n,i)){const i=r&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i);t.setValue(s.id,{value:i})}t.setValue(i,{value:r})});n.addEventListener("resetform",t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue});if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",e=>{const s={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)});this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);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 s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s){s=s!==e.buttonValue;t.setValue(i,{value:s})}if(s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");Ot.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="radio";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.tabIndex=0;n.addEventListener("change",e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})});n.addEventListener("resetform",t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue});if(this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e);t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)});this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);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}),s=document.createElement("select");Ot.add(s);s.setAttribute("data-element-id",e);s.disabled=this.data.readOnly;this._setRequired(s,this.data.required);s.name=this.data.fieldName;s.tabIndex=0;let n=this.data.combo&&this.data.options.length>0;if(!this.data.combo){s.size=this.data.options.length;this.data.multiSelect&&(s.multiple=!0)}s.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e});const fixDisplayValue=(t,e)=>{const i=e.replaceAll(" "," ");t.textContent=i;i!==e&&t.setAttribute("display-value",e)};for(const t of this.data.options){const e=document.createElement("option");fixDisplayValue(e,t.displayValue);e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);n=!1}s.append(e)}let r=null;if(n){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);s.prepend(t);r=()=>{t.remove();s.removeEventListener("input",r);r=null};s.addEventListener("input",r)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?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.getAttribute("display-value")||t.textContent,exportValue:t.value}))};if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",i=>{const n={value(i){r?.();const n=i.detail.value,o=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});a=getValue(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,r=i.detail.remove;n[r].selected=!1;s.remove(r);if(n.length>0){-1===Array.prototype.findIndex.call(n,t=>t.selected)&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]});a=getValue(!1)},insert(i){const{index:n,displayValue:r,exportValue:o}=i.detail.insert,l=s.children[n],h=document.createElement("option");fixDisplayValue(h,r);h.value=o;l?l.before(h):s.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");fixDisplayValue(n,e);n.value=i;s.append(n)}s.options.length>0&&(s.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:getValue(!0)});a=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)});s.addEventListener("input",i=>{const s=getValue(!0),n=getValue(!1);t.setValue(e,{value:s});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})});this._setEventListeners(s,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 s.addEventListener("input",function(i){t.setValue(e,{value:getValue(!0)})});this.data.combo&&this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i,parent:s}=t,n=!!s._commentManager;super(t,{isRenderable:!n&&AnnotationElement._hasPopupData(e)});this.elements=i;if(n&&AnnotationElement._hasPopupData(e)){const t=this.popup=this.#jr();for(const e of i)e.popup=t}else this.popup=null}#jr(){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.#jr(),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=>`${W}${t}`).join(","));return this.container}}class PopupElement{#j=null;#$r=this.#Ir.bind(this);#Xr=this.#qr.bind(this);#Kr=this.#Yr.bind(this);#Qr=this.#Jr.bind(this);#Zr=null;#_t=null;#ta=null;#ea=null;#ia=null;#sa=null;#na=null;#ra=!1;#aa=null;#oa=null;#F=null;#la=null;#ha=null;#ve=null;#da=null;#fe=null;#ca=null;#Nr=null;#ua=!1;#pa=null;#ga=null;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:r,richText:a,parent:o,rect:l,parentRect:h,open:d,commentManager:c=null}){this.#_t=t;this.#ca=s;this.#ta=r;this.#fe=a;this.#sa=o;this.#Zr=e;this.#da=l;this.#na=h;this.#ia=i;this.#j=c;this.#pa=i[0];this.#ea=PDFDateString.toDateObject(n);this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup());if(!c){this.#ma();this.#_t.hidden=!0;d&&this.#Jr()}}#ma(){if(this.#oa)return;this.#oa=new AbortController;const{signal:t}=this.#oa;for(const e of this.trigger){e.addEventListener("click",this.#Qr,{signal:t});e.addEventListener("pointerenter",this.#Kr,{signal:t});e.addEventListener("pointerleave",this.#Xr,{signal:t});e.classList.add("popupTriggerArea")}for(const e of this.#ia)e.container?.addEventListener("keydown",this.#$r,{signal:t})}#fa(){const t=this.#ia.find(t=>t.hasCommentButton);t&&(this.#ha=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#la){this.#la.parentNode||this.#pa.container.after(this.#la);return}this.#ha||this.#fa();if(!this.#ha)return;const{signal:t}=this.#oa=new AbortController,e=this.#pa.hasOwnCommentButton,togglePopup=()=>{this.#j.toggleCommentPopup(this,!0,void 0,!e)},showPopup=()=>{this.#j.toggleCommentPopup(this,!1,!0,!e)},hidePopup=()=>{this.#j.toggleCommentPopup(this,!1,!1)};if(e){this.#la=this.#pa.container;for(const e of this.trigger){e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.addEventListener("keydown",this.#$r,{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.#la=document.createElement("button");e.className="annotationCommentButton";const i=this.#pa.container;e.style.zIndex=parseInt(i.style.zIndex,10)+1;e.tabIndex=0;e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.setAttribute("data-l10n-id","pdfjs-show-comment-button");this.#ba();this.#ya();e.addEventListener("keydown",this.#$r,{signal:t});e.addEventListener("click",togglePopup,{signal:t});e.addEventListener("pointerenter",showPopup,{signal:t});e.addEventListener("pointerleave",hidePopup,{signal:t});i.after(e)}}#ya(){if(this.#pa.extraPopupElement&&!this.#pa.editor)return;this.#la||this.renderCommentButton();const[t,e]=this.#ha,{style:i}=this.#la;i.left=`calc(${t}%)`;i.top=`calc(${e}% - var(--comment-button-dim))`}#ba(){if(!this.#pa.extraPopupElement){this.#la||this.renderCommentButton();this.#la.style.backgroundColor=this.commentButtonColor||""}}get commentButtonColor(){const{color:t,opacity:e}=this.#pa.commentData;return t?this.#sa._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#la?.focus()},0)}getData(){const{richText:t,color:e,opacity:i,creationDate:s,modificationDate:n}=this.#pa.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:s,modificationDate:n}}get elementBeforePopup(){return this.#la}get comment(){this.#ga||=this.#pa.commentText;return this.#ga}set comment(t){t!==this.comment&&(this.#pa.commentText=this.#ga=t)}focus(){this.#pa.container?.focus()}get parentBoundingClientRect(){return this.#pa.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#la){this.#la.classList.toggle("selected",t);this.#la.ariaExpanded=e}}setSelectedCommentButton(t){this.#la.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#ve)return this.#ve;const{x:t,y:e,height:i}=this.#la.getBoundingClientRect(),{x:s,y:n,width:r,height:a}=this.#pa.layer.getBoundingClientRect();return[(t-s)/r,(e+i-n)/a]}set commentPopupPosition(t){this.#ve=t}hasDefaultPopupPosition(){return null===this.#ve}get commentButtonPosition(){return this.#ha}get commentButtonWidth(){return this.#la.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,i]=this.#ve||this.commentButtonPosition.map(t=>t/100),s=this.parentBoundingClientRect,{x:n,y:r,width:a,height:o}=s;this.#j.showDialog(null,this,n+e*a,r+i*o,{...t,parentDimensions:s})}render(){if(this.#aa)return;const t=this.#aa=document.createElement("div");t.className="popup";if(this.#Zr){const e=t.style.outlineColor=Util.makeHexColor(...this.#Zr);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");e.className="header";if(this.#ca?.str){const t=document.createElement("span");t.className="title";e.append(t);({dir:t.dir,str:t.textContent}=this.#ca)}t.append(e);if(this.#ea){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.#ea.valueOf()}));t.dateTime=this.#ea.toISOString();e.append(t)}renderRichText({html:this.#Aa||this.#ta.str,dir:this.#ta?.dir,className:"popupContent"},t);this.#_t.append(t)}get#Aa(){const t=this.#fe,e=this.#ta;return!t?.str||e?.str&&e.str!==t.str?null:this.#fe.html||null}get#va(){return this.#Aa?.attributes?.style?.fontSize||0}get#wa(){return this.#Aa?.attributes?.style?.color||null}#xa(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#wa,fontSize:this.#va?`calc(${this.#va}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}#Ir(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#ra)&&this.#Jr()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#j){if(i){this.remove();this.#ga=null}else if(e)if(e.deleted)this.remove();else{this.#ba();this.#ga=e.text}if(t){this.#ha=null;this.#fa();this.#ya()}}else if(i||e?.deleted)this.remove();else{this.#ma();this.#Nr||={contentsObj:this.#ta,richText:this.#fe};t&&(this.#F=null);if(e&&e.text){this.#fe=this.#xa(e.text);this.#ea=PDFDateString.toDateObject(e.date);this.#ta=null}this.#aa?.remove();this.#aa=null}}resetEdited(){if(this.#Nr){({contentsObj:this.#ta,richText:this.#fe}=this.#Nr);this.#Nr=null;this.#aa?.remove();this.#aa=null;this.#F=null}}remove(){this.#oa?.abort();this.#oa=null;this.#aa?.remove();this.#aa=null;this.#ua=!1;this.#ra=!1;this.#la?.remove();this.#la=null;if(this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#Ca(){if(null!==this.#F)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:s,pageY:n}}}=this.#sa;let r=!!this.#na,a=r?this.#na:this.#da;for(const t of this.#ia)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.#F=[100*(h-s)/e,100*(d-n)/i];const{style:c}=this.#_t;c.left=`${this.#F[0]}%`;c.top=`${this.#F[1]}%`}#Jr(){if(this.#j)this.#j.toggleCommentPopup(this,!1);else{this.#ra=!this.#ra;if(this.#ra){this.#Yr();this.#_t.addEventListener("click",this.#Qr);this.#_t.addEventListener("keydown",this.#$r)}else{this.#qr();this.#_t.removeEventListener("click",this.#Qr);this.#_t.removeEventListener("keydown",this.#$r)}}}#Yr(){this.#aa||this.render();if(this.isVisible)this.#ra&&this.#_t.classList.add("focused");else{this.#Ca();this.#_t.hidden=!1;this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex,10)+1e3}}#qr(){this.#_t.classList.remove("focused");if(!this.#ra&&this.isVisible){this.#_t.hidden=!0;this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex,10)-1e3}}forceHide(){this.#ua=this.isVisible;this.#ua&&(this.#_t.hidden=!0)}maybeShow(){if(!this.#j){this.#ma();if(this.#ua){this.#aa||this.#Yr();this.#ua=!1;this.#_t.hidden=!1}}}get isVisible(){return!this.#j&&!1===this.#_t.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=m.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{#Ea=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=this.#Ea=this.svgFactory.createElement("svg:line");n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]);n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]);n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]);n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]);n.setAttribute("stroke-width",t.borderStyle.width||1);n.setAttribute("stroke","transparent");n.setAttribute("fill","transparent");s.append(n);this.container.append(s);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Ea}addHighlightArea(){this.container.classList.add("highlightArea")}}class SquareAnnotationElement extends AnnotationElement{#Ta=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=t.borderStyle.width,r=this.#Ta=this.svgFactory.createElement("svg:rect");r.setAttribute("x",n/2);r.setAttribute("y",n/2);r.setAttribute("width",e-n);r.setAttribute("height",i-n);r.setAttribute("stroke-width",n||1);r.setAttribute("stroke","transparent");r.setAttribute("fill","transparent");s.append(r);this.container.append(s);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Ta}addHighlightArea(){this.container.classList.add("highlightArea")}}class CircleAnnotationElement extends AnnotationElement{#Sa=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=t.borderStyle.width,r=this.#Sa=this.svgFactory.createElement("svg:ellipse");r.setAttribute("cx",e/2);r.setAttribute("cy",i/2);r.setAttribute("rx",e/2-n/2);r.setAttribute("ry",i/2-n/2);r.setAttribute("stroke-width",n||1);r.setAttribute("stroke","transparent");r.setAttribute("fill","transparent");s.append(r);this.container.append(s);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Sa}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolylineAnnotationElement extends AnnotationElement{#_a=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:s},width:n,height:r}=this;if(!e)return this.container;const a=this.svgFactory.create(n,r,!0);let o=[];for(let i=0,s=e.length;i=0&&n.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#Da.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Ia()});if(!e.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}else i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#ka}addHighlightArea(){this.container.classList.add("highlightArea")}#Ia(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Fa=null;#Ba=null;#G=null;#Ra=new Map;#Oa=null;#La=null;#ia=[];#Na=!1;zIndex=0;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:r,structTreeLayer:a,commentManager:o,linkService:l,annotationStorage:h}){this.div=t;this.#Fa=e;this.#Ba=i;this.#Oa=a||null;this.#La=l||null;this.#G=h||new AnnotationStorage;this.page=n;this.viewport=r;this._annotationEditorUIManager=s;this._commentManager=o||null}hasEditableAnnotations(){return this.#Ra.size>0}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const s=new Map,n=[],r={data:null,layer:i,linkService:this.#La,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:this.#G,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===T.POPUP;if(e){const e=s.get(t.id);if(!e)continue;if(!this._commentManager){n.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.#ia.push(i);t.popupRef&&s.getOrInsertComputed(t.popupRef,makeArr).push(i)}const a=i.render();t.hidden&&(a.style.visibility="hidden");if(i._isEditable){this.#Ra.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}await this.#Ua();for(const t of n){const e=r.elements=s.get(t.id);r.data=t;const i=AnnotationElementFactory.create(r);if(!i.isRenderable)continue;const n=i.render();i.contentElement.id=`${W}${t.id}`;t.hidden&&(n.style.visibility="hidden");e.at(-1).container.after(n)}this.#Ha()}async#Ua(){if(0===this.#ia.length)return;this.div.replaceChildren();const t=[];if(!this.#Na){this.#Na=!0;for(const{contentElement:e,data:{id:i}}of this.#ia){const s=e.id=`${W}${i}`;t.push(this.#Oa?.getAriaAttributes(s).then(t=>{if(t)for(const[i,s]of t)e.setAttribute(i,s)}))}}this.#ia.sort(({data:{rect:[t,e,i,s]}},{data:{rect:[n,r,a,o]}})=>{if(t===i&&e===s)return 1;if(n===a&&r===o)return-1;const l=(e+s)/2,h=(r+o)/2;if(l>=o&&h<=e)return-1;if(h>=s&&l<=r)return 1;return(t+i)/2-(n+a)/2});const e=document.createDocumentFragment();for(const t of this.#ia){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.#Fa)for(const t of this.#ia)this.#Fa.addPointerInTextLayer(t.contentElement,!1)}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#La,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=`${W}${i.id}`;this.#ia.push(t)}}await this.#Ua()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#Ha();e.hidden=!1}#Ha(){if(!this.#Ba)return;const t=this.div;for(const[e,i]of this.#Ba){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i);const r=this.#Ra.get(e);if(r)if(r._hasNoCanvas){this._annotationEditorUIManager?.setMissingCanvas(e,s.id,i);r._hasNoCanvas=!1}else r.canvas=i}this.#Ba.clear()}getEditableAnnotations(){return this.#Ra.values()}getEditableAnnotation(t){return this.#Ra.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:i,rotation:s}=t,n=new EditorAnnotationElement({data:{id:i,rect:t.getPDFRect(),rotation:s},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#La,annotationStorage:this.#G});n.render();n.contentElement.id=`${W}${i}`;n.createOrUpdatePopup();this.#ia.push(n);return n}removeAnnotation(t){const e=this.#ia.findIndex(e=>e.data.id===t);if(e<0)return;const[i]=this.#ia.splice(e,1);this.#Fa?.removePointerInTextLayer(i.contentElement)}updateFakeAnnotations(t){if(0!==t.length){for(const e of t)e.updateFakeAnnotationElement(this);this.#Ua()}}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}static get _defaultBorderStyle(){return shadow(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:S,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const Nt=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#za="";#Ga=`${this.id}-editor`;#Wa=null;#va;_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=m.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.color=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#va=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 f.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case f.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case f.FREETEXT_SIZE:this.#Va(e);break;case f.FREETEXT_COLOR:this.#ba(e)}}static get defaultPropertiesToUpdate(){return[[f.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[f.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[f.FREETEXT_SIZE,this.#va],[f.FREETEXT_COLOR,this.color]]}get toolbarButtons(){this._colorPicker||=new BasicColorPicker(this);return[["colorPicker",this._colorPicker]]}get colorType(){return f.FREETEXT_COLOR}#Va(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`;this.translate(0,-(t-this.#va)*this.parentScale);this.#va=t;this.#ja()},e=this.#va;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:f.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color;this._colorPicker?.update(this.color);super.onUpdatedColor()}#ba(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:f.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.#va)*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.#Wa=new AbortController;const t=this._uiManager.combinedSignal(this.#Wa);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.#Ga);this._isDraggable=!0;this.#Wa?.abort();this.#Wa=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()}#$a(){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.#Xa(i));e=i}return t.join("\n")}#ja(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=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=s;e.classList.toggle("hidden",n)}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.#za,e=this.#za=this.#$a().trimEnd();if(t===e)return;const setText=t=>{this.#za=t;if(t){this.#qa();this._uiManager.rebuild(this);this.#ja()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#ja()}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.#Ga);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.#va}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,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=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+(n[0]-h)/o;u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o;u=e-(n[1]-d)/l;[r,a]=[a,-r];break;case 180:c=t-this.width+(n[0]-h)/o;u=e-(n[1]-d)/l;[r,a]=[-r,-a];break;case 270:c=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-d-this.width*o)/l;[r,a]=[-a,r]}this.setAt(c*i,u*s,r,a)}else this._moveAfterPaste(t,e);this.#qa();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Xa(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Nt,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=FreeTextEditor.#Ka(e.getData("text")||"").replaceAll(Nt,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize();n.deleteFromDocument();const r=n.getRangeAt(0);if(!s.includes("\n")){r.insertNode(document.createTextNode(s));this.editorDiv.normalize();n.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(Nt,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Xa(i)):e=h}l.push(a.nodeValue.slice(0,o).replaceAll(Nt,""))}else if(a===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Xa(i))}}this.#za=`${l.join("\n")}${s}${h.join("\n")}`;this.#qa();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}n.removeAllRanges();n.addRange(d)}#qa(){this.editorDiv.replaceChildren();if(this.#za)for(const t of this.#za.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Ya(){return this.#za.replaceAll(" "," ")}static#Ka(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 s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:r,id:a,popupRef:o,richText:l,contentsObj:h,creationDate:d,modificationDate:c},textContent:u,textPosition:p,parent:{page:{pageNumber:g}}}=t;if(!u||0===u.length)return null;s=t={annotationType:m.FREETEXT,color:Array.from(i),fontSize:e,value:u.join("\n"),position:p,pageIndex:g-1,rect:n.slice(0),rotation:r,annotationElementId:a,id:a,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:d,modificationDate:c}}const n=await super.deserialize(t,e,i);n.#va=t.fontSize;n.color=Util.makeHexColor(...t.color);n.#za=FreeTextEditor.#Ka(t.value);n._initialData=s;t.comment&&n.setCommentData(t);return n}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.#va,value:this.#Ya()});this.addComment(i);if(t){i.isCopy=!0;return i}if(this.annotationElementId&&!this.#Qa(i))return null;i.id=this.annotationElementId;return i}#Qa(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==s[e])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:i}=e;i.fontSize=`calc(${this.#va}px * var(--total-scale-factor))`;i.color=this.color;e.replaceChildren();for(const t of this.#za.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.#za}});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,s,n,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.#bo(i);return i.join(" ")}#mo(){const[t,e,i,s]=this.#Ja,[n,r,a,o]=this.#go();return`M${(this.#so[2]-t)/i} ${(this.#so[3]-e)/s} L${(this.#so[4]-t)/i} ${(this.#so[5]-e)/s} L${n} ${r} L${a} ${o} L${(this.#so[16]-t)/i} ${(this.#so[17]-e)/s} L${(this.#so[14]-t)/i} ${(this.#so[15]-e)/s} Z`}#bo(t){const e=this.#Za;t.push(`L${e[4]} ${e[5]} Z`)}#fo(t){const[e,i,s,n]=this.#Ja,r=this.#so.subarray(4,6),a=this.#so.subarray(16,18),[o,l,h,d]=this.#go();t.push(`L${(r[0]-e)/s} ${(r[1]-i)/n} L${o} ${l} L${h} ${d} L${(a[0]-e)/s} ${(a[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,r){return new FreeDrawOutline(t,e,i,s,n,r)}getOutlines(){const t=this.#io,e=this.#Za,i=this.#so,[s,n,r,a]=this.#Ja,o=new Float32Array((this.#do?.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.#vo(l,h);return this.newFreeDrawOutline(l,o,this.#Ja,this.#lo,this.#to,this.#eo)}#yo(t){const e=this.#so,[i,s,n,r]=this.#Ja,[a,o,l,h]=this.#go(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/r,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/r,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/r],0);return this.newFreeDrawOutline(d,t,this.#Ja,this.#lo,this.#to,this.#eo)}#vo(t,e){const i=this.#Za;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#Ao(t,e){const i=this.#so.subarray(4,6),s=this.#so.subarray(16,18),[n,r,a,o]=this.#Ja,[l,h,d,c]=this.#go();t.set([NaN,NaN,NaN,NaN,(i[0]-n)/a,(i[1]-r)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-n)/a,(s[1]-r)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Ja;#wo=new Float32Array(4);#to;#eo;#do;#lo;#xo;constructor(t,e,i,s,n,r){super();this.#xo=t;this.#do=e;this.#Ja=i;this.#lo=s;this.#to=n;this.#eo=r;this.firstPoint=[NaN,NaN];this.lastPoint=[NaN,NaN];this.#Co(r);const[a,o,l,h]=this.#wo;for(let e=0,i=t.length;ep){a=u;o=p}else o===p&&(a=d(a,u));if(hc[1]){a=c[0];o=c[1]}else o===c[1]&&(a=d(a,c[0]));if(ht[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#So)if(e[3]){t.push(...this.#Po(e));this.#Do(e)}else{this.#Mo(e);t.push(...this.#Po(e))}return this.#ko(t)}#ko(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,r,a,o,l]=t;i.delete(t);let h=e,d=r;n=[e,a];s.push(n);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){n.push(h,d,e,d===r?r:a);h=e}d=d===r?a:r}n.push(h,d)}return new HighlightOutline(s,this.#Ja,this.#Eo,this.#To)}#Io(t){const e=this.#_o;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,r=e[n][0];if(r===t)return n;r=0;s--){const[i,n]=this.#_o[s];if(i!==t)break;if(i===t&&n===e){this.#_o.splice(s,1);return}}}#Po(t){const[e,i,s]=t,n=[[e,i,s]],r=this.#Io(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===r)return[];n.splice(t,1);t--;r--}else{n[t][2]=i;o>s&&n.push([e,s,o])}}}return n}}class HighlightOutline extends Outline{#Ja;#Fo;constructor(t,e,i,s){super();this.#Fo=t;this.#Ja=e;this.firstPoint=i;this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#Fo){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n-1){this.#Wo=!0;this.#$o(t);this.#Xo()}else if(this.#Oo){this.#Bo=t.anchorNode;this.#Ro=t.anchorOffset;this.#Uo=t.focusNode;this.#Ho=t.focusOffset;this.#qo();this.#Xo();this.rotate(this.rotation)}this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}get telemetryInitialData(){return{action:"added",type:this.#Wo?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#ho,methodOfCreation:this.#jo}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#qo(){const t=new HighlightOutliner(this.#Oo,.001);this.#Go=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#Go.box;const e=new HighlightOutliner(this.#Oo,.0025,.001,"ltr"===this._uiManager.direction);this.#No=e.getOutlines();const{firstPoint:i}=this.#Go;this.#Eo=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];const{lastPoint:s}=this.#No;this.#To=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#$o({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#Go=t;this.#No=t.getNewOutline(this.#ho/2+1.5,.0025);if(e>=0){this.#S=e;this.#Lo=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Vo=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#No.box,path:{d:this.#No.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#S,{bbox:HighlightEditor.#Ko(this.#Go.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Vo,{bbox:HighlightEditor.#Ko(this.#No.box,e),path:{d:this.#No.toSVGPath()}})}const[s,n,r,a]=t.box;switch(this.rotation){case 0:this.x=s;this.y=n;this.width=r;this.height=a;break;case 90:{const[t,e]=this.parentDimensions;this.x=n;this.y=1-s;this.width=r*e/t;this.height=a*t/e;break}case 180:this.x=1-s;this.y=1-n;this.width=r;this.height=a;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n;this.y=s;this.width=r*e/t;this.height=a*t/e;break}}const{firstPoint:o}=t;this.#Eo=[(o[0]-s)/r,(o[1]-n)/a];const{lastPoint:l}=this.#No;this.#To=[(l[0]-s)/r,(l[1]-n)/a]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case f.HIGHLIGHT_COLOR:HighlightEditor._defaultColor=e;break;case f.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#To}get commentButtonPosition(){return this.#Eo}updateParams(t,e){switch(t){case f.HIGHLIGHT_COLOR:this.#ba(e);break;case f.HIGHLIGHT_THICKNESS:this.#Yo(e)}}static get defaultPropertiesToUpdate(){return[[f.HIGHLIGHT_COLOR,HighlightEditor._defaultColor],[f.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[f.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[f.HIGHLIGHT_THICKNESS,this.#ho||HighlightEditor._defaultThickness],[f.HIGHLIGHT_FREE,this.#Wo]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#S,{root:{fill:this.color,"fill-opacity":this.opacity}});this.#r?.updateColor(this.color);super.onUpdatedColor()}#ba(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:f.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#Yo(t){const e=this.#ho,setThickness=t=>{this.#ho=t;this.#Qo(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:f.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){if(this._uiManager.highlightColors){return[["colorPicker",this.#r=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.#Jo())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Jo())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#Zo();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Xo();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#Zo();else if(t){this.#Xo(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#Qo(t){if(this.#Wo){this.#$o({highlightOutlines:this.#Go.getNewOutline(t/2)});this.fixAndSetPosition();this.setDims()}}#Zo(){if(null!==this.#S&&this.parent){this.parent.drawLayer.remove(this.#S);this.#S=null;this.parent.drawLayer.remove(this.#Vo);this.#Vo=null}}#Xo(t=this.parent){if(null===this.#S){({id:this.#S,clipPathId:this.#Lo}=t.drawLayer.draw({bbox:this.#Go.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#Wo},path:{d:this.#Go.toSVGPath()}},!1,!0));this.#Vo=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Wo},bbox:this.#No.box,path:{d:this.#No.toSVGPath()}},this.#Wo);this.#zo&&(this.#zo.style.clipPath=this.#Lo)}}static#Ko([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Wo){t=(t-this.rotation+360)%360;i=HighlightEditor.#Ko(this.#Go.box,t)}else i=HighlightEditor.#Ko([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#S,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Vo,{bbox:HighlightEditor.#Ko(this.#No.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#be){t.setAttribute("aria-label",this.#be);t.setAttribute("role","mark")}this.#Wo?t.classList.add("free"):this.div.addEventListener("keydown",this.#tl.bind(this),{signal:this._uiManager._signal});const e=this.#zo=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#Lo;this.setDims();bindEvents(this,this.#zo,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Vo,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Vo,{rootClass:{hovered:!1}})}#tl(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#el(!0);break;case 1:case 3:this.#el(!1)}}#el(t){if(!this.#Bo)return;const e=window.getSelection();t?e.setPosition(this.#Bo,this.#Ro):e.setPosition(this.#Uo,this.#Ho)}select(){super.select();this.#Vo&&this.parent?.drawLayer.updateProperties(this.#Vo,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Vo){this.parent?.drawLayer.updateProperties(this.#Vo,{rootClass:{selected:!1}});this.#Wo||this.#el(!1)}}get _mustFixPosition(){return!this.#Wo}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#S,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Vo,{rootClass:{hidden:!t}})}}#Jo(){return this.#Wo?this.rotation:0}#il(){if(this.#Wo)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#Oo,r=new Float32Array(8*n.length);let a=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l)*e+s;r[a]=r[a+4]=n;r[a+1]=r[a+3]=c;r[a+2]=r[a+6]=n+h*t;r[a+5]=r[a+7]=c-d*e;a+=8}return r}#sl(t){return this.#Go.serialize(t,this.#Jo())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:r,y:a,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#nl(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.#rl.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({x:s,y:n},[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#rl(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#nl(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 s=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:n,id:r,color:a,opacity:o,popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:p}}}=t;s=t={annotationType:m.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:n,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:n,id:r,color:a,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:p}}}=t;s=t={annotationType:m.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}const{color:n,quadPoints:r,inkLists:a,outlines:o,opacity:l}=t,h=await super.deserialize(t,e,i);h.color=Util.makeHexColor(...n);h.opacity=l||1;a&&(h.#ho=t.thickness);h._initialData=s;t.comment&&h.setCommentData(t);const[d,c]=h.pageDimensions,[u,p]=h.pageTranslation;if(r){const t=h.#Oo=[];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{#al=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.#al[t]=e}toSVGProperties(){const t=this.#al;this.#al=Object.create(null);return{root:t}}reset(){this.#al=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#ol=null;#ll;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#hl=null;static#dl=null;static#cl=null;static _INNER_MARGIN=3;constructor(t){super(t);this.#ll=t.mustBeCommitted||!1;this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color);super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(t){if(t.drawOutlines){this.#ul(t);this.#Xo()}}#ul({drawOutlines:t,drawId:e,drawingOptions:i}){this.#ol=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.#pl(t,this.parent);this.#gl(t.box)}#pl(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[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;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.#hl.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,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],setter=i=>{s.updateProperty(e,i);const n=this.#ol.updateProperty(e,i);n&&this.#gl(n);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties());t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,e){const i=this.constructor.typesMap.get(this.colorType),s=this.constructor.typesMap.get(this.opacityType),n=this._drawingOptions,r=n[i],a=n[s],setter=(t,e)=>{n.updateProperty(i,t);n.updateProperty(s,e);this.#ol.updateProperty(i,t);this.#ol.updateProperty(s,e);this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties());this.onUpdatedColor();this.onUpdatedOpacity()};this.addCommands({cmd:setter.bind(this,t,e),undo:setter.bind(this,r,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:f.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ol.getPathResizingSVGProperties(this.#ml()),{bbox:this.#fl()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ol.getPathResizedSVGProperties(this.#ml()),{bbox:this.#fl()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#fl()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ol.getPathTranslatedSVGProperties(this.#ml(),this.parentDimensions),{bbox:this.#fl()}))}_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.#ll){this.#ll=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#Zo();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Xo();this.#gl(this.#ol.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#Zo()}else if(t){this._uiManager.addShouldRescale(this);this.#Xo(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#Zo(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#Xo(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#pl(this.#ol,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#bl([t,e,i,s]){const{parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[e,1-t,i*(r/n),s*(n/r)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(r/n),s*(n/r)];default:return[t,e,i,s]}}#ml(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[1-e,t,i*(n/r),s*(r/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/r),s*(r/n)];default:return[t,e,i,s]}}#gl(t){[this.x,this.y,this.width,this.height]=this.#bl(t);if(this.div){this.fixAndSetPosition();this.setDims()}this._onResized()}#fl(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:r,parentDimensions:[a,o]}=this;switch((4*n+r)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(a/o),s*(o/a),i*(a/o)];case 5:return[1-e,t,i*(a/o),s*(o/a)];case 6:return[1-t-s*(o/a),1-e,s*(o/a),i*(a/o)];case 7:return[e-i*(a/o),1-t-s*(o/a),i*(a/o),s*(o/a)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/a),e,s*(o/a),i*(a/o)];case 13:return[1-e-i*(a/o),t-s*(o/a),i*(a/o),s*(o/a)];case 14:return[1-t,1-e-i*(a/o),s*(o/a),i*(a/o)];case 15:return[e,1-t,i*(a/o),s*(o/a)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#fl()},this.#ol.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#gl(this.#ol.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 s=document.createElement("div");i.append(s);s.setAttribute("aria-hidden","true");s.className="internal";this.setDims();this._uiManager.addShouldRescale(this);this.disableEditing();this._isCopy&&this._moveAfterPaste(t,e);return i}static createDrawerInstance(t,e,i,s,n){unreachable("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:r,offsetY:a,pointerId:o,pointerType:l}=s;if(CurrentPointers.isInitializedAndDifferentPointerType(l))return;const{viewport:{rotation:h}}=t,{width:d,height:c}=n.getBoundingClientRect(),u=DrawingEditor.#dl=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.#hl.isCancellable()){DrawingEditor.#hl.removeLastElement();DrawingEditor.#hl.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}},{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",t=>{CurrentPointers.isSameTimeStamp(t.timeStamp)&&stopEvent(t)},{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#hl)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#hl.startNew(r,a,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#hl=this.createDrawerInstance(r,a,d,c,h);DrawingEditor.#cl=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#cl.toSVGProperties(),DrawingEditor.#hl.defaultSVGProperties),!0,!1))}}static _drawMove(t){CurrentPointers.isSameTimeStamp(t.timeStamp);if(!DrawingEditor.#hl)return;const{offsetX:e,offsetY:i,pointerId:s}=t;if(CurrentPointers.isSamePointerId(s))if(CurrentPointers.isUsingMultiplePointers())this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#hl.add(e,i));CurrentPointers.setTimeStamp(t.timeStamp);stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#hl=null;DrawingEditor.#cl=null;CurrentPointers.clearTimeStamp()}if(DrawingEditor.#dl){DrawingEditor.#dl.abort();DrawingEditor.#dl=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.#hl.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#hl,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:f.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(f.DRAW_STEP);if(!DrawingEditor.#hl.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#hl.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#cl,mustBeCommitted:!t});this._cleanup(!0);return r}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,r){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#ul({drawOutlines:o});l.#Xo();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#ol.serialize([e,i,s,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getPDFRect()});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#so=new Float64Array(6);#Ea;#yl;#In;#ho;#do;#Al="";#vl=0;#Fo=new InkDrawOutline;#wl;#xl;constructor(t,e,i,s,n,r){this.#wl=i;this.#xl=s;this.#In=n;this.#ho=r;[t,e]=this.#Cl(t,e);const a=this.#Ea=[NaN,NaN,NaN,NaN,t,e];this.#do=[t,e];this.#yl=[{line:a,points:this.#do}];this.#so.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#ho=e)}#Cl(t,e){return Outline._normalizePoint(t,e,this.#wl,this.#xl,this.#In)}isEmpty(){return!this.#yl||0===this.#yl.length}isCancellable(){return this.#do.length<=10}add(t,e){[t,e]=this.#Cl(t,e);const[i,s,n,r]=this.#so.subarray(2,6),a=t-n,o=e-r;if(Math.hypot(this.#wl*a,this.#xl*o)<=2)return null;this.#do.push(t,e);if(isNaN(i)){this.#so.set([n,r,t,e],2);this.#Ea.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#so[0])&&this.#Ea.splice(6,6);this.#so.set([i,s,n,r,t,e],0);this.#Ea.push(...Outline.createBezierPoints(i,s,n,r,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#do.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#wl=i;this.#xl=s;this.#In=n;[t,e]=this.#Cl(t,e);const r=this.#Ea=[NaN,NaN,NaN,NaN,t,e];this.#do=[t,e];const a=this.#yl.at(-1);if(a){a.line=new Float32Array(a.line);a.points=new Float32Array(a.points)}this.#yl.push({line:r,points:this.#do});this.#so.set(r,0);this.#vl=0;this.toSVGPath();return null}getLastElement(){return this.#yl.at(-1)}setLastElement(t){if(!this.#yl)return this.#Fo.setLastElement(t);this.#yl.push(t);this.#Ea=t.line;this.#do=t.points;this.#vl=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#yl)return this.#Fo.removeLastElement();this.#yl.pop();this.#Al="";for(let t=0,e=this.#yl.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,s,1,o,l,n);return m}#Pl(t=this.#ho){const e=this.#to+t/2*this.#Tl;return this.#In%180==0?[e/this.#wl,e/this.#xl]:[e/this.#xl,e/this.#wl]}#_l(){const[t,e,i,s]=this.#wo,[n,r]=this.#Pl(0);return[t+n,e+r,i-2*n,s-2*r]}#Sl(){const t=this.#wo=i.slice();for(const{line:e}of this.#yl){if(e.length<=12){for(let i=4,s=e.length;it!==e[i])||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}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#Dl={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#Ml(t,e,i,s){s-=e;return 0===(i-=t)?s>0?0:4:1===i?s+6:2-s}static#kl=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#Il(t,e,i,s,n,r,a){const o=this.#Ml(i,s,n,r);for(let n=0;n<8;n++){const r=(-n+o-a+16)%8;if(0!==t[(i+this.#kl[2*r])*e+(s+this.#kl[2*r+1])])return r}return-1}static#Fl(t,e,i,s,n,r,a){const o=this.#Ml(i,s,n,r);for(let n=0;n<8;n++){const r=(n+o+a+16)%8;if(0!==t[(i+this.#kl[2*r])*e+(s+this.#kl[2*r+1])])return r}return-1}static#Bl(t,e,i,s){const n=t.length,r=new Int32Array(n);for(let e=0;e=1&&0===r[s+1])){1!==n&&(a=Math.abs(n));continue}o+=1;d+=1;n>1&&(a=n)}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.#Il(r,e,t,i,h,d,0);if(-1===m){r[s]=-o;1!==r[s]&&(a=Math.abs(r[s]));continue}let f=this.#kl[2*m],b=this.#kl[2*m+1];const y=t+f,A=i+b;h=y;d=A;let v=t,w=i;for(;;){const n=this.#Fl(r,e,v,w,h,d,1);f=this.#kl[2*n];b=this.#kl[2*n+1];const l=v+f,u=w+b;c.push(u,l);const p=v*e+w;0===r[p+1]?r[p]=-o:1===r[p]&&(r[p]=o);if(l===t&&u===i&&v===y&&w===A){1!==r[s]&&(a=Math.abs(r[s]));break}h=v;d=w;v=l;w=u}}}return l}static#Rl(t,e,i,s){if(i-e<=4){for(let n=e;nv){w=s;v=e}}if(v>(l*A)**2){this.#Rl(t,e,w+2,s);this.#Rl(t,w,i,s)}else s.push(n,r)}static#Ol(t){const e=[],i=t.length;this.#Rl(t,0,i,e);e.push(t[i-2],t[i-1]);return e.length<=4?null:e}static#Ll(t,e,i,s,n,r){const a=new Float32Array(r**2),o=-2*s**2,l=r>>1;for(let t=0;t=i))for(let i=0;i=e)continue;const p=t[u*e+s],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#Nl(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#Ul(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let s=-1/0,n=1/0;for(let e=0,r=i.length;e0!==t);let r=n,a=n;for(e=n;e<256;e++){const n=t[e];if(n>i){if(e-r>s){s=e-r;a=e-1}i=n;r=e}}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#zl(t){const e=t,{width:i,height:s}=t,{maxDim:n}=this.#Dl;let r=i,a=s;if(i>n||s>n){let o=i,l=s,h=Math.log2(Math.max(i,s)/n);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++]=s;c[u++]=n;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,s=e.length;i{await n.ready;await n.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:s,height:n}=this.#Vl,r=Math.max(s,n);return{areContours:e,outline:SignatureExtractor.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:s,height:n},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,s){const{x:n,y:r}=this,{outline:a}=this.#Vl=t;this.#Gl=a instanceof ContourDrawOutline;this.description=i;let o;if(this.#Gl)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=n;this.y=r;this.center();this._onResized();this.onScaleChanging();this.rotate();this._uiManager.addToAnnotationStorage(this);this.setUuid(s);this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!s,hasDescription:!!i}});this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:s}=this.parent.viewport;return SignatureExtractor.process(t,e,i,s,SignatureEditor._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:s},rotation:n}=this.parent.viewport;return SignatureExtractor.extractContoursFromText(t,e,i,s,n,SignatureEditor._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:s}=this.parent.viewport;return SignatureExtractor.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:s,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":s}}=this,n=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#Gl,color:[0,0,0],thickness:this.#Gl?0:s});this.addComment(n);if(t){n.paths={lines:e,points:i};n.uuid=this.#jl;n.isCopy=!0}else n.lines=e;this.#Wl&&(n.accessibilityData={type:"Figure",alt:this.#Wl});return n}static deserializeDraw(t,e,i,s,n,r){return r.areContours?ContourDrawOutline.deserialize(t,e,i,s,n,r):InkDrawOutline.deserialize(t,e,i,s,n,r)}static async deserialize(t,e,i){const s=await super.deserialize(t,e,i);s.#Gl=t.areContours;s.description=t.accessibilityData?.alt||"";s.#jl=t.uuid;return s}}class StampEditor extends AnnotationEditor{#$l=null;#Xl=null;#ql=null;#Kl=null;#Yl=null;#Ql="";#Jl=null;#Zl=!1;#th=null;#eh=!1;#ih=!1;static _type="stamp";static _editorType=m.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Kl=t.bitmapUrl;this.#Yl=t.bitmapFile;this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e)}static isHandlingMimeForPasting(t){return j.includes(t)}static paste(t,e){e.pasteEditor({mode:m.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}}#sh(t,e=!1){if(t){this.#$l=t.bitmap;if(!e){this.#Xl=t.id;this.#eh=t.isSvg}t.file&&(this.#Ql=t.file.name);this.#nh()}else this.remove()}#rh(){this.#ql=null;this._uiManager.enableWaiting(!1);if(this.#Jl)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#$l)this.addEditToolbar().then(()=>{this._editToolbar.hide();this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#$l){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:s,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await i.guess({name:"altText",request:{data:s,width:n,height:r,channels:s.length/(n*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}#ah(){if(this.#Xl){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#Xl).then(t=>this.#sh(t,!0)).finally(()=>this.#rh());return}if(this.#Kl){const t=this.#Kl;this.#Kl=null;this._uiManager.enableWaiting(!0);this.#ql=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#sh(t)).finally(()=>this.#rh());return}if(this.#Yl){const t=this.#Yl;this.#Yl=null;this._uiManager.enableWaiting(!0);this.#ql=this._uiManager.imageManager.getFromFile(t).then(t=>this.#sh(t)).finally(()=>this.#rh());return}const t=document.createElement("input");t.type="file";t.accept=j.join(",");const e=this._uiManager._signal;this.#ql=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.#sh(e)}else this.remove();i()},{signal:e});t.addEventListener("cancel",()=>{this.remove();i()},{signal:e})}).finally(()=>this.#rh());t.click()}remove(){if(this.#Xl){this.#$l=null;this._uiManager.imageManager.deleteId(this.#Xl);this.#Jl?.remove();this.#Jl=null;if(this.#th){clearTimeout(this.#th);this.#th=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Xl&&null===this.#Jl&&this.#ah();this.isAttachedToDOM||this.parent.add(this)}}else this.#Xl&&this.#ah()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#ql||this.#$l||this.#Kl||this.#Yl||this.#Xl||this.#Zl)}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.#Zl||(this.#$l?this.#nh():this.#ah());this._isCopy&&this._moveAfterPaste(t,e);this._uiManager.addShouldRescale(this);return this.div}setCanvas(t,e){const{id:i,bitmap:s}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove();if(i&&this._uiManager.imageManager.isValidId(i)){this.#Xl=i;s&&(this.#$l=s);this.#Zl=!1;this.#nh()}}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#th&&clearTimeout(this.#th);this.#th=setTimeout(()=>{this.#th=null;this.#oh()},200)}#nh(){const{div:t}=this;let{width:e,height:i}=this.#$l;const[s,n]=this.pageDimensions,r=.75;if(this.width){e=this.width*s;i=this.height*n}else if(e>r*s||i>r*n){const t=Math.min(r*s/e,r*n/i);e*=t;i*=t}this._uiManager.enableWaiting(!1);const a=this.#Jl=document.createElement("canvas");a.setAttribute("role","img");this.addContainer(a);this.width=e/s;this.height=i/n;this.setDims();this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#oh();if(!this.#ih){this.parent.addUndoableEditor(this);this.#ih=!0}this._reportTelemetry({action:"inserted_image"});this.#Ql&&this.div.setAttribute("aria-description",this.#Ql);this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#$l,r=new OutputScale;let a=this.#$l,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t);l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*r.sx),i=h.height=Math.ceil(l*r.sy);this.#eh||(a=this.#lh(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||n>t){const r=Math.min(t/s,t/n);e=Math.floor(s*r);i=Math.floor(n*r);this.#eh||(a=this.#lh(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}}#lh(t,e){const{width:i,height:s}=this.#$l;let n=i,r=s,a=this.#$l;for(;n>2*t||r>2*e;){const i=n,s=r;n>2*t&&(n=Math.ceil(n/2));r>2*e&&(r=Math.ceil(r/2));const o=new OffscreenCanvas(n,r);o.getContext("2d").drawImage(a,0,0,i,s,0,0,n,r);a=o.transferToImageBitmap()}return a}#oh(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new OutputScale,r=Math.ceil(i*t*n.sx),a=Math.ceil(s*e*n.sy),o=this.#Jl;if(!o||o.width===r&&o.height===a)return;o.width=r;o.height=a;const l=this.#eh?this.#$l:this.#lh(r,a),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,r,a)}#hh(t){if(t){if(this.#eh){const t=this._uiManager.imageManager.getSvgUrl(this.#Xl);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#$l);t.getContext("2d").drawImage(this.#$l,0,0);return t.toDataURL()}if(this.#eh){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#$l,0,0,this.#$l.width,this.#$l.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#$l)}static async deserialize(t,e,i){let s=null,n=!1;if(t instanceof StampAnnotationElement){const{data:{rect:r,rotation:a,id:o,structParent:l,popupRef:h,richText:d,contentsObj:c,creationDate:u,modificationDate:p},container:g,parent:{page:{pageNumber:f}},canvas:b}=t;let y,A;if(b){delete t.canvas;({id:y,bitmap:A}=i.imageManager.getFromCanvas(g.id,b));b.remove()}else{n=!0;t._hasNoCanvas=!0}const v=(await e._structTree.getAriaAttributes(`${W}${o}`))?.get("aria-label")||"";s=t={annotationType:m.STAMP,bitmapId:y,bitmap:A,pageIndex:f-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:v},isSvg:!1,structParent:l,popupRef:h,richText:d,comment:c?.str||null,creationDate:u,modificationDate:p}}const r=await super.deserialize(t,e,i),{rect:a,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:d,accessibilityData:c}=t;if(n){i.addMissingCanvas(t.id,r);r.#Zl=!0}else if(h&&i.imageManager.isValidId(h)){r.#Xl=h;o&&(r.#$l=o)}else r.#Kl=l;r.#eh=d;const[u,p]=r.pageDimensions;r.width=(a[2]-a[0])/u;r.height=(a[3]-a[1])/p;c&&(r.altTextData=c);r._initialData=s;t.comment&&r.setCommentData(t);r.#ih=!!s;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.#Xl,isSvg:this.#eh});this.addComment(i);if(t){i.bitmapUrl=this.#hh(!0);i.accessibilityData=this.serializeAltText(!0);i.isCopy=!0;return i}const{decorative:s,altText:n}=this.serializeAltText(!1);!s&&n&&(i.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#Qa(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.#eh?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#Xl)){if(this.#eh){const t=e.stamps.get(this.#Xl);if(r>t.area){t.area=r;t.serialized.bitmap.close();t.serialized.bitmap=this.#hh(!1)}}}else{e.stamps.set(this.#Xl,{area:r,serialized:i});i.bitmap=this.#hh(!1)}return i}#Qa(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){if(this.deleted){t.hide();return null}t.updateEdited({rect:this.getPDFRect(),popup:this.comment});return null}}class AnnotationEditorLayer{#Fa;#dh=!1;#ch=null;#uh=null;#ph=null;#gh=new Map;#mh=!1;#fh=!1;#bh=!1;#yh=null;#Ah=null;#vh=null;#wh=null;#xh=null;#Ch=-1;#y;static _initialized=!1;static#Q=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor,SignatureEditor].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:r,drawLayer:a,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#Q.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#y=t;this.pageIndex=e;this.div=i;this.#Fa=n;this.#ch=r;this.viewport=l;this.#vh=o;this.drawLayer=a;this._structTree=s;this.#y.addLayer(this)}get isEmpty(){return 0===this.#gh.size}get isInvisible(){return this.isEmpty&&this.#y.getMode()===m.NONE}updateToolbar(t){this.#y.updateToolbar(t)}updateMode(t=this.#y.getMode()){this.#Eh();switch(t){case m.NONE:this.div.classList.toggle("nonEditing",!0);this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case m.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case m.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===m.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const i of AnnotationEditorLayer.#Q.values())e.toggle(`${i._type}Editing`,t===i._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#vh?.div}setEditingState(t){this.#y.setEditingState(t)}addCommands(t){this.#y.addCommands(t)}cleanUndoStack(t){this.#y.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#ch?.togglePointerEvents(t)}get#Th(){return 0!==this.#gh.size?this.#gh.values():this.#y.getEditors(this.pageIndex)}async enable(){this.#bh=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);this.div.classList.toggle("nonEditing",!1);this.#xh?.abort();this.#xh=null;const t=new Set;for(const e of this.#Th){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#y.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}const e=this.#ch;if(e)for(const i of e.getEditableAnnotations()){i.hide();if(this.#y.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.#bh=!1;this.#y._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){this.#fh=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);this.div.classList.toggle("nonEditing",!0);if(this.#vh&&!this.#xh){this.#xh=new AbortController;const t=this.#y.combinedSignal(this.#xh);this.#vh.div.addEventListener("pointerdown",t=>{const{clientX:e,clientY:i,timeStamp:s}=t;if(s-this.#Ch>500){this.#Ch=s;return}this.#Ch=-1;const{classList:n}=this.div;n.toggle("getElements",!0);const r=document.elementsFromPoint(e,i);n.toggle("getElements",!1);if(!this.div.contains(r[0]))return;let a;const o=new RegExp(`^${g}[0-9]+$`);for(const t of r)if(o.test(t.id)){a=t.id;break}if(!a)return;const l=this.#gh.get(a);if(null===l?.annotationElementId){stopEvent(t);l.dblclick(t)}},{signal:t,capture:!0})}const t=this.#ch,e=[];if(t){const i=new Map,s=new Map;for(const t of this.#Th){t.disableEditing();if(t.annotationElementId)if(null===t.serialize()){s.set(t.annotationElementId,t);this.getEditableAnnotation(t.annotationElementId)?.show();t.remove()}else i.set(t.annotationElementId,t);else e.push(t)}for(const e of t.getEditableAnnotations()){const{id:t}=e.data;if(this.#y.isDeletedAnnotationElement(t)){e.updateEdited({deleted:!0});continue}let n=s.get(t);if(n){n.resetAnnotationElement(e);n.show(!1);e.show()}else{n=i.get(t);if(n){this.#y.addChangedExistingAnnotation(n);n.renderAnnotationElement(e)&&n.show(!1)}e.show()}}}this.#Eh();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#Q.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);t?.updateFakeAnnotations(e);this.#fh=!1}getEditableAnnotation(t){return this.#ch?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#y.getActive()!==t&&this.#y.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#vh?.div&&!this.#wh){this.#wh=new AbortController;const t=this.#y.combinedSignal(this.#wh);this.#vh.div.addEventListener("pointerdown",this.#Sh.bind(this),{signal:t});this.#vh.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#vh?.div&&this.#wh){this.#wh.abort();this.#wh=null;this.#vh.div.classList.remove("highlighting")}}#Sh(t){this.#y.unselectAll();const{target:e}=t;if(e===this.#vh.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent")||e.classList.contains("textLayerImagePlaceholder"))&&this.#vh.div.contains(e)){const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#y.showAllEditors("highlight",!0,!0);this.#vh.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#y.direction,{target:this.#vh.div,x:t.x,y:t.y});this.#vh.div.addEventListener("pointerup",()=>{this.#vh.div.classList.remove("free");this.toggleDrawing(!0)},{once:!0,signal:this.#y._signal});t.preventDefault()}}enableClick(){if(this.#uh)return;this.#uh=new AbortController;const t=this.#y.combinedSignal(this.#uh);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.#uh?.abort();this.#uh=null}attach(t){this.#gh.set(t.id,t);const{annotationElementId:e}=t;e&&this.#y.isDeletedAnnotationElement(e)&&this.#y.removeDeletedAnnotationElement(t)}detach(t){this.#gh.delete(t.id);this.#Fa?.removePointerInTextLayer(t.contentDiv);!this.#fh&&t.annotationElementId&&this.#y.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#y.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#y.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.#y.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#bh);this.#y.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#ph){t._focusEventsAllowed=!1;this.#ph=setTimeout(()=>{this.#ph=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#y._signal});e.focus()}},0)}t._structTreeParentId=this.#Fa?.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.#gh.values())if(e.uid===t)return e;return null}get#_h(){return AnnotationEditorLayer.#Q.get(this.#y.getMode())}combinedSignal(t){return this.#y.combinedSignal(t)}#Ph(t){const e=this.#_h;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#_h?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t);await this.#y.updateMode(t.mode);const{offsetX:i,offsetY:s}=this.#Dh(),n=this.#y.getId(),r=this.#Ph({parent:this,id:n,x:i,y:s,uiManager:this.#y,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await(AnnotationEditorLayer.#Q.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#y))||null}createAndAddNewEditor(t,e,i={}){const s=this.#y.getId(),n=this.#Ph({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#y,isCentered:e,...i});n&&this.add(n);return n}get boundingClientRect(){return this.div.getBoundingClientRect()}#Dh(){const{x:t,y:e,width:i,height:s}=this.boundingClientRect,n=Math.max(0,t),r=Math.max(0,e),a=(n+Math.min(window.innerWidth,t+i))/2-t,o=(r+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[a,o]:[o,a];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#Dh(),!0,t)}setSelected(t){this.#y.setSelected(t)}toggleSelected(t){this.#y.toggleSelected(t)}unselect(t){this.#y.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.#mh)return;this.#mh=!1;if(this.#_h?.isDrawer&&this.#_h.supportMultipleDrawings)return;if(!this.#dh){this.#dh=!0;return}const i=this.#y.getMode();i!==m.STAMP&&i!==m.POPUP&&i!==m.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#y.unselectAll()}pointerdown(t){this.#y.getMode()===m.HIGHLIGHT&&this.enableTextSelection();if(this.#mh){this.#mh=!1;return}const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#mh=!0;if(this.#_h?.isDrawer){this.startDrawingSession(t);return}const i=this.#y.getActive();this.#dh=!i||i.isEmpty()}startDrawingSession(t){this.div.focus({preventScroll:!0});if(this.#yh){this.#_h.startDrawing(this,this.#y,!1,t);return}this.#y.setCurrentDrawingSession(this);this.#yh=new AbortController;const e=this.#y.combinedSignal(this.#yh);this.div.addEventListener("blur",({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#Ah=null;this.commitOrRemove()}},{signal:e});this.#_h.startDrawing(this,this.#y,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#Ah=t);return}this.#Ah&&setTimeout(()=>{this.#Ah?.focus();this.#Ah=null},0)}endDrawingSession(t=!1){if(!this.#yh)return null;this.#y.setCurrentDrawingSession(null);this.#yh.abort();this.#yh=null;this.#Ah=null;return this.#_h.endDrawing(t)}findNewParent(t,e,i){const s=this.#y.findParent(e,i);if(null===s||s===this)return!1;s.changeParent(t);return!0}commitOrRemove(){if(this.#yh){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#yh&&this.#_h.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#y.getActive()?.parent===this){this.#y.commitOrRemove();this.#y.setActiveEditor(null)}if(this.#ph){clearTimeout(this.#ph);this.#ph=null}for(const t of this.#gh.values()){this.#Fa?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#gh.clear();this.#y.removeLayer(this)}#Eh(){for(const t of this.#gh.values())t.isEmpty()&&t.remove()}async render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#y.getEditors(this.pageIndex)){this.add(t);t.rebuild()}await this.#y.findClonesForPage(this);this.div.hidden=this.isEmpty;this.updateMode()}update({viewport:t}){this.#y.commitOrRemove();this.#Eh();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#gh.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#y.viewParameters.realScale}}class DrawLayer{#sa=null;#Mh=new Map;#kh=new Map;static#S=0;setParent(t){if(this.#sa){if(this.#sa!==t){if(this.#Mh.size>0)for(const e of this.#Mh.values()){e.remove();t.append(e)}this.#sa=t}}else this.#sa=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#Ih(t,[e,i,s,n]){const{style:r}=t;r.top=100*i+"%";r.left=100*e+"%";r.width=100*s+"%";r.height=100*n+"%"}#Fh(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#sa.append(t);t.setAttribute("aria-hidden",!0);return t}#Bh(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s);i.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");i.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return s}#Rh(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=DrawLayer.#S++,n=this.#Fh(),r=DrawLayer._svgFactory.createElement("defs");n.append(r);const a=DrawLayer._svgFactory.createElement("path");r.append(a);const o=`path_${s}`;a.setAttribute("id",o);a.setAttribute("vector-effect","non-scaling-stroke");e&&this.#kh.set(s,a);const l=i?this.#Bh(r,o):null,h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#Mh.set(s,n);return{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=DrawLayer.#S++,s=this.#Fh(),n=DrawLayer._svgFactory.createElement("defs");s.append(n);const r=DrawLayer._svgFactory.createElement("path");n.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");n.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 s=DrawLayer._svgFactory.createElement("use");t.append(s);s.setAttribute("href",`#${a}`);s.setAttribute("stroke","none");s.setAttribute("fill","black");s.setAttribute("fill-rule","nonzero");s.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");s.append(l);l.setAttribute("href",`#${a}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();s.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(s,t);this.#Mh.set(i,s);return i}finalizeDraw(t,e){this.#kh.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:r}=e,a="number"==typeof t?this.#Mh.get(t):t;if(a){i&&this.#Rh(a,i);s&&DrawLayer.#Ih(a,s);if(n){const{classList:t}=a;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(r){const t=a.firstElementChild.firstElementChild;this.#Rh(t,r)}}}updateParent(t,e){if(e===this)return;const i=this.#Mh.get(t);if(i){e.#sa.append(i);this.#Mh.delete(t);e.#Mh.set(t,i)}}remove(t){this.#kh.delete(t);if(null!==this.#sa){this.#Mh.get(t).remove();this.#Mh.delete(t)}}destroy(){this.#sa=null;for(const t of this.#Mh.values())t.remove();this.#Mh.clear();this.#kh.clear()}}function percentage(t){return`${(100*t).toFixed(2)}%`}class TextLayerImages{#Oh=[];#Lh=new Map;#Nh=null;#Uh=0;#Dn=0;#Pn=0;static#Hh=null;constructor(t,e,i,s){this.#Uh=t;this.#Oh=e;this.#Dn=i.rawDims.pageWidth;this.#Pn=i.rawDims.pageHeight;this.#Nh=s}render(){const t=document.createElement("div");t.className="textLayerImages";for(let e=0;e{if(!(t.target instanceof HTMLCanvasElement))return;const e=t.target,i=this.#Lh.get(e);if(!i)return;const s=TextLayerImages.#Hh?.deref();if(s===e)return;if(s){s.width=0;s.height=0}TextLayerImages.#Hh=new WeakRef(e);const{inverseTransform:n,x1:r,y1:a,width:o,height:l}=i,h=this.#Nh(),d=Math.ceil(r*h.width),c=Math.ceil(a*h.height),u=Math.floor((r+o/this.#Dn)*h.width),p=Math.floor((a+l/this.#Pn)*h.height);e.width=u-d;e.height=p-c;const g=e.getContext("2d");g.setTransform(...n);g.translate(-d,-c);g.drawImage(h,0,0)});return t}#zh([t,e,i,s,n,r]){const a=Math.hypot((n-t)*this.#Dn,(r-e)*this.#Pn),o=Math.hypot((i-t)*this.#Dn,(s-e)*this.#Pn);if(a