4NK_IA_front/public/assets/pdf-CusTIDZW.js
2025-09-18 15:31:16 +00:00

13 lines
314 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var cs=c=>{throw TypeError(c)};var Me=(c,t,e)=>t.has(c)||cs("Cannot "+e);var mt=(c,t,e)=>(Me(c,t,"read from private field"),e?e.call(c):t.get(c)),zt=(c,t,e)=>t.has(c)?cs("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(c):t.set(c,e),Kt=(c,t,e,s)=>(Me(c,t,"write to private field"),s?s.call(c,e):t.set(c,e),e),he=(c,t,e)=>(Me(c,t,"access private method"),e);var ds=(c,t,e,s)=>({set _(i){Kt(c,t,i,e)},get _(){return mt(c,t,s)}});import{a6 as ce}from"./index-ChSrE95j.js";var se={};se.d=(c,t)=>{for(var e in t)se.o(t,e)&&!se.o(c,e)&&Object.defineProperty(c,e,{enumerable:!0,get:t[e]})};se.o=(c,t)=>Object.prototype.hasOwnProperty.call(c,t);var M=globalThis.pdfjsLib={};se.d(M,{AbortException:()=>Nt,AnnotationEditorLayer:()=>St,AnnotationEditorParamsType:()=>R,AnnotationEditorType:()=>I,AnnotationEditorUIManager:()=>kt,AnnotationLayer:()=>ra,AnnotationMode:()=>Tt,ColorPicker:()=>pt,DOMSVGFactory:()=>os,DrawLayer:()=>st,FeatureTest:()=>rt,GlobalWorkerOptions:()=>ne,ImageKind:()=>me,InvalidPDFException:()=>Ls,MissingPDFException:()=>Ot,OPS:()=>bt,OutputScale:()=>ze,PDFDataRangeTransport:()=>Ks,PDFDateString:()=>Fs,PDFWorker:()=>$t,PasswordResponses:()=>di,PermissionFlag:()=>ci,PixelsPerInch:()=>qt,RenderingCancelledException:()=>Ye,TextLayer:()=>nt,UnexpectedResponseException:()=>Se,Util:()=>S,VerbosityLevel:()=>ve,XfaLayer:()=>Js,build:()=>zn,createValidAbsoluteUrl:()=>gi,fetchData:()=>Ce,getDocument:()=>Pn,getFilenameFromUrl:()=>Si,getPdfFilenameFromUrl:()=>xi,getXfaPageViewport:()=>Ci,isDataScheme:()=>Te,isPdfFile:()=>Ke,noContextMenu:()=>gt,normalizeUnicode:()=>vi,setLayerDimensions:()=>Ft,shadow:()=>D,version:()=>Bn});const it=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Ps=[1,0,0,1,0,0],Ne=[.001,0,0,.001,0,0],li=1e7,Pe=1.35,dt={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Tt={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},hi="pdfjs_internal_editor_",I={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},R={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},ci={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},et={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},me={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},K={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,WIDGET:20},Qt={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},ve={ERRORS:0,WARNINGS:1,INFOS:5},bt={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},di={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let we=ve.WARNINGS;function ui(c){Number.isInteger(c)&&(we=c)}function fi(){return we}function Ee(c){we>=ve.INFOS&&console.log(`Info: ${c}`)}function F(c){we>=ve.WARNINGS&&console.log(`Warning: ${c}`)}function H(c){throw new Error(c)}function J(c,t){c||H(t)}function pi(c){switch(c?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function gi(c,t=null,e=null){if(!c)return null;try{if(e&&typeof c=="string"&&(e.addDefaultProtocol&&c.startsWith("www.")&&c.match(/\./g)?.length>=2&&(c=`http://${c}`),e.tryConvertEncoding))try{c=yi(c)}catch{}const s=t?new URL(c,t):new URL(c);if(pi(s))return s}catch{}return null}function D(c,t,e,s=!1){return Object.defineProperty(c,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const Mt=(function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t})();class He extends Mt{constructor(t,e){super(t,"PasswordException"),this.code=e}}class Be extends Mt{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class Ls extends Mt{constructor(t){super(t,"InvalidPDFException")}}class Ot extends Mt{constructor(t){super(t,"MissingPDFException")}}class Se extends Mt{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class mi extends Mt{constructor(t){super(t,"FormatError")}}class Nt extends Mt{constructor(t){super(t,"AbortException")}}function Is(c){(typeof c!="object"||c?.length===void 0)&&H("Invalid argument for bytesToString");const t=c.length,e=8192;if(t<e)return String.fromCharCode.apply(null,c);const s=[];for(let i=0;i<t;i+=e){const n=Math.min(i+e,t),a=c.subarray(i,n);s.push(String.fromCharCode.apply(null,a))}return s.join("")}function xe(c){typeof c!="string"&&H("Invalid argument for stringToBytes");const t=c.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=c.charCodeAt(s)&255;return e}function bi(c){return String.fromCharCode(c>>24&255,c>>16&255,c>>8&255,c&255)}function qe(c){const t=Object.create(null);for(const[e,s]of c)t[e]=s;return t}function Ai(){const c=new Uint8Array(4);return c[0]=1,new Uint32Array(c.buffer,0,1)[0]===1}function _i(){try{return new Function(""),!0}catch{return!1}}class rt{static get isLittleEndian(){return D(this,"isLittleEndian",Ai())}static get isEvalSupported(){return D(this,"isEvalSupported",_i())}static get isOffscreenCanvasSupported(){return D(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?D(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof navigator?.userAgent=="string"&&navigator.userAgent.includes("Firefox")}):D(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return D(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const Le=Array.from(Array(256).keys(),c=>c.toString(16).padStart(2,"0"));class S{static makeHexColor(t,e,s){return`#${Le[t]}${Le[e]}${Le[s]}`}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),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 applyTransform(t,e){const s=t[0]*e[0]+t[1]*e[2]+e[4],i=t[0]*e[1]+t[1]*e[3]+e[5];return[s,i]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2],i=(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,n=(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s;return[i,n]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e),i=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],a[0]),Math.min(s[1],i[1],n[1],a[1]),Math.max(s[0],i[0],n[0],a[0]),Math.max(s[1],i[1],n[1],a[1])]}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){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],i=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(s+a)/2,o=Math.sqrt((s+a)**2-4*(s*a-n*i))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[s,n,i,a]}static#t(t,e,s,i,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,u=l*l,f=u*l,p=d*(d*(d*t+3*l*e)+3*u*s)+f*i,g=d*(d*(d*n+3*l*a)+3*u*r)+f*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,s,i,n,a,r,o,l,h,d,u){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,s,i,n,a,r,o,-d/h,u);return}const f=h**2-4*d*l;if(f<0)return;const p=Math.sqrt(f),g=2*l;this.#t(t,e,s,i,n,a,r,o,(-h+p)/g,u),this.#t(t,e,s,i,n,a,r,o,(-h-p)/g,u)}static bezierBoundingBox(t,e,s,i,n,a,r,o,l){return l?(l[0]=Math.min(l[0],t,r),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,r),l[3]=Math.max(l[3],e,o)):l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)],this.#e(t,s,n,r,e,i,a,o,3*(-t+3*(s-n)+r),6*(t-2*s+n),3*(s-t),l),this.#e(t,s,n,r,e,i,a,o,3*(-e+3*(i-a)+o),6*(e-2*i+a),3*(i-e),l),l}}function yi(c){return decodeURIComponent(escape(c))}let Ie=null,us=null;function vi(c){return Ie||(Ie=/([\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,us=new Map([["ſt","ſt"]])),c.replaceAll(Ie,(t,e,s)=>e?e.normalize("NFKC"):us.get(s))}function wi(){if(typeof crypto<"u"&&typeof crypto?.randomUUID=="function")return crypto.randomUUID();const c=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto?.getRandomValues=="function")crypto.getRandomValues(c);else for(let t=0;t<32;t++)c[t]=Math.floor(Math.random()*255);return Is(c)}const Xe="pdfjs_internal_id_",vt={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8};function Ei(c){return Uint8Array.prototype.toBase64?c.toBase64():btoa(Is(c))}const Et="http://www.w3.org/2000/svg";class qt{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Ce(c,t="text"){if(te(c,document.baseURI)){const e=await fetch(c);if(!e.ok)throw new Error(e.statusText);switch(t){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json()}return e.text()}return new Promise((e,s)=>{const i=new XMLHttpRequest;i.open("GET",c,!0),i.responseType=t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case"arraybuffer":case"blob":case"json":e(i.response);return}e(i.responseText);return}s(new Error(i.statusText))}},i.send(null)})}class re{constructor({viewBox:t,scale:e,rotation:s,offsetX:i=0,offsetY:n=0,dontFlip:a=!1}){this.viewBox=t,this.scale=e,this.rotation=s,this.offsetX=i,this.offsetY=n;const r=(t[2]+t[0])/2,o=(t[3]+t[1])/2;let l,h,d,u;switch(s%=360,s<0&&(s+=360),s){case 180:l=-1,h=0,d=0,u=1;break;case 90:l=0,h=1,d=1,u=0;break;case 270:l=0,h=-1,d=-1,u=0;break;case 0:l=1,h=0,d=0,u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,u=-u);let f,p,g,b;l===0?(f=Math.abs(o-t[1])*e+i,p=Math.abs(r-t[0])*e+n,g=(t[3]-t[1])*e,b=(t[2]-t[0])*e):(f=Math.abs(r-t[0])*e+i,p=Math.abs(o-t[1])*e+n,g=(t[2]-t[0])*e,b=(t[3]-t[1])*e),this.transform=[l*e,h*e,d*e,u*e,f-l*e*r-d*e*o,p-h*e*r-u*e*o],this.width=g,this.height=b}get rawDims(){const{viewBox:t}=this;return D(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:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new re({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return S.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=S.applyTransform([t[0],t[1]],this.transform),s=S.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return S.applyInverseTransform([t,e],this.transform)}}class Ye extends Mt{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Te(c){const t=c.length;let e=0;for(;e<t&&c[e].trim()==="";)e++;return c.substring(e,e+5).toLowerCase()==="data:"}function Ke(c){return typeof c=="string"&&/\.pdf$/i.test(c)}function Si(c){return[c]=c.split(/[#?]/,1),c.substring(c.lastIndexOf("/")+1)}function xi(c,t="document.pdf"){if(typeof c!="string")return t;if(Te(c))return F('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(c);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||t}class fs{started=Object.create(null);times=[];time(t){t in this.started&&F(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||F(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:s}of this.times)e=Math.max(s.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms
`);return t.join("")}}function te(c,t){try{const{protocol:e}=t?new URL(c,t):new URL(c);return e==="http:"||e==="https:"}catch{return!1}}function gt(c){c.preventDefault()}function ps(c){console.log("Deprecated API usage: "+c)}class Fs{static#t;static toDateObject(t){if(!t||typeof t!="string")return null;this.#t||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#t.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r: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;return d=d>=0&&d<=59?d:0,l==="-"?(a+=h,r+=d):l==="+"&&(a-=h,r-=d),new Date(Date.UTC(s,i,n,a,r,o))}}function Ci(c,{scale:t=1,rotation:e=0}){const{width:s,height:i}=c.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new re({viewBox:n,scale:t,rotation:e})}function Qe(c){if(c.startsWith("#")){const t=parseInt(c.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return c.startsWith("rgb(")?c.slice(4,-1).split(",").map(t=>parseInt(t)):c.startsWith("rgba(")?c.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(F(`Not a valid color format: "${c}"`),[0,0,0])}function Ti(c){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const e of c.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;c.set(e,Qe(s))}t.remove()}function $(c){const{a:t,b:e,c:s,d:i,e:n,f:a}=c.getTransform();return[t,e,s,i,n,a]}function wt(c){const{a:t,b:e,c:s,d:i,e:n,f:a}=c.getTransform().invertSelf();return[t,e,s,i,n,a]}function Ft(c,t,e=!1,s=!0){if(t instanceof re){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:a}=c,r=rt.isCSSRoundSupported,o=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;!e||t.rotation%180===0?(a.width=h,a.height=d):(a.width=d,a.height=h)}s&&c.setAttribute("data-main-rotation",t.rotation)}class ze{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}class ie{#t=null;#e=null;#s;#n=null;#a=null;static#i=null;constructor(t){this.#s=t,ie.#i||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#t=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#s._uiManager._signal;t.addEventListener("contextmenu",gt,{signal:e}),t.addEventListener("pointerdown",ie.#l,{signal:e});const s=this.#n=document.createElement("div");s.className="buttons",t.append(s);const i=this.#s.toolbarPosition;if(i){const{style:n}=t,a=this.#s._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*a}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#t}static#l(t){t.stopPropagation()}#h(t){this.#s._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()}#c(t){this.#s._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()}#o(t){const e=this.#s._uiManager._signal;t.addEventListener("focusin",this.#h.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",gt,{signal:e})}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#a?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#s,s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",ie.#i[t]),this.#o(s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),this.#n.append(s)}get#r(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#o(e),this.#n.prepend(e,this.#r),this.#a=t}addColorPicker(t){this.#e=t;const e=t.renderButton();this.#o(e),this.#n.prepend(e,this.#r)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class ki{#t=null;#e=null;#s;constructor(t){this.#s=t}#n(){const t=this.#e=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",gt,{signal:this.#s._signal});const e=this.#t=document.createElement("div");return e.className="buttons",t.append(e),this.#i(),t}#a(t,e){let s=0,i=0;for(const n of t){const a=n.y+n.height;if(a<s)continue;const r=n.x+(e?n.width:0);if(a>s){i=r,s=a;continue}e?r>i&&(i=r):r<i&&(i=r)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#a(e,s),{style:a}=this.#e||=this.#n();t.append(this.#e),a.insetInlineEnd=`${100*i}%`,a.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#i(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=this.#s._signal;t.addEventListener("contextmenu",gt,{signal:s}),t.addEventListener("click",()=>{this.#s.highlightSelection("floating_button")},{signal:s}),this.#t.append(t)}}function _e(c,t,e){for(const s of e)t.addEventListener(s,c[s].bind(c))}function Ri(c){return Math.round(Math.min(255,Math.max(1,255*c))).toString(16).padStart(2,"0")}class Mi{#t=0;get id(){return`${hi}${this.#t++}`}}class Je{#t=wi();#e=0;#s=null;static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;const n=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return D(this,"_isSVGFittingCanvas",n)}async#n(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let i;if(typeof e=="string"?(s.url=e,i=await Ce(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=Je._isSVGFittingCanvas,a=new FileReader,r=new Image,o=new Promise((l,h)=>{r.onload=()=>{s.bitmap=r,s.isSvg=!0,l()},a.onload=async()=>{const d=s.svgUrl=a.result;r.src=await n?`${d}#svgView(preserveAspectRatio(none))`:d},r.onerror=a.onerror=h});a.readAsDataURL(i),await o}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){console.error(i),s=null}return this.#s.set(t,s),s&&this.#s.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#n(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#n(t,t)}async getFromBlob(t,e){const s=await e;return this.#n(t,s)}async getFromId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s?.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${this.#t}_${this.#e++}`,refCounter:1,isSvg:!1},this.#s.set(t,s),this.#s.set(s.id,s),s}getSvgUrl(t){const e=this.#s.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const i=new OffscreenCanvas(s.width,s.height);i.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=i.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#t}_`)}}class Pi{#t=[];#e=!1;#s;#n=-1;constructor(t=128){this.#s=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(i&&t(),this.#e)return;const o={cmd:t,undo:e,post:s,type:n};if(this.#n===-1){this.#t.length>0&&(this.#t.length=0),this.#n=0,this.#t.push(o);return}if(a&&this.#t[this.#n].type===n){r&&(o.undo=this.#t[this.#n].undo),this.#t[this.#n]=o;return}const l=this.#n+1;l===this.#s?this.#t.splice(0,1):(this.#n=l,l<this.#t.length&&this.#t.splice(l)),this.#t.push(o)}undo(){if(this.#n===-1)return;this.#e=!0;const{undo:t,post:e}=this.#t[this.#n];t(),e?.(),this.#e=!1,this.#n-=1}redo(){if(this.#n<this.#t.length-1){this.#n+=1,this.#e=!0;const{cmd:t,post:e}=this.#t[this.#n];t(),e?.(),this.#e=!1}}hasSomethingToUndo(){return this.#n!==-1}hasSomethingToRedo(){return this.#n<this.#t.length-1}destroy(){this.#t=null}}class oe{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=rt.platform;for(const[s,i,n={}]of t)for(const a of s){const r=a.startsWith("mac+");e&&r?(this.callbacks.set(a.slice(4),{callback:i,options:n}),this.allKeys.add(a.split("+").at(-1))):!e&&!r&&(this.callbacks.set(a,{callback:i,options:n}),this.allKeys.add(a.split("+").at(-1)))}}#t(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#t(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:a=[],checker:r=null}}=s;r&&!r(t,e)||(i.bind(t,...a,e)(),n||(e.stopPropagation(),e.preventDefault()))}}class Ze{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Ti(t),D(this,"_colors",t)}convert(t){const e=Qe(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((n,a)=>n===e[a]))return Ze._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?S.makeHexColor(...e):t}}class kt{#t=new AbortController;#e=null;#s=new Map;#n=new Map;#a=null;#i=null;#l=null;#h=new Pi;#c=null;#o=0;#d=new Set;#r=null;#u=null;#p=new Set;#f=!1;#b=!1;#m=!1;#g=null;#A=null;#y=null;#C=null;#E=!1;#S=null;#D=new Mi;#T=!1;#v=!1;#x=null;#k=null;#R=null;#L=null;#w=I.NONE;#_=new Set;#I=null;#F=null;#O=null;#j={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#B=[0,0];#N=null;#H=null;#U=null;#M=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=kt.prototype,e=a=>a.#H.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&a.hasSomethingToControl(),s=(a,{target:r})=>{if(r instanceof HTMLInputElement){const{type:o}=r;return o!=="text"&&o!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return D(this,"_keyboardManager",new oe([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["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:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(a,{target:r})=>!(r instanceof HTMLButtonElement)&&a.#H.contains(r)&&!a.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(a,{target:r})=>!(r instanceof HTMLButtonElement)&&a.#H.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,a,r,o,l,h,d){const u=this._signal=this.#t.signal;this.#H=t,this.#U=e,this.#a=s,this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:u}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:u}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:u}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:u}),i._on("setpreference",this.onSetPreference.bind(this),{signal:u}),i._on("switchannotationeditorparams",f=>this.updateParams(f.type,f.value),{signal:u}),this.#tt(),this.#nt(),this.#q(),this.#i=n.annotationStorage,this.#g=n.filterFactory,this.#F=a,this.#C=r||null,this.#f=o,this.#b=l,this.#m=h,this.#L=d||null,this.viewParameters={realScale:qt.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#M?.resolve(),this.#M=null,this.#t?.abort(),this.#t=null,this._signal=null;for(const t of this.#n.values())t.destroy();this.#n.clear(),this.#s.clear(),this.#p.clear(),this.#e=null,this.#_.clear(),this.#h.destroy(),this.#a?.destroy(),this.#S?.hide(),this.#S=null,this.#A&&(clearTimeout(this.#A),this.#A=null),this.#N&&(clearTimeout(this.#N),this.#N=null)}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#L}get useNewAltTextFlow(){return this.#b}get useNewAltTextWhenAddingImage(){return this.#m}get hcmFilter(){return D(this,"hcmFilter",this.#F?this.#g.addHCMFilter(this.#F.foreground,this.#F.background):"none")}get direction(){return D(this,"direction",getComputedStyle(this.#H).direction)}get highlightColors(){return D(this,"highlightColors",this.#C?new Map(this.#C.split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return D(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){this.#R=t}editAltText(t,e=!1){this.#a?.editAltText(this,t,e)}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}){switch(t){case"enableNewAltTextWhenAddingImage":this.#m=e;break}}onPageChanging({pageNumber:t}){this.#o=t-1}focusMainContainer(){this.#H.focus()}findParent(t,e){for(const s of this.#n.values()){const{x:i,y:n,width:a,height:r}=s.div.getBoundingClientRect();if(t>=i&&t<=i+a&&e>=n&&e<=n+r)return s}return null}disableUserSelect(t=!1){this.#U.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#p.add(t)}removeShouldRescale(t){this.#p.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*qt.PDF_TO_CSS_UNITS;for(const e of this.#p)e.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#$({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#V(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#n.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:a}=e,r=e.toString(),l=this.#$(e).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;e.empty();const d=this.#V(l),u=this.#w===I.NONE,f=()=>{d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:a,text:r}),u&&this.showAllEditors("highlight",!0,!0)};if(u){this.switchToMode(I.HIGHLIGHT,f);return}f()}#J(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#$(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#S||=new ki(this),this.#S.show(s,i,this.direction==="ltr"))}addToAnnotationStorage(t){!t.isEmpty()&&this.#i&&!this.#i.has(t.id)&&this.#i.setValue(t.id,t)}#Z(){const t=document.getSelection();if(!t||t.isCollapsed){this.#I&&(this.#S?.hide(),this.#I=null,this.#P({hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===this.#I)return;const i=this.#$(t).closest(".textLayer");if(!i){this.#I&&(this.#S?.hide(),this.#I=null,this.#P({hasSelectedText:!1}));return}if(this.#S?.hide(),this.#I=e,this.#P({hasSelectedText:!0}),!(this.#w!==I.HIGHLIGHT&&this.#w!==I.NONE)&&(this.#w===I.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#E=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#w===I.HIGHLIGHT?this.#V(i):null;n?.toggleDrawing();const a=new AbortController,r=this.combinedSignal(a),o=l=>{l.type==="pointerup"&&l.button!==0||(a.abort(),n?.toggleDrawing(!0),l.type==="pointerup"&&this.#W("main_toolbar"))};window.addEventListener("pointerup",o,{signal:r}),window.addEventListener("blur",o,{signal:r})}}#W(t=""){this.#w===I.HIGHLIGHT?this.highlightSelection(t):this.#f&&this.#J()}#tt(){document.addEventListener("selectionchange",this.#Z.bind(this),{signal:this._signal})}#et(){if(this.#y)return;this.#y=new AbortController;const t=this.combinedSignal(this.#y);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#st(){this.#y?.abort(),this.#y=null}blur(){if(this.isShiftKeyDown=!1,this.#E&&(this.#E=!1,this.#W("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#_)if(e.div.contains(t)){this.#k=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#k)return;const[t,e]=this.#k;this.#k=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#q(){if(this.#x)return;this.#x=new AbortController;const t=this.combinedSignal(this.#x);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#it(){this.#x?.abort(),this.#x=null}#X(){if(this.#c)return;this.#c=new AbortController;const t=this.combinedSignal(this.#c);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})}#Y(){this.#c?.abort(),this.#c=null}#nt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#q(),this.#X()}removeEditListeners(){this.#it(),this.#Y()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#u)if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#u)if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){if(t.preventDefault(),this.#e?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#_){const i=s.serialize(!0);i&&e.push(i)}e.length!==0&&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 n of e.items)for(const a of this.#u)if(a.isHandlingMimeForPasting(n.type)){a.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){F(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const o of s){const l=await i.deserialize(o);if(!l)return;n.push(l)}const a=()=>{for(const o of n)this.#K(o);this.#Q(n)},r=()=>{for(const o of n)o.remove()};this.addCommands({cmd:a,undo:r,mustExec:!0})}catch(n){F(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#w!==I.NONE&&!this.isEditorHandlingKeyboard&&kt._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#E&&(this.#E=!1,this.#W("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}}#P(t){Object.entries(t).some(([s,i])=>this.#j[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#j,t)}),this.#w===I.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#z([[R.HIGHLIGHT_FREE,!0]]))}#z(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#et(),this.#X(),this.#P({isEditing:this.#w!==I.NONE,isEmpty:this.#G(),hasSomethingToUndo:this.#h.hasSomethingToUndo(),hasSomethingToRedo:this.#h.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#st(),this.#Y(),this.#P({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#u){this.#u=t;for(const e of this.#u)this.#z(e.defaultPropertiesToUpdate)}}getId(){return this.#D.id}get currentLayer(){return this.#n.get(this.#o)}getLayer(t){return this.#n.get(t)}get currentPageIndex(){return this.#o}addLayer(t){this.#n.set(t.pageIndex,t),this.#T?t.enable():t.disable()}removeLayer(t){this.#n.delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(this.#w!==t&&!(this.#M&&(await this.#M.promise,!this.#M))){if(this.#M=Promise.withResolvers(),this.#w=t,t===I.NONE){this.setEditingState(!1),this.#rt(),this.#M.resolve();return}this.setEditingState(!0),await this.#at(),this.unselectAll();for(const i of this.#n.values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),this.#M.resolve();return}for(const i of this.#s.values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();this.#M.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#w&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#u){switch(t){case R.CREATE:this.currentLayer.addNewEditor();return;case R.HIGHLIGHT_DEFAULT_COLOR:this.#R?.updateColor(e);break;case R.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#O||=new Map).set(t,e),this.showAllEditors("highlight",e);break}for(const s of this.#_)s.updateParams(t,e);for(const s of this.#u)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#s.values())n.editorType===t&&n.show(e);(this.#O?.get(R.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#z([[R.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#v!==t){this.#v=t;for(const e of this.#n.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#at(){if(!this.#T){this.#T=!0;const t=[];for(const e of this.#n.values())t.push(e.enable());await Promise.all(t);for(const e of this.#s.values())e.enable()}}#rt(){if(this.unselectAll(),this.#T){this.#T=!1;for(const t of this.#n.values())t.disable();for(const t of this.#s.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#s.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#s.get(t)}addEditor(t){this.#s.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#A&&clearTimeout(this.#A),this.#A=setTimeout(()=>{this.focusMainContainer(),this.#A=null},0)),this.#s.delete(t.id),this.unselect(t),(!t.annotationElementId||!this.#d.has(t.annotationElementId))&&this.#i?.remove(t.id)}addDeletedAnnotationElement(t){this.#d.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#d.has(t)}removeDeletedAnnotationElement(t){this.#d.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#K(t){const e=this.#n.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#z(t.propertiesToUpdate))}get#ot(){let t=null;for(t of this.#_);return t}updateUI(t){this.#ot===t&&this.#z(t.propertiesToUpdate)}toggleSelected(t){if(this.#_.has(t)){this.#_.delete(t),t.unselect(),this.#P({hasSelectedEditor:this.hasSelection});return}this.#_.add(t),t.select(),this.#z(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}setSelected(t){for(const e of this.#_)e!==t&&e.unselect();this.#_.clear(),this.#_.add(t),t.select(),this.#z(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}isSelected(t){return this.#_.has(t)}get firstSelectedEditor(){return this.#_.values().next().value}unselect(t){t.unselect(),this.#_.delete(t),this.#P({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#_.size!==0}get isEnterHandled(){return this.#_.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#h.undo(),this.#P({hasSomethingToUndo:this.#h.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#G()})}redo(){this.#h.redo(),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:this.#h.hasSomethingToRedo(),isEmpty:this.#G()})}addCommands(t){this.#h.add(t),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#G()})}#G(){if(this.#s.size===0)return!0;if(this.#s.size===1)for(const t of this.#s.values())return t.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...this.#_],e=()=>{for(const i of t)i.remove()},s=()=>{for(const i of t)this.#K(i)};this.addCommands({cmd:e,undo:s,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#Q(t){for(const e of this.#_)e.unselect();this.#_.clear();for(const e of t)e.isEmpty()||(this.#_.add(e),e.select());this.#P({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#_)t.commit();this.#Q(this.#s.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#w!==I.NONE))&&this.hasSelection){for(const t of this.#_)t.unselect();this.#_.clear(),this.#P({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#B[0]+=t,this.#B[1]+=e;const[i,n]=this.#B,a=[...this.#_],r=1e3;this.#N&&clearTimeout(this.#N),this.#N=setTimeout(()=>{this.#N=null,this.#B[0]=this.#B[1]=0,this.addCommands({cmd:()=>{for(const o of a)this.#s.has(o.id)&&o.translateInPage(i,n)},undo:()=>{for(const o of a)this.#s.has(o.id)&&o.translateInPage(-i,-n)},mustExec:!1})},r);for(const o of a)o.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#r=new Map;for(const t of this.#_)this.#r.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#r)return!1;this.disableUserSelect(!1);const t=this.#r;this.#r=null;let e=!1;for(const[{x:i,y:n,pageIndex:a},r]of t)r.newX=i,r.newY=n,r.newPageIndex=a,e||=i!==r.savedX||n!==r.savedY||a!==r.savedPageIndex;if(!e)return!1;const s=(i,n,a,r)=>{if(this.#s.has(i.id)){const o=this.#n.get(r);o?i._setParentAndPosition(o,n,a):(i.pageIndex=r,i.x=n,i.y=a)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:a,newPageIndex:r}]of t)s(i,n,a,r)},undo:()=>{for(const[i,{savedX:n,savedY:a,savedPageIndex:r}]of t)s(i,n,a,r)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#r)for(const s of this.#r.keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#_.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#w}get imageManager(){return D(this,"imageManager",new Je)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let l=0,h=e.rangeCount;l<h;l++)if(!t.contains(e.getRangeAt(l).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:a}=t.getBoundingClientRect();let r;switch(t.getAttribute("data-main-rotation")){case"90":r=(l,h,d,u)=>({x:(h-i)/a,y:1-(l+d-s)/n,width:u/a,height:d/n});break;case"180":r=(l,h,d,u)=>({x:1-(l+d-s)/n,y:1-(h+u-i)/a,width:d/n,height:u/a});break;case"270":r=(l,h,d,u)=>({x:1-(h+u-i)/a,y:(l-s)/n,width:u/a,height:d/n});break;default:r=(l,h,d,u)=>({x:(l-s)/n,y:(h-i)/a,width:d/n,height:u/a});break}const o=[];for(let l=0,h=e.rangeCount;l<h;l++){const d=e.getRangeAt(l);if(!d.collapsed)for(const{x:u,y:f,width:p,height:g}of d.getClientRects())p===0||g===0||o.push(r(u,f,p,g))}return o.length===0?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#l||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#l?.delete(t)}renderAnnotationElement(t){const e=this.#l?.get(t.data.id);if(!e)return;const s=this.#i.getRawValue(e);s&&(this.#w===I.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}}class _t{#t=null;#e=!1;#s=null;#n=null;#a=null;#i=null;#l=!1;#h=null;#c=null;#o=null;#d=null;#r=!1;static#u=null;static _l10n=null;constructor(t){this.#c=t,this.#r=t._uiManager.useNewAltTextFlow,_t.#u||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){_t._l10n??=t}async render(){const t=this.#s=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#n=document.createElement("span");t.append(e),this.#r?(t.classList.add("new"),t.setAttribute("data-l10n-id",_t.#u.missing),e.setAttribute("data-l10n-id",_t.#u["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=this.#c._uiManager._signal;t.addEventListener("contextmenu",gt,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#r&&this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#p}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#l=!0,i(n))},{signal:s}),await this.#f(),t}get#p(){return this.#t&&"added"||this.#t===null&&this.guessedText&&"review"||"missing"}finish(){this.#s&&(this.#s.focus({focusVisible:this.#l}),this.#l=!1)}isEmpty(){return this.#r?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#r?this.#t!==null||!!this.#o:this.isEmpty()}get guessedText(){return this.#o}async setGuessedText(t){this.#t===null&&(this.#o=t,this.#d=await _t._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#f())}toggleAltTextBadge(t=!1){if(!this.#r||this.#t){this.#h?.remove(),this.#h=null;return}if(!this.#h){const e=this.#h=document.createElement("div");e.className="noAltTextBadge",this.#c.div.append(e)}this.#h.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#o===e&&(e=this.#d),{altText:e,decorative:this.#e,guessedText:this.#o,textWithDisclaimer:this.#d}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#o=s,this.#d=i),!(this.#t===t&&this.#e===e)&&(n||(this.#t=t,this.#e=e),this.#f())}toggle(t=!1){this.#s&&(!t&&this.#i&&(clearTimeout(this.#i),this.#i=null),this.#s.disabled=!t)}shown(){this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#p}})}destroy(){this.#s?.remove(),this.#s=null,this.#n=null,this.#a=null,this.#h?.remove(),this.#h=null}async#f(){const t=this.#s;if(!t)return;if(this.#r){if(t.classList.toggle("done",!!this.#t),t.setAttribute("data-l10n-id",_t.#u[this.#p]),this.#n?.setAttribute("data-l10n-id",_t.#u[`${this.#p}-label`]),!this.#t){this.#a?.remove();return}}else{if(!this.#t&&!this.#e){t.classList.remove("done"),this.#a?.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#a;if(!e){this.#a=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#c.id}`;const i=100,n=this.#c._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#i),this.#i=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#i=setTimeout(()=>{this.#i=null,this.#a.classList.add("show"),this.#c._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#i&&(clearTimeout(this.#i),this.#i=null),this.#a?.classList.remove("show")},{signal:n})}this.#e?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#t),e.parentNode||t.append(e),this.#c.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class k{#t=null;#e=null;#s=null;#n=!1;#a=!1;#i=null;#l=null;#h=null;#c="";#o=!1;#d=null;#r=!1;#u=!1;#p=!1;#f=null;#b=0;#m=0;#g=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#A=!1;#y=k._zIndex++;static _borderLineWidth=-1;static _colorManager=new Ze;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=k.prototype._resizeWithKeyboard,e=kt.TRANSLATE_SMALL,s=kt.TRANSLATE_BIG;return D(this,"_resizerKeyboardManager",new oe([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],k.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;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return D(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Li({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(k._l10n??=t,k._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"}),k._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);k._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){H("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#A}set _isDraggable(t){this.#A=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2),this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2),this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}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.#y}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#O(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#o?this.#o=!1:this.parent.setSelected(this))}focusout(t){!this._focusEventsAllowed||!this.isAttachedToDOM||t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,a]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/a,this.fixAndSetPosition()}#C([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this.fixAndSetPosition()}translate(t,e){this.#C(this.parentDimensions,t,e)}translateInPage(t,e){this.#d||=[this.x,this.y],this.#C(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#d||=[this.x,this.y];const[s,i]=this.parentDimensions;if(this.x+=t/s,this.y+=e/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:l,y:h}=this.div.getBoundingClientRect();this.parent.findNewParent(this,l,h)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:n,y:a}=this;const[r,o]=this.getBaseTranslation();n+=r,a+=o,this.div.style.left=`${(100*n).toFixed(2)}%`,this.div.style.top=`${(100*a).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#d&&(this.#d[0]!==this.x||this.#d[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=k,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[e,s]=this.pageDimensions;let{x:i,y:n,width:a,height:r}=this;if(a*=e,r*=s,i*=e,n*=s,this._mustFixPosition)switch(t){case 0:i=Math.max(0,Math.min(e-a,i)),n=Math.max(0,Math.min(s-r,n));break;case 90:i=Math.max(0,Math.min(e-r,i)),n=Math.min(s,Math.max(a,n));break;case 180:i=Math.min(e,Math.max(a,i)),n=Math.min(s,Math.max(r,n));break;case 270:i=Math.min(e,Math.max(r,i)),n=Math.max(0,Math.min(s-a,n));break}this.x=i/=e,this.y=n/=s;const[o,l]=this.getBaseTranslation();i+=o,n+=l;const{style:h}=this.div;h.left=`${(100*i).toFixed(2)}%`,h.top=`${(100*n).toFixed(2)}%`,this.moveInDOM()}static#E(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return k.#E(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return k.#E(t,e,360-this.parentRotation)}#S(t){switch(t){case 90:{const[e,s]=this.pageDimensions;return[0,-e/s,s/e,0]}case 180:return[-1,0,0,-1];case 270:{const[e,s]=this.pageDimensions;return[0,e/s,-s/e,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,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions;this.div.style.width=`${(100*t/s).toFixed(2)}%`,this.#a||(this.div.style.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#a&&e.endsWith("%");if(i&&n)return;const[a,r]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/a).toFixed(2)}%`),!this.#a&&!n&&(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#D(){if(this.#i)return;this.#i=document.createElement("div"),this.#i.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 s of t){const i=document.createElement("div");this.#i.append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",this.#T.bind(this,s),{signal:e}),i.addEventListener("contextmenu",gt,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#i)}#T(t,e){e.preventDefault();const{isMac:s}=rt.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#s?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1;const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#x.bind(this,t),{passive:!0,capture:!0,signal:a}),window.addEventListener("contextmenu",gt,{signal:a});const r=this.x,o=this.y,l=this.width,h=this.height,d=this.parent.div.style.cursor,u=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const f=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=d,this.div.style.cursor=u,this.#v(r,o,l,h)};window.addEventListener("pointerup",f,{signal:a}),window.addEventListener("blur",f,{signal:a})}#v(t,e,s,i){const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===s&&o===i||this.addCommands({cmd:()=>{this.width=r,this.height=o,this.x=n,this.y=a;const[l,h]=this.parentDimensions;this.setDims(l*r,h*o),this.fixAndSetPosition()},undo:()=>{this.width=s,this.height=i,this.x=t,this.y=e;const[l,h]=this.parentDimensions;this.setDims(l*s,h*i),this.fixAndSetPosition()},mustExec:!0})}#x(t,e){const[s,i]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=k.MIN_SIZE/s,h=k.MIN_SIZE/i,d=T=>Math.round(T*1e4)/1e4,u=this.#S(this.rotation),f=(T,L)=>[u[0]*T+u[2]*L,u[1]*T+u[3]*L],p=this.#S(360-this.rotation),g=(T,L)=>[p[0]*T+p[2]*L,p[1]*T+p[3]*L];let b,m,A=!1,y=!1;switch(t){case"topLeft":A=!0,b=(T,L)=>[0,0],m=(T,L)=>[T,L];break;case"topMiddle":b=(T,L)=>[T/2,0],m=(T,L)=>[T/2,L];break;case"topRight":A=!0,b=(T,L)=>[T,0],m=(T,L)=>[0,L];break;case"middleRight":y=!0,b=(T,L)=>[T,L/2],m=(T,L)=>[0,L/2];break;case"bottomRight":A=!0,b=(T,L)=>[T,L],m=(T,L)=>[0,0];break;case"bottomMiddle":b=(T,L)=>[T/2,L],m=(T,L)=>[T/2,0];break;case"bottomLeft":A=!0,b=(T,L)=>[0,L],m=(T,L)=>[T,0];break;case"middleLeft":y=!0,b=(T,L)=>[0,L/2],m=(T,L)=>[T,L/2];break}const _=b(r,o),v=m(r,o);let w=f(...v);const E=d(n+w[0]),C=d(a+w[1]);let x=1,O=1,[P,B]=this.screenToPageTranslation(e.movementX,e.movementY);if([P,B]=g(P/s,B/i),A){const T=Math.hypot(r,o);x=O=Math.max(Math.min(Math.hypot(v[0]-_[0]-P,v[1]-_[1]-B)/T,1/r,1/o),l/r,h/o)}else y?x=Math.max(l,Math.min(1,Math.abs(v[0]-_[0]-P)))/r:O=Math.max(h,Math.min(1,Math.abs(v[1]-_[1]-B)))/o;const z=d(r*x),X=d(o*O);w=f(...m(z,X));const N=E-w[0],U=C-w[1];this.width=z,this.height=X,this.x=N,this.y=U,this.setDims(s*z,i*X),this.fixAndSetPosition()}altTextFinish(){this.#s?.finish()}async addEditToolbar(){return this._editToolbar||this.#u?this._editToolbar:(this._editToolbar=new ie(this),this.div.append(this._editToolbar.render()),this.#s&&await this._editToolbar.addAltText(this.#s),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#s?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#s||(_t.initialize(k._l10n),this.#s=new _t(this),this.#t&&(this.#s.data=this.#t,this.#t=null),await this.addEditToolbar())}get altTextData(){return this.#s?.data}set altTextData(t){this.#s&&(this.#s.data=t)}get guessedAltText(){return this.#s?.guessedText}async setGuessedAltText(t){await this.#s?.setGuessedText(t)}serializeAltText(t){return this.#s?.serialize(t)}hasAltText(){return!!this.#s&&!this.#s.isEmpty()}hasAltTextData(){return this.#s?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#n?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#L();const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),_e(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=rt.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#o=!0,this._isDraggable){this.#R(t);return}this.#k(t)}get isSelected(){return this._uiManager.isSelected(this)}#k(t){const{isMac:e}=rt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#R(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();const s=new AbortController,i=this._uiManager.combinedSignal(s);if(e){this.div.classList.add("moving"),this.#b=t.clientX,this.#m=t.clientY;const a=r=>{const{clientX:o,clientY:l}=r,[h,d]=this.screenToPageTranslation(o-this.#b,l-this.#m);this.#b=o,this.#m=l,this._uiManager.dragSelectedEditors(h,d)};window.addEventListener("pointermove",a,{passive:!0,capture:!0,signal:i})}const n=()=>{s.abort(),e&&this.div.classList.remove("moving"),this.#o=!1,this._uiManager.endDragSession()||this.#k(t)};window.addEventListener("pointerup",n,{signal:i}),window.addEventListener("blur",n,{signal:i})}moveInDOM(){this.#f&&clearTimeout(this.#f),this.#f=setTimeout(()=>{this.#f=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/i,h=e/i,d=this.x*n,u=this.y*a,f=this.width*n,p=this.height*a;switch(s){case 0:return[d+l+r,a-u-h-p+o,d+l+f+r,a-u-h+o];case 90:return[d+h+r,a-u+l+o,d+h+p+r,a-u+l+f+o];case 180:return[d-l-f+r,a-u+h+o,d-l+r,a-u+h+p+o];case 270:return[d-h-p+r,a-u-l-f+o,d-h+r,a-u-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,a]=t,r=n-s,o=a-i;switch(this.rotation){case 0:return[s,e-a,r,o];case 90:return[s,e-i,o,r];case 180:return[n,e-i,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#u=!0}disableEditMode(){this.#u=!1}isInEditMode(){return this.#u}shouldGetKeyboardEvents(){return this.#p}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}#L(){if(this.#h||!this.div)return;this.#h=new AbortController;const t=this._uiManager.combinedSignal(this.#h);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#L()}rotate(t){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){H("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,i.#t=t.accessibilityData;const[n,a]=i.pageDimensions,[r,o,l,h]=i.getRectInCurrentCoords(t.rect,a);return i.x=r/n,i.y=o/a,i.width=l/n,i.height=h/a,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#h?.abort(),this.#h=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#f&&(clearTimeout(this.#f),this.#f=null),this.#O(),this.removeEditToolbar(),this.#g){for(const t of this.#g.values())clearTimeout(t);this.#g=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#D(),this.#i.classList.remove("hidden"),_e(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#i.children;if(!this.#e){this.#e=Array.from(e);const a=this.#w.bind(this),r=this.#_.bind(this),o=this._uiManager._signal;for(const l of this.#e){const h=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",a,{signal:o}),l.addEventListener("blur",r,{signal:o}),l.addEventListener("focus",this.#I.bind(this,h),{signal:o}),l.setAttribute("data-l10n-id",k._l10nResizer[h])}}const s=this.#e[0];let i=0;for(const a of e){if(a===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#e.length/4);if(n!==i){if(n<i)for(let r=0;r<i-n;r++)this.#i.append(this.#i.firstChild);else if(n>i)for(let r=0;r<n-i;r++)this.#i.firstChild.before(this.#i.lastChild);let a=0;for(const r of e){const l=this.#e[a++].getAttribute("data-resizer-name");r.setAttribute("data-l10n-id",k._l10nResizer[l])}}this.#F(0),this.#p=!0,this.#i.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#w(t){k._resizerKeyboardManager.exec(this,t)}#_(t){this.#p&&t.relatedTarget?.parentNode!==this.#i&&this.#O()}#I(t){this.#c=this.#p?t:""}#F(t){if(this.#e)for(const e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#p&&this.#x(this.#c,{movementX:t,movementY:e})}#O(){if(this.#p=!1,this.#F(-1),this.#l){const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#l;this.#v(t,e,s,i),this.#l=null}}_stopResizingWithKeyboard(){this.#O(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#s?.toggleAltTextBadge(!1)}unselect(){this.#i?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#s?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#r}set isEditing(t){this.#r=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#a=!0;const s=t/e,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}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.#g||=new Map;const{action:s}=t;let i=this.#g.get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#g.delete(s),this.#g.size===0&&(this.#g=null)},k._telemetryTimeout),this.#g.set(s,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.#n=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#n=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class Li extends k{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const gs=3285377520,ft=4294901760,At=65535;class Ds{constructor(t){this.h1=t?t&4294967295:gs,this.h2=t?t&4294967295:gs}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let g=0,b=t.length;g<b;g++){const m=t.charCodeAt(g);m<=255?e[s++]=m:(e[s++]=m>>>8,e[s++]=m&255)}}else if(ArrayBuffer.isView(t))e=t.slice(),s=e.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,n=s-i*4,a=new Uint32Array(e.buffer,0,i);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,u=461845907,f=d&At,p=u&At;for(let g=0;g<i;g++)g&1?(r=a[g],r=r*d&ft|r*f&At,r=r<<15|r>>>17,r=r*u&ft|r*p&At,l^=r,l=l<<13|l>>>19,l=l*5+3864292196):(o=a[g],o=o*d&ft|o*f&At,o=o<<15|o>>>17,o=o*u&ft|o*p&At,h^=o,h=h<<13|h>>>19,h=h*5+3864292196);switch(r=0,n){case 3:r^=e[i*4+2]<<16;case 2:r^=e[i*4+1]<<8;case 1:r^=e[i*4],r=r*d&ft|r*f&At,r=r<<15|r>>>17,r=r*u&ft|r*p&At,i&1?l^=r:h^=r}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&ft|t*36045&At,e=e*4283543511&ft|((e<<16|t>>>16)*2950163797&ft)>>>16,t^=e>>>1,t=t*444984403&ft|t*60499&At,e=e*3301882366&ft|((e<<16|t>>>16)*3120437893&ft)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Ue=Object.freeze({map:null,hash:"",transfer:void 0});class ts{#t=!1;#e=null;#s=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=this.#s.get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return this.#s.get(t)}remove(t){if(this.#s.delete(t),this.#s.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of this.#s.values())if(e instanceof k)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#s.get(t);let i=!1;if(s!==void 0)for(const[n,a]of Object.entries(e))s[n]!==a&&(i=!0,s[n]=a);else i=!0,this.#s.set(t,e);i&&this.#n(),e instanceof k&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#s.has(t)}getAll(){return this.#s.size>0?qe(this.#s):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#s.size}#n(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Os(this)}get serializable(){if(this.#s.size===0)return Ue;const t=new Map,e=new Ds,s=[],i=Object.create(null);let n=!1;for(const[a,r]of this.#s){const o=r instanceof k?r.serialize(!1,i):r;o&&(t.set(a,o),e.update(`${a}:${JSON.stringify(o)}`),n||=!!o.bitmap)}if(n)for(const a of t.values())a.bitmap&&s.push(a.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:Ue}get editorStats(){let t=null;const e=new Map;for(const s of this.#s.values()){if(!(s instanceof k))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const a=t[n]||=new Map;for(const[r,o]of Object.entries(i)){if(r==="type")continue;let l=a.get(r);l||(l=new Map,a.set(r,l));const h=l.get(o)??0;l.set(o,h+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){this.#e=null}get modifiedIds(){if(this.#e)return this.#e;const t=[];for(const e of this.#s.values())!(e instanceof k)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}}class Os extends ts{#t;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable,n=structuredClone(e,i?{transfer:i}:null);this.#t={map:n,hash:s,transfer:i}}get print(){H("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return D(this,"modifiedIds",{ids:new Set,hash:""})}}class Ii{#t=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||this.#t.has(t.loadedName))){if(J(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,a=new FontFace(s,i,n);this.addNativeFontFace(a);try{await a.load(),this.#t.add(s),e?.(t)}catch{F(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}H("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw F(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return D(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(it||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),D(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(J(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const n=s.shift();setTimeout(n.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:e,callback:t};return s.push(i),i}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return D(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(_,v){return _.charCodeAt(v)<<24|_.charCodeAt(v+1)<<16|_.charCodeAt(v+2)<<8|_.charCodeAt(v+3)&255}function i(_,v,w,E){const C=_.substring(0,v),x=_.substring(v+w);return C+E+x}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let l=0;function h(_,v){if(++l>30){F("Load test font never loaded."),v();return}if(o.font="30px "+_,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0){v();return}setTimeout(h.bind(null,_,v))}const d=`lt${Date.now()}${this.loadTestFontId++}`;let u=this._loadTestFont;u=i(u,976,d.length,d);const p=16,g=1482184792;let b=s(u,p);for(n=0,a=d.length-3;n<a;n+=4)b=b-g+s(d,n)|0;n<d.length&&(b=b-g+s(d+"XXX",n)|0),u=i(u,p,4,bi(b));const m=`url(data:font/opentype;base64,${btoa(u)});`,A=`@font-face {font-family:"${d}";src:${m}}`;this.insertRule(A);const y=this._document.createElement("div");y.style.visibility="hidden",y.style.width=y.style.height="10px",y.style.position="absolute",y.style.top=y.style.left="0px";for(const _ of[t.loadedName,d]){const v=this._document.createElement("span");v.textContent="Hi",v.style.fontFamily=_,y.append(v)}this._document.body.append(y),h(d,()=>{y.remove(),e.complete()})}}class Fi{constructor(t,{disableFontFace:e=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const i in t)this[i]=t[i];this.disableFontFace=e===!0,this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{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)}return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Ei(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];let s;try{s=t.get(this.loadedName+"_path_"+e)}catch(n){F(`getPathGenerator - ignoring character: "${n}".`)}if(!Array.isArray(s)||s.length===0)return this.compiledGlyphs[e]=function(n,a){};const i=[];for(let n=0,a=s.length;n<a;)switch(s[n++]){case vt.BEZIER_CURVE_TO:{const[r,o,l,h,d,u]=s.slice(n,n+6);i.push(f=>f.bezierCurveTo(r,o,l,h,d,u)),n+=6}break;case vt.MOVE_TO:{const[r,o]=s.slice(n,n+2);i.push(l=>l.moveTo(r,o)),n+=2}break;case vt.LINE_TO:{const[r,o]=s.slice(n,n+2);i.push(l=>l.lineTo(r,o)),n+=2}break;case vt.QUADRATIC_CURVE_TO:{const[r,o,l,h]=s.slice(n,n+4);i.push(d=>d.quadraticCurveTo(r,o,l,h)),n+=4}break;case vt.RESTORE:i.push(r=>r.restore());break;case vt.SAVE:i.push(r=>r.save());break;case vt.SCALE:J(i.length===2,"Scale command is only valid at the third position.");break;case vt.TRANSFORM:{const[r,o,l,h,d,u]=s.slice(n,n+6);i.push(f=>f.transform(r,o,l,h,d,u)),n+=6}break;case vt.TRANSLATE:{const[r,o]=s.slice(n,n+2);i.push(l=>l.translate(r,o)),n+=2}break}return this.compiledGlyphs[e]=function(a,r){i[0](a),i[1](a),a.scale(r,-r);for(let o=2,l=i.length;o<l;o++)i[o](a)}}}class Ns{#t=!1;constructor({enableHWA:t=!1}){this.#t=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#t})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){H("Abstract method `_createCanvas` called.")}}class Di extends Ns{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class Hs{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(s=>({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){H("Abstract method `_fetch` called.")}}class Bs extends Hs{async _fetch(t){const e=await Ce(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):xe(e)}}class zs{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class Oi extends zs{#t;#e;#s;#n;#a;#i;#l=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#n=t,this.#a=e}get#h(){return this.#e||=new Map}get#c(){return this.#i||=new Map}get#o(){if(!this.#s){const t=this.#a.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 s=this.#a.createElementNS(Et,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#a.createElementNS(Et,"defs"),t.append(s),s.append(this.#s),this.#a.body.append(t)}return this.#s}#d(t){if(t.length===1){const o=t[0],l=new Array(256);for(let d=0;d<256;d++)l[d]=o[d]/255;const h=l.join(",");return[h,h,h]}const[e,s,i]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let o=0;o<256;o++)n[o]=e[o]/255,a[o]=s[o]/255,r[o]=i[o]/255;return[n.join(","),a.join(","),r.join(",")]}#r(t){if(this.#t===void 0){this.#t="";const e=this.#a.URL;e!==this.#a.baseURI&&(Te(e)?F('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=e.split("#",1)[0])}return`url(${this.#t}#${t})`}addFilter(t){if(!t)return"none";let e=this.#h.get(t);if(e)return e;const[s,i,n]=this.#d(t),a=t.length===1?s:`${s}${i}${n}`;if(e=this.#h.get(a),e)return this.#h.set(t,e),e;const r=`g_${this.#n}_transfer_map_${this.#l++}`,o=this.#r(r);this.#h.set(t,o),this.#h.set(a,o);const l=this.#f(r);return this.#m(s,i,n,l),o}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#c.get(i);if(n?.key===s||(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#c.set(i,n)),!t||!e))return n.url;const a=this.#A(t);t=S.makeHexColor(...a);const r=this.#A(e);if(e=S.makeHexColor(...r),this.#o.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const o=new Array(256);for(let f=0;f<=255;f++){const p=f/255;o[f]=p<=.03928?p/12.92:((p+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#n}_hcm_filter`,d=n.filter=this.#f(h);this.#m(l,l,l,d),this.#p(d);const u=(f,p)=>{const g=a[f]/255,b=r[f]/255,m=new Array(p+1);for(let A=0;A<=p;A++)m[A]=g+A/p*(b-g);return m.join(",")};return this.#m(u(0,5),u(1,5),u(2,5),d),n.url=this.#r(h),n.url}addAlphaFilter(t){let e=this.#h.get(t);if(e)return e;const[s]=this.#d([t]),i=`alpha_${s}`;if(e=this.#h.get(i),e)return this.#h.set(t,e),e;const n=`g_${this.#n}_alpha_map_${this.#l++}`,a=this.#r(n);this.#h.set(t,a),this.#h.set(i,a);const r=this.#f(n);return this.#g(s,r),a}addLuminosityFilter(t){let e=this.#h.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#d([t]),i=`luminosity_${s}`):i="luminosity",e=this.#h.get(i),e)return this.#h.set(t,e),e;const n=`g_${this.#n}_luminosity_map_${this.#l++}`,a=this.#r(n);this.#h.set(t,a),this.#h.set(i,a);const r=this.#f(n);return this.#u(r),t&&this.#g(s,r),a}addHighlightHCMFilter(t,e,s,i,n){const a=`${e}-${s}-${i}-${n}`;let r=this.#c.get(t);if(r?.key===a||(r?(r.filter?.remove(),r.key=a,r.url="none",r.filter=null):(r={key:a,url:"none",filter:null},this.#c.set(t,r)),!e||!s))return r.url;const[o,l]=[e,s].map(this.#A.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]),[u,f]=[i,n].map(this.#A.bind(this));d<h&&([h,d,u,f]=[d,h,f,u]),this.#o.style.color="";const p=(m,A,y)=>{const _=new Array(256),v=(d-h)/y,w=m/255,E=(A-m)/(255*y);let C=0;for(let x=0;x<=y;x++){const O=Math.round(h+x*v),P=w+x*E;for(let B=C;B<=O;B++)_[B]=P;C=O+1}for(let x=C;x<256;x++)_[x]=_[C-1];return _.join(",")},g=`g_${this.#n}_hcm_${t}_filter`,b=r.filter=this.#f(g);return this.#p(b),this.#m(p(u[0],f[0],5),p(u[1],f[1],5),p(u[2],f[2],5),b),r.url=this.#r(g),r.url}destroy(t=!1){t&&this.#c.size!==0||(this.#s&&(this.#s.parentNode.parentNode.remove(),this.#s=null),this.#e&&(this.#e.clear(),this.#e=null),this.#l=0)}#u(t){const e=this.#a.createElementNS(Et,"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)}#p(t){const e=this.#a.createElementNS(Et,"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)}#f(t){const e=this.#a.createElementNS(Et,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#o.append(e),e}#b(t,e,s){const i=this.#a.createElementNS(Et,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#m(t,e,s,i){const n=this.#a.createElementNS(Et,"feComponentTransfer");i.append(n),this.#b(n,"feFuncR",t),this.#b(n,"feFuncG",e),this.#b(n,"feFuncB",s)}#g(t,e){const s=this.#a.createElementNS(Et,"feComponentTransfer");e.append(s),this.#b(s,"feFuncA",t)}#A(t){return this.#o.style.color=t,Qe(getComputedStyle(this.#o).getPropertyValue("color"))}}class Us{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(s=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){H("Abstract method `_fetch` called.")}}class js extends Us{async _fetch(t){const e=await Ce(t,"arraybuffer");return new Uint8Array(e)}}if(it){var je=Promise.withResolvers(),Ge=null;(async()=>{const t=await ce(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),e=await ce(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),s=await ce(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),i=await ce(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);let n,a;return new Map(Object.entries({fs:t,http:e,https:s,url:i,canvas:n,path2d:a}))})().then(t=>{Ge=t,je.resolve()},t=>{F(`loadPackages: ${t}`),Ge=new Map,je.resolve()})}class Rt{static get promise(){return je.promise}static get(t){return Ge?.get(t)}}async function Gs(c){const e=await Rt.get("fs").promises.readFile(c);return new Uint8Array(e)}class Ni extends zs{}class Hi extends Ns{_createCanvas(t,e){return Rt.get("canvas").createCanvas(t,e)}}class Bi extends Hs{async _fetch(t){return Gs(t)}}class zi extends Us{async _fetch(t){return Gs(t)}}const at={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function $e(c,t){if(!t)return;const e=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],e,s),c.clip(i)}class es{getPattern(){H("Abstract method `getPattern` called.")}}class Ui extends es{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===at.STROKE||i===at.FILL){const a=e.current.getClippedPathBoundingBox(i,$(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-a[0],-a[1]),s=S.transform(s,[1,0,0,1,a[0],a[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),$e(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(s);n.setTransform(d)}else $e(t,this._bbox),n=this._createGradient(t);return n}}function Fe(c,t,e,s,i,n,a,r){const o=t.coords,l=t.colors,h=c.data,d=c.width*4;let u;o[e+1]>o[s+1]&&(u=e,e=s,s=u,u=n,n=a,a=u),o[s+1]>o[i+1]&&(u=s,s=i,i=u,u=a,a=r,r=u),o[e+1]>o[s+1]&&(u=e,e=s,s=u,u=n,n=a,a=u);const f=(o[e]+t.offsetX)*t.scaleX,p=(o[e+1]+t.offsetY)*t.scaleY,g=(o[s]+t.offsetX)*t.scaleX,b=(o[s+1]+t.offsetY)*t.scaleY,m=(o[i]+t.offsetX)*t.scaleX,A=(o[i+1]+t.offsetY)*t.scaleY;if(p>=A)return;const y=l[n],_=l[n+1],v=l[n+2],w=l[a],E=l[a+1],C=l[a+2],x=l[r],O=l[r+1],P=l[r+2],B=Math.round(p),z=Math.round(A);let X,N,U,T,L,Ct,yt,ut;for(let tt=B;tt<=z;tt++){if(tt<b){const j=tt<p?0:(p-tt)/(p-b);X=f-(f-g)*j,N=y-(y-w)*j,U=_-(_-E)*j,T=v-(v-C)*j}else{let j;tt>A?j=1:b===A?j=0:j=(b-tt)/(b-A),X=g-(g-m)*j,N=w-(w-x)*j,U=E-(E-O)*j,T=C-(C-P)*j}let Y;tt<p?Y=0:tt>A?Y=1:Y=(p-tt)/(p-A),L=f-(f-m)*Y,Ct=y-(y-x)*Y,yt=_-(_-O)*Y,ut=v-(v-P)*Y;const Bt=Math.round(Math.min(X,L)),Xt=Math.round(Math.max(X,L));let ot=d*tt+Bt*4;for(let j=Bt;j<=Xt;j++)Y=(X-j)/(X-L),Y<0?Y=0:Y>1&&(Y=1),h[ot++]=N-(N-Ct)*Y|0,h[ot++]=U-(U-yt)*Y|0,h[ot++]=T-(T-ut)*Y|0,h[ot++]=255}}function ji(c,t,e){const s=t.coords,i=t.colors;let n,a;switch(t.type){case"lattice":const r=t.verticesPerRow,o=Math.floor(s.length/r)-1,l=r-1;for(n=0;n<o;n++){let h=n*r;for(let d=0;d<l;d++,h++)Fe(c,e,s[h],s[h+1],s[h+r],i[h],i[h+1],i[h+r]),Fe(c,e,s[h+r+1],s[h+1],s[h+r],i[h+r+1],i[h+1],i[h+r])}break;case"triangles":for(n=0,a=s.length;n<a;n+=3)Fe(c,e,s[n],s[n+1],s[n+2],i[n],i[n+1],i[n+2]);break;default:throw new Error("illegal figure")}}class Gi extends es{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const r=Math.floor(this._bounds[0]),o=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-r,h=Math.ceil(this._bounds[3])-o,d=Math.min(Math.ceil(Math.abs(l*t[0]*1.1)),3e3),u=Math.min(Math.ceil(Math.abs(h*t[1]*1.1)),3e3),f=l/d,p=h/u,g={coords:this._coords,colors:this._colors,offsetX:-r,offsetY:-o,scaleX:1/f,scaleY:1/p},b=d+4,m=u+4,A=s.getCanvas("mesh",b,m),y=A.context,_=y.createImageData(d,u);if(e){const w=_.data;for(let E=0,C=w.length;E<C;E+=4)w[E]=e[0],w[E+1]=e[1],w[E+2]=e[2],w[E+3]=255}for(const w of this._figures)ji(_,w,g);return y.putImageData(_,2,2),{canvas:A.canvas,offsetX:r-2*f,offsetY:o-2*p,scaleX:f,scaleY:p}}getPattern(t,e,s,i){$e(t,this._bbox);let n;if(i===at.SHADING)n=S.singularValueDecompose2dScale($(t));else if(n=S.singularValueDecompose2dScale(e.baseTransform),this.matrix){const r=S.singularValueDecompose2dScale(this.matrix);n=[n[0]*r[0],n[1]*r[1]]}const a=this._createMeshCanvas(n,i===at.SHADING?null:this._background,e.cachedCanvases);return i!==at.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(a.offsetX,a.offsetY),t.scale(a.scaleX,a.scaleY),t.createPattern(a.canvas,"no-repeat")}}class $i extends es{getPattern(){return"hotpink"}}function Wi(c){switch(c[0]){case"RadialAxial":return new Ui(c);case"Mesh":return new Gi(c);case"Dummy":return new $i}throw new Error(`Unknown IR type: ${c[0]}`)}const ms={COLORED:1,UNCOLORED:2};class ss{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:a,canvasGraphicsFactory:r}=this;let{xstep:o,ystep:l}=this;o=Math.abs(o),l=Math.abs(l),Ee("TilingType: "+n);const h=e[0],d=e[1],u=e[2],f=e[3],p=u-h,g=f-d,b=S.singularValueDecompose2dScale(this.matrix),m=S.singularValueDecompose2dScale(this.baseTransform),A=b[0]*m[0],y=b[1]*m[1];let _=p,v=g,w=!1,E=!1;const C=Math.ceil(o*A),x=Math.ceil(l*y),O=Math.ceil(p*A),P=Math.ceil(g*y);C>=O?_=o:w=!0,x>=P?v=l:E=!0;const B=this.getSizeAndScale(_,this.ctx.canvas.width,A),z=this.getSizeAndScale(v,this.ctx.canvas.height,y),X=t.cachedCanvases.getCanvas("pattern",B.size,z.size),N=X.context,U=r.createCanvasGraphics(N);if(U.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(U,i,a),N.translate(-B.scale*h,-z.scale*d),U.transform(B.scale,0,0,z.scale,0,0),N.save(),this.clipBbox(U,h,d,u,f),U.baseTransform=$(U.ctx),U.executeOperatorList(s),U.endDrawing(),N.restore(),w||E){const T=X.canvas;w&&(_=o),E&&(v=l);const L=this.getSizeAndScale(_,this.ctx.canvas.width,A),Ct=this.getSizeAndScale(v,this.ctx.canvas.height,y),yt=L.size,ut=Ct.size,tt=t.cachedCanvases.getCanvas("pattern-workaround",yt,ut),Y=tt.context,Bt=w?Math.floor(p/o):0,Xt=E?Math.floor(g/l):0;for(let ot=0;ot<=Bt;ot++)for(let j=0;j<=Xt;j++)Y.drawImage(T,yt*ot,ut*j,yt,ut,0,0,yt,ut);return{canvas:tt.canvas,scaleX:L.scale,scaleY:Ct.scale,offsetX:h,offsetY:d}}return{canvas:X.canvas,scaleX:B.scale,scaleY:z.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,s){const i=Math.max(ss.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const a=i-e,r=n-s;t.ctx.rect(e,s,a,r),t.current.updateRectMinMax($(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case ms.COLORED:const a=this.ctx;i.fillStyle=a.fillStyle,i.strokeStyle=a.strokeStyle,n.fillColor=a.fillStyle,n.strokeColor=a.strokeStyle;break;case ms.UNCOLORED:const r=S.makeHexColor(s[0],s[1],s[2]);i.fillStyle=r,i.strokeStyle=r,n.fillColor=r,n.strokeColor=r;break;default:throw new mi(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==at.SHADING&&(n=S.transform(n,e.baseTransform),this.matrix&&(n=S.transform(n,this.matrix)));const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY),r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");return o.setTransform(r),o}}function Vi({src:c,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:a=!1}){const r=rt.isLittleEndian?4278190080:255,[o,l]=a?[n,r]:[r,n],h=s>>3,d=s&7,u=c.length;e=new Uint32Array(e.buffer);let f=0;for(let p=0;p<i;p++){for(const b=t+h;t<b;t++){const m=t<u?c[t]:255;e[f++]=m&128?l:o,e[f++]=m&64?l:o,e[f++]=m&32?l:o,e[f++]=m&16?l:o,e[f++]=m&8?l:o,e[f++]=m&4?l:o,e[f++]=m&2?l:o,e[f++]=m&1?l:o}if(d===0)continue;const g=t<u?c[t++]:255;for(let b=0;b<d;b++)e[f++]=g&1<<7-b?l:o}return{srcPos:t,destPos:f}}const bs=16,As=100,qi=15,_s=10,ys=1e3,ht=16;function Xi(c,t){if(c._removeMirroring)throw new Error("Context is already forwarding operations.");c.__originalSave=c.save,c.__originalRestore=c.restore,c.__originalRotate=c.rotate,c.__originalScale=c.scale,c.__originalTranslate=c.translate,c.__originalTransform=c.transform,c.__originalSetTransform=c.setTransform,c.__originalResetTransform=c.resetTransform,c.__originalClip=c.clip,c.__originalMoveTo=c.moveTo,c.__originalLineTo=c.lineTo,c.__originalBezierCurveTo=c.bezierCurveTo,c.__originalRect=c.rect,c.__originalClosePath=c.closePath,c.__originalBeginPath=c.beginPath,c._removeMirroring=()=>{c.save=c.__originalSave,c.restore=c.__originalRestore,c.rotate=c.__originalRotate,c.scale=c.__originalScale,c.translate=c.__originalTranslate,c.transform=c.__originalTransform,c.setTransform=c.__originalSetTransform,c.resetTransform=c.__originalResetTransform,c.clip=c.__originalClip,c.moveTo=c.__originalMoveTo,c.lineTo=c.__originalLineTo,c.bezierCurveTo=c.__originalBezierCurveTo,c.rect=c.__originalRect,c.closePath=c.__originalClosePath,c.beginPath=c.__originalBeginPath,delete c._removeMirroring},c.save=function(){t.save(),this.__originalSave()},c.restore=function(){t.restore(),this.__originalRestore()},c.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},c.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},c.transform=function(s,i,n,a,r,o){t.transform(s,i,n,a,r,o),this.__originalTransform(s,i,n,a,r,o)},c.setTransform=function(s,i,n,a,r,o){t.setTransform(s,i,n,a,r,o),this.__originalSetTransform(s,i,n,a,r,o)},c.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},c.rotate=function(s){t.rotate(s),this.__originalRotate(s)},c.clip=function(s){t.clip(s),this.__originalClip(s)},c.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},c.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},c.bezierCurveTo=function(e,s,i,n,a,r){t.bezierCurveTo(e,s,i,n,a,r),this.__originalBezierCurveTo(e,s,i,n,a,r)},c.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},c.closePath=function(){t.closePath(),this.__originalClosePath()},c.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class Yi{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return this.cache[t]!==void 0?(i=this.cache[t],this.canvasFactory.reset(i,e,s)):(i=this.canvasFactory.create(e,s),this.cache[t]=i),i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function de(c,t,e,s,i,n,a,r,o,l){const[h,d,u,f,p,g]=$(c);if(d===0&&u===0){const A=a*h+p,y=Math.round(A),_=r*f+g,v=Math.round(_),w=(a+o)*h+p,E=Math.abs(Math.round(w)-y)||1,C=(r+l)*f+g,x=Math.abs(Math.round(C)-v)||1;return c.setTransform(Math.sign(h),0,0,Math.sign(f),y,v),c.drawImage(t,e,s,i,n,0,0,E,x),c.setTransform(h,d,u,f,p,g),[E,x]}if(h===0&&f===0){const A=r*u+p,y=Math.round(A),_=a*d+g,v=Math.round(_),w=(r+l)*u+p,E=Math.abs(Math.round(w)-y)||1,C=(a+o)*d+g,x=Math.abs(Math.round(C)-v)||1;return c.setTransform(0,Math.sign(d),Math.sign(u),0,y,v),c.drawImage(t,e,s,i,n,0,0,x,E),c.setTransform(h,d,u,f,p,g),[x,E]}c.drawImage(t,e,s,i,n,a,r,o,l);const b=Math.hypot(h,d),m=Math.hypot(u,f);return[b*o,m*l]}function Ki(c){const{width:t,height:e}=c;if(t>ys||e>ys)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=t+1;let a=new Uint8Array(n*(e+1)),r,o,l;const h=t+7&-8;let d=new Uint8Array(h*e),u=0;for(const m of c.data){let A=128;for(;A>0;)d[u++]=m&A?0:255,A>>=1}let f=0;for(u=0,d[u]!==0&&(a[0]=1,++f),o=1;o<t;o++)d[u]!==d[u+1]&&(a[o]=d[u]?2:1,++f),u++;for(d[u]!==0&&(a[o]=2,++f),r=1;r<e;r++){u=r*h,l=r*n,d[u-h]!==d[u]&&(a[l]=d[u]?1:8,++f);let m=(d[u]?4:0)+(d[u-h]?8:0);for(o=1;o<t;o++)m=(m>>2)+(d[u+1]?4:0)+(d[u-h+1]?8:0),i[m]&&(a[l+o]=i[m],++f),u++;if(d[u-h]!==d[u]&&(a[l+o]=d[u]?2:4,++f),f>s)return null}for(u=h*(e-1),l=r*n,d[u]!==0&&(a[l]=8,++f),o=1;o<t;o++)d[u]!==d[u+1]&&(a[l+o]=d[u]?4:8,++f),u++;if(d[u]!==0&&(a[l+o]=4,++f),f>s)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(r=0;f&&r<=e;r++){let m=r*n;const A=m+t;for(;m<A&&!a[m];)m++;if(m===A)continue;g.moveTo(m%n,r);const y=m;let _=a[m];do{const v=p[_];do m+=v;while(!a[m]);const w=a[m];w!==5&&w!==10?(_=w,a[m]=0):(_=w&51*_>>4,a[m]&=_>>2|_<<2),g.lineTo(m%n,m/n|0),a[m]||--f}while(y!==m);--r}return d=null,a=null,function(m){m.save(),m.scale(1/t,-1/e),m.translate(0,-e),m.fill(g),m.beginPath(),m.restore()}}class vs{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Ps,this.textMatrixScale=1,this.fontMatrix=Ne,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=et.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=S.applyTransform([e,s],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=S.applyTransform(e,t),i=S.applyTransform(e.slice(2),t),n=S.applyTransform([e[0],e[3]],t),a=S.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],a[0]),this.minY=Math.min(this.minY,s[1],i[1],n[1],a[1]),this.maxX=Math.max(this.maxX,s[0],i[0],n[0],a[0]),this.maxY=Math.max(this.maxY,s[1],i[1],n[1],a[1])}updateScalingPathMinMax(t,e){S.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,a,r,o,l,h){const d=S.bezierBoundingBox(e,s,i,n,a,r,o,l,h);h||this.updateRectMinMax(t,d)}getPathBoundingBox(t=at.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===at.STROKE){e||H("Stroke bounding box must include transform.");const i=S.singularValueDecompose2dScale(e),n=i[0]*this.lineWidth/2,a=i[1]*this.lineWidth/2;s[0]-=n,s[1]-=a,s[2]+=n,s[3]+=a}return s}updateClipFromPath(){const t=S.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=at.FILL,e=null){return S.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function ws(c,t){if(typeof ImageData<"u"&&t instanceof ImageData){c.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%ht,n=(e-i)/ht,a=i===0?n:n+1,r=c.createImageData(s,ht);let o=0,l;const h=t.data,d=r.data;let u,f,p,g;if(t.kind===me.GRAYSCALE_1BPP){const b=h.byteLength,m=new Uint32Array(d.buffer,0,d.byteLength>>2),A=m.length,y=s+7>>3,_=4294967295,v=rt.isLittleEndian?4278190080:255;for(u=0;u<a;u++){for(p=u<n?ht:i,l=0,f=0;f<p;f++){const w=b-o;let E=0;const C=w>y?s:w*8-7,x=C&-8;let O=0,P=0;for(;E<x;E+=8)P=h[o++],m[l++]=P&128?_:v,m[l++]=P&64?_:v,m[l++]=P&32?_:v,m[l++]=P&16?_:v,m[l++]=P&8?_:v,m[l++]=P&4?_:v,m[l++]=P&2?_:v,m[l++]=P&1?_:v;for(;E<C;E++)O===0&&(P=h[o++],O=128),m[l++]=P&O?_:v,O>>=1}for(;l<A;)m[l++]=0;c.putImageData(r,0,u*ht)}}else if(t.kind===me.RGBA_32BPP){for(f=0,g=s*ht*4,u=0;u<n;u++)d.set(h.subarray(o,o+g)),o+=g,c.putImageData(r,0,f),f+=ht;u<a&&(g=s*i*4,d.set(h.subarray(o,o+g)),c.putImageData(r,0,f))}else if(t.kind===me.RGB_24BPP)for(p=ht,g=s*p,u=0;u<a;u++){for(u>=n&&(p=i,g=s*p),l=0,f=g;f--;)d[l++]=h[o++],d[l++]=h[o++],d[l++]=h[o++],d[l++]=255;c.putImageData(r,0,u*ht)}else throw new Error(`bad image kind: ${t.kind}`)}function Es(c,t){if(t.bitmap){c.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%ht,n=(e-i)/ht,a=i===0?n:n+1,r=c.createImageData(s,ht);let o=0;const l=t.data,h=r.data;for(let d=0;d<a;d++){const u=d<n?ht:i;({srcPos:o}=Vi({src:l,srcPos:o,dest:h,width:s,height:u,nonBlackColor:0})),c.putImageData(r,0,d*ht)}}function Jt(c,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)c[s]!==void 0&&(t[s]=c[s]);c.setLineDash!==void 0&&(t.setLineDash(c.getLineDash()),t.lineDashOffset=c.lineDashOffset)}function ue(c){if(c.strokeStyle=c.fillStyle="#000000",c.fillRule="nonzero",c.globalAlpha=1,c.lineWidth=1,c.lineCap="butt",c.lineJoin="miter",c.miterLimit=10,c.globalCompositeOperation="source-over",c.font="10px sans-serif",c.setLineDash!==void 0&&(c.setLineDash([]),c.lineDashOffset=0),!it){const{filter:t}=c;t!=="none"&&t!==""&&(c.filter="none")}}function Ss(c,t){if(t)return!0;const e=S.singularValueDecompose2dScale(c);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*qt.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const Qi=["butt","round","square"],Ji=["miter","round","bevel"],Zi={},xs={};class Gt{constructor(t,e,s,i,n,{optionalContentConfig:a,markedContentStack:r=null},o,l){this.ctx=t,this.current=new vs(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=r||[],this.optionalContentConfig=a,this.cachedCanvases=new Yi(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,a=this.ctx.canvas.height,r=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,a),this.ctx.fillStyle=r,s){const o=this.cachedCanvases.getCanvas("transparent",n,a);this.compositeCtx=this.ctx,this.transparentCanvas=o.canvas,this.ctx=o.context,this.ctx.save(),this.ctx.transform(...$(this.compositeCtx))}this.ctx.save(),ue(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=$(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,a=t.fnArray;let r=e||0;const o=n.length;if(o===r)return r;const l=o-r>_s&&typeof s=="function",h=l?Date.now()+qi:0;let d=0;const u=this.commonObjs,f=this.objs;let p;for(;;){if(i!==void 0&&r===i.nextBreakPoint)return i.breakIt(r,s),r;if(p=a[r],p!==bt.dependency)this[p].apply(this,n[r]);else for(const g of n[r]){const b=g.startsWith("g_")?u:f;if(!b.has(g))return b.get(g,s),r}if(r++,r===o)return r;if(l&&++d>_s){if(Date.now()>h)return s(),r;d=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){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 s=t.width??t.displayWidth,i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1),a=Math.max(Math.hypot(e[2],e[3]),1),r=s,o=i,l="prescale1",h,d;for(;n>2&&r>1||a>2&&o>1;){let u=r,f=o;n>2&&r>1&&(u=r>=16384?Math.floor(r/2)-1||1:Math.ceil(r/2),n/=r/u),a>2&&o>1&&(f=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o)/2,a/=o/f),h=this.cachedCanvases.getCanvas(l,u,f),d=h.context,d.clearRect(0,0,u,f),d.drawImage(t,0,0,r,o,0,0,u,f),t=h.canvas,r=u,o=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:r,paintHeight:o}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,a=this.current.patternFill,r=$(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const C=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]),o=this._cachedBitmapsMap.get(C),o||(o=new Map,this._cachedBitmapsMap.set(C,o));const x=o.get(l);if(x&&!a){const O=Math.round(Math.min(r[0],r[2])+r[4]),P=Math.round(Math.min(r[1],r[3])+r[5]);return{canvas:x,offsetX:O,offsetY:P}}h=x}h||(d=this.cachedCanvases.getCanvas("maskCanvas",s,i),Es(d.context,t));let u=S.transform(r,[1/s,0,0,-1/i,0,0]);u=S.transform(u,[1,0,0,1,0,-i]);const[f,p,g,b]=S.getAxialAlignedBoundingBox([0,0,s,i],u),m=Math.round(g-f)||1,A=Math.round(b-p)||1,y=this.cachedCanvases.getCanvas("fillCanvas",m,A),_=y.context,v=f,w=p;_.translate(-v,-w),_.transform(...u),h||(h=this._scaleImage(d.canvas,wt(_)),h=h.img,o&&a&&o.set(l,h)),_.imageSmoothingEnabled=Ss($(_),t.interpolate),de(_,h,0,0,h.width,h.height,0,0,s,i),_.globalCompositeOperation="source-in";const E=S.transform(wt(_),[1,0,0,1,-v,-w]);return _.fillStyle=a?n.getPattern(e,this,E,at.FILL):n,_.fillRect(0,0,s,i),o&&!a&&(this.cachedCanvases.delete("fillCanvas"),o.set(l,y.canvas)),{canvas:y.canvas,offsetX:Math.round(v),offsetY:Math.round(w)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=Qi[t]}setLineJoin(t){this.ctx.lineJoin=Ji[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...$(this.suspendedCtx)),Jt(this.suspendedCtx,n),Xi(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Jt(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],a=i[1],r=i[2]-n,o=i[3]-a;r===0||o===0||(this.genericComposeSMask(e.context,s,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,a,r,o,l,h,d){let u=t.canvas,f=o-h,p=l-d;if(a){const b=S.makeHexColor(...a);if(f<0||p<0||f+s>u.width||p+i>u.height){const m=this.cachedCanvases.getCanvas("maskExtension",s,i),A=m.context;A.drawImage(u,-f,-p),A.globalCompositeOperation="destination-atop",A.fillStyle=b,A.fillRect(0,0,s,i),A.globalCompositeOperation="source-over",u=m.canvas,f=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const m=new Path2D;m.rect(f,p,s,i),t.clip(m),t.globalCompositeOperation="destination-atop",t.fillStyle=b,t.fillRect(f,p,s,i),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),n==="Alpha"&&r?e.filter=this.filterFactory.addAlphaFilter(r):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,s,i),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(u,f,p,s,i,o,l,s,i),e.restore()}save(){this.inSMaskMode?(Jt(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),Jt(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,a){this.ctx.transform(t,e,s,i,n,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let a=n.x,r=n.y,o,l;const h=$(i),d=h[0]===0&&h[3]===0||h[1]===0&&h[2]===0,u=d?s.slice(0):null;for(let f=0,p=0,g=t.length;f<g;f++)switch(t[f]|0){case bt.rectangle:a=e[p++],r=e[p++];const b=e[p++],m=e[p++],A=a+b,y=r+m;i.moveTo(a,r),b===0||m===0?i.lineTo(A,y):(i.lineTo(A,r),i.lineTo(A,y),i.lineTo(a,y)),d||n.updateRectMinMax(h,[a,r,A,y]),i.closePath();break;case bt.moveTo:a=e[p++],r=e[p++],i.moveTo(a,r),d||n.updatePathMinMax(h,a,r);break;case bt.lineTo:a=e[p++],r=e[p++],i.lineTo(a,r),d||n.updatePathMinMax(h,a,r);break;case bt.curveTo:o=a,l=r,a=e[p+4],r=e[p+5],i.bezierCurveTo(e[p],e[p+1],e[p+2],e[p+3],a,r),n.updateCurvePathMinMax(h,o,l,e[p],e[p+1],e[p+2],e[p+3],a,r,u),p+=6;break;case bt.curveTo2:o=a,l=r,i.bezierCurveTo(a,r,e[p],e[p+1],e[p+2],e[p+3]),n.updateCurvePathMinMax(h,o,l,a,r,e[p],e[p+1],e[p+2],e[p+3],u),a=e[p+2],r=e[p+3],p+=4;break;case bt.curveTo3:o=a,l=r,a=e[p+2],r=e[p+3],i.bezierCurveTo(e[p],e[p+1],a,r,a,r),n.updateCurvePathMinMax(h,o,l,e[p],e[p+1],a,r,a,r,u),p+=4;break;case bt.closePath:i.closePath();break}d&&n.updateScalingPathMinMax(h,u),n.setCurrentPoint(a,r)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof s=="object"&&s?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,wt(e),at.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,wt(e),at.FILL),n=!0);const a=this.current.getClippedPathBoundingBox();this.contentVisible&&a!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(a)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=Zi}eoClip(){this.pendingClip=xs}beginText(){this.current.textMatrix=Ps,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(t===void 0){e.beginPath();return}e.save(),e.beginPath();for(const s of t)e.setTransform(...s.transform),e.translate(s.x,s.y),s.addToPath(e,s.fontSize);e.restore(),e.clip(),e.beginPath(),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||Ne,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&F("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",a=s.systemFontInfo?.css||`"${n}", ${s.fallbackName}`;let r="normal";s.black?r="900":s.bold&&(r="bold");const o=s.italic?"italic":"normal";let l=e;e<bs?l=bs:e>As&&(l=As),this.current.fontSizeScale=e/l,this.ctx.font=`${o} ${r} ${l}px ${a}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,a){this.current.textMatrix=[t,e,s,i,n,a],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,s,i){const n=this.ctx,a=this.current,r=a.font,o=a.textRenderingMode,l=a.fontSize/a.fontSizeScale,h=o&et.FILL_STROKE_MASK,d=!!(o&et.ADD_TO_PATH_FLAG),u=a.patternFill&&!r.missingFile;let f;(r.disableFontFace||d||u)&&(f=r.getPathGenerator(this.commonObjs,t)),r.disableFontFace||u?(n.save(),n.translate(e,s),n.beginPath(),f(n,l),i&&n.setTransform(...i),(h===et.FILL||h===et.FILL_STROKE)&&n.fill(),(h===et.STROKE||h===et.FILL_STROKE)&&n.stroke(),n.restore()):((h===et.FILL||h===et.FILL_STROKE)&&n.fillText(t,e,s),(h===et.STROKE||h===et.FILL_STROKE)&&n.strokeText(t,e,s)),d&&(this.pendingTextPaths||=[]).push({transform:$(n),x:e,y:s,fontSize:l,addToPath:f})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return D(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,u=s.vertical,f=u?1:-1,p=s.defaultVMetrics,g=i*e.fontMatrix[0],b=e.textRenderingMode===et.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(h,-1):n.scale(h,1);let m;if(e.patternFill){n.save();const w=e.fillColor.getPattern(n,this,wt(n),at.FILL);m=$(n),n.restore(),n.fillStyle=w}let A=e.lineWidth;const y=e.textMatrixScale;if(y===0||A===0){const w=e.textRenderingMode&et.FILL_STROKE_MASK;(w===et.STROKE||w===et.FILL_STROKE)&&(A=this.getSinglePixelWidth())}else A/=y;if(a!==1&&(n.scale(a,a),A/=a),n.lineWidth=A,s.isInvalidPDFjsFont){const w=[];let E=0;for(const C of t)w.push(C.unicode),E+=C.width;n.fillText(w.join(""),0,0),e.x+=E*g*h,n.restore(),this.compose();return}let _=0,v;for(v=0;v<d;++v){const w=t[v];if(typeof w=="number"){_+=f*w*i/1e3;continue}let E=!1;const C=(w.isSpace?o:0)+r,x=w.fontChar,O=w.accent;let P,B,z=w.width;if(u){const N=w.vmetric||p,U=-(w.vmetric?N[1]:z*.5)*g,T=N[2]*g;z=N?-N[0]:z,P=U/a,B=(_+T)/a}else P=_/a,B=0;if(s.remeasure&&z>0){const N=n.measureText(x).width*1e3/i*a;if(z<N&&this.isFontSubpixelAAEnabled){const U=z/N;E=!0,n.save(),n.scale(U,1),P/=U}else z!==N&&(P+=(z-N)/2e3*i/a)}if(this.contentVisible&&(w.isInFont||s.missingFile)){if(b&&!O)n.fillText(x,P,B);else if(this.paintChar(x,P,B,m),O){const N=P+i*O.offset.x/a,U=B-i*O.offset.y/a;this.paintChar(O.fontChar,N,U,m)}}const X=u?z*g-C*l:z*g+C*l;_+=X,E&&n.restore()}u?e.y-=_:e.x+=_*h,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,a=s.fontDirection,r=i.vertical?1:-1,o=s.charSpacing,l=s.wordSpacing,h=s.textHScale*a,d=s.fontMatrix||Ne,u=t.length,f=s.textRenderingMode===et.INVISIBLE;let p,g,b,m;if(!(f||n===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(h,a),p=0;p<u;++p){if(g=t[p],typeof g=="number"){m=r*g*n/1e3,this.ctx.translate(m,0),s.x+=m*h;continue}const A=(g.isSpace?l:0)+o,y=i.charProcOperatorList[g.operatorListId];if(!y){F(`Type3 character "${g.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=g,this.save(),e.scale(n,n),e.transform(...d),this.executeOperatorList(y),this.restore()),b=S.applyTransform([g.width,0],d)[0]*n+A,e.translate(b,0),s.x+=b*h}e.restore(),this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,a){this.ctx.rect(s,i,n-s,a-i),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let e;if(t[0]==="TilingPattern"){const s=t[1],i=this.baseTransform||$(this.ctx),n={createCanvasGraphics:a=>new Gt(a,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new ss(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=S.makeHexColor(t,e,s)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=S.makeHexColor(t,e,s),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=Wi(this.getObject(t)),this.cachedPatterns.set(t,s)),e&&(s.matrix=e),s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,wt(e),at.SHADING);const i=wt(e);if(i){const{width:n,height:a}=e.canvas,[r,o,l,h]=S.getAxialAlignedBoundingBox([0,0,n,a],i);this.ctx.fillRect(r,o,l-r,h-o)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){H("Should not call beginInlineImage")}beginImageData(){H("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=$(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax($(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||Ee("TODO: Support non-isolated groups."),t.knockout&&F("Knockout groups not supported.");const s=$(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=S.getAxialAlignedBoundingBox(t.bbox,$(e));const n=[0,0,e.canvas.width,e.canvas.height];i=S.intersect(i,n)||[0,0,0,0];const a=Math.floor(i[0]),r=Math.floor(i[1]),o=Math.max(Math.ceil(i[2])-a,1),l=Math.max(Math.ceil(i[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),u=d.context;u.translate(-a,-r),u.transform(...s),t.smask?this.smaskStack.push({canvas:d.canvas,context:u,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(a,r),e.save()),Jt(e,u),this.ctx=u,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=$(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=S.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],i);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,s,i,n){if(this.#t(),ue(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const a=e[2]-e[0],r=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice(),s[4]-=e[0],s[5]-=e[1],e=e.slice(),e[0]=e[1]=0,e[2]=a,e[3]=r;const[o,l]=S.singularValueDecompose2dScale($(this.ctx)),{viewportScale:h}=this,d=Math.ceil(a*this.outputScaleX*h),u=Math.ceil(r*this.outputScaleY*h);this.annotationCanvas=this.canvasFactory.create(d,u);const{canvas:f,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=p,this.ctx.save(),this.ctx.setTransform(o,0,0,-l,0,r*l),ue(this.ctx)}else ue(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],a,r),this.ctx.clip(),this.ctx.beginPath()}this.current=new vs(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;t=this.getObject(t.data,t),t.count=e;const s=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=Ki(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),a=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(a,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=$(r);r.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let h=0,d=a.length;h<d;h+=2){const u=S.transform(o,[e,s,i,n,a[h],a[h+1]]),[f,p]=S.applyTransform([0,0],u);r.drawImage(l.canvas,f,p)}r.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;for(const n of t){const{data:a,width:r,height:o,transform:l}=n,h=this.cachedCanvases.getCanvas("maskCanvas",r,o),d=h.context;d.save();const u=this.getObject(a,n);Es(d,u),d.globalCompositeOperation="source-in",d.fillStyle=i?s.getPattern(d,this,wt(e),at.FILL):s,d.fillRect(0,0,r,o),d.restore(),e.save(),e.transform(...l),e.scale(1,-1),de(e,h.canvas,0,0,r,o,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){F("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){F("Dependent image isn't ready yet");return}const a=n.width,r=n.height,o=[];for(let l=0,h=i.length;l<h;l+=2)o.push({transform:[e,0,0,s,i[l],i[l+1]],x:0,y:0,w:a,h:r});this.paintInlineImageXObjectGroup(n,o)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),a=n.context;return a.filter=this.current.transferMaps,a.drawImage(e,0,0),a.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!it){const{filter:r}=i;r!=="none"&&r!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const o=this.cachedCanvases.getCanvas("inlineImage",e,s).context;ws(o,t),n=this.applyTransferMapsToCanvas(o)}const a=this._scaleImage(n,wt(i));i.imageSmoothingEnabled=Ss($(i),t.interpolate),de(i,a.img,0,0,a.paintWidth,a.paintHeight,0,-s,e,s),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const n=t.width,a=t.height,o=this.cachedCanvases.getCanvas("inlineImage",n,a).context;ws(o,t),i=this.applyTransferMapsToCanvas(o)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),de(s,i,n.x,n.y,n.w,n.h,0,-1,1,1),s.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(t);const s=this.ctx;this.pendingClip&&(e||(this.pendingClip===xs?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=$(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let a,r;if(s===0&&i===0){const o=Math.abs(e),l=Math.abs(n);if(o===l)if(t===0)a=r=1/o;else{const h=o*t;a=r=h<1?1/h:1}else if(t===0)a=1/o,r=1/l;else{const h=o*t,d=l*t;a=h<1?1/h:1,r=d<1?1/d:1}}else{const o=Math.abs(e*n-s*i),l=Math.hypot(e,s),h=Math.hypot(i,n);if(t===0)a=h/o,r=l/o;else{const d=t*o;a=h>d?h/d:1,r=l>d?l/d:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const a=e.getLineDash();if(t&&e.save(),e.scale(i,n),a.length>0){const r=Math.max(i,n);e.setLineDash(a.map(o=>o/r)),e.lineDashOffset/=r}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const c in bt)Gt.prototype[c]!==void 0&&(Gt.prototype[bt[c]]=Gt.prototype[c]);class ne{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");this.#t=t}static get workerSrc(){return this.#e}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");this.#e=t}}const fe={DATA:1,ERROR:2},q={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function ct(c){switch(c instanceof Error||typeof c=="object"&&c!==null||H('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),c.name){case"AbortException":return new Nt(c.message);case"MissingPDFException":return new Ot(c.message);case"PasswordException":return new He(c.message,c.code);case"UnexpectedResponseException":return new Se(c.message,c.status);case"UnknownErrorException":return new Be(c.message,c.details);default:return new Be(c.message,c.toString())}}class ee{#t=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,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),s.addEventListener("message",this.#e.bind(this),{signal:this.#t.signal})}#e({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#n(t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===fe.DATA)i.resolve(t.data);else if(t.callback===fe.ERROR)i.reject(ct(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;new Promise(function(a){a(e(t.data))}).then(function(a){n.postMessage({sourceName:s,targetName:i,callback:fe.DATA,callbackId:t.callbackId,data:a})},function(a){n.postMessage({sourceName:s,targetName:i,callback:fe.ERROR,callbackId:t.callbackId,reason:ct(a)})});return}if(t.streamId){this.#s(t);return}e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(a){n.reject(a)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:l=>{const h=Promise.withResolvers();return this.streamControllers[n]={controller:l,startCall:h,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:l.desiredSize},i),h.promise},pull:l=>{const h=Promise.withResolvers();return this.streamControllers[n].pullCall=h,o.postMessage({sourceName:a,targetName:r,stream:q.PULL,streamId:n,desiredSize:l.desiredSize}),h.promise},cancel:l=>{J(l instanceof Error,"cancel must have a valid reason");const h=Promise.withResolvers();return this.streamControllers[n].cancelCall=h,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:a,targetName:r,stream:q.CANCEL,streamId:n,reason:ct(l)}),h.promise}},s)}#s(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(l,h=1,d){if(this.isCancelled)return;const u=this.desiredSize;this.desiredSize-=h,u>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:q.ENQUEUE,streamId:e,chunk:l},d)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:q.CLOSE,streamId:e}),delete a.streamSinks[e])},error(l){J(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:q.ERROR,streamId:e,reason:ct(l)}))},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,new Promise(function(l){l(r(t.data,o))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:q.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:q.START_COMPLETE,streamId:e,reason:ct(l)})})}#n(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case q.START_COMPLETE:t.success?a.startCall.resolve():a.startCall.reject(ct(t.reason));break;case q.PULL_COMPLETE:t.success?a.pullCall.resolve():a.pullCall.reject(ct(t.reason));break;case q.PULL:if(!r){n.postMessage({sourceName:s,targetName:i,stream:q.PULL_COMPLETE,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,new Promise(function(o){o(r.onPull?.())}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:q.PULL_COMPLETE,streamId:e,success:!0})},function(o){n.postMessage({sourceName:s,targetName:i,stream:q.PULL_COMPLETE,streamId:e,reason:ct(o)})});break;case q.ENQUEUE:if(J(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case q.CLOSE:if(J(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#a(a,e);break;case q.ERROR:J(a,"error should have stream controller"),a.controller.error(ct(t.reason)),this.#a(a,e);break;case q.CANCEL_COMPLETE:t.success?a.cancelCall.resolve():a.cancelCall.reject(ct(t.reason)),this.#a(a,e);break;case q.CANCEL:if(!r)break;new Promise(function(o){o(r.onCancel?.(ct(t.reason)))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:q.CANCEL_COMPLETE,streamId:e,success:!0})},function(o){n.postMessage({sourceName:s,targetName:i,stream:q.CANCEL_COMPLETE,streamId:e,reason:ct(o)})}),r.sinkCapability.reject(ct(t.reason)),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#a(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#t?.abort(),this.#t=null}}class tn{#t;#e;constructor({parsedData:t,rawData:e}){this.#t=t,this.#e=e}getRaw(){return this.#e}get(t){return this.#t.get(t)??null}getAll(){return qe(this.#t)}has(t){return this.#t.has(t)}}const Ut=Symbol("INTERNAL");class en{#t=!1;#e=!1;#s=!1;#n=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&dt.DISPLAY),this.#e=!!(t&dt.PRINT),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#s)return this.#n;if(!this.#n)return!1;const{print:t,view:e}=this.usage;return this.#t?e?.viewState!=="OFF":this.#e?t?.printState!=="OFF":!0}_setVisible(t,e,s=!1){t!==Ut&&H("Internal method `_setVisible` called."),this.#s=s,this.#n=e}}class sn{#t=null;#e=new Map;#s=null;#n=null;constructor(t,e=dt.DISPLAY){if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,this.#n=t.order;for(const s of t.groups)this.#e.set(s.id,new en(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(Ut,!1);for(const s of t.on)this.#e.get(s)._setVisible(Ut,!0);for(const s of t.off)this.#e.get(s)._setVisible(Ut,!1);this.#s=this.getHash()}}#a(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const n=t[i];let a;if(Array.isArray(n))a=this.#a(n);else if(this.#e.has(n))a=this.#e.get(n).visible;else return F(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!a)return!1;break;case"Or":if(a)return!0;break;case"Not":return!a;default:return!0}}return s==="And"}isVisible(t){if(this.#e.size===0)return!0;if(!t)return Ee("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(F(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return this.#a(t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!this.#e.has(e))return F(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!this.#e.has(e))return F(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!this.#e.has(e))return F(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!this.#e.has(e))return F(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return F(`Unknown optional content policy ${t.policy}.`),!0}return F(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){F(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const n of i.rbGroups)for(const a of n)a!==t&&this.#e.get(a)?._setVisible(Ut,!1,!0);i._setVisible(Ut,!!e,!0),this.#t=null}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const n=this.#e.get(i);if(n)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}this.#t=null}get hasInitialVisibility(){return this.#s===null||this.getHash()===this.#s}getOrder(){return this.#e.size?this.#n?this.#n.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?qe(this.#e):null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Ds;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}}class nn{constructor(t,{disableRange:e=!1,disableStream:s=!1}){J(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=r,n?.length>0){const o=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(o)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((o,l)=>{this._onReceiveData({begin:o,chunk:l})}),t.addProgressListener((o,l)=>{this._onProgress({loaded:o,total:l})}),t.addProgressiveReadListener(o=>{this._onReceiveData({chunk:o})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});J(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){t.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){J(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new an(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new rn(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class an{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=Ke(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const n of this._queuedChunks)this._loaded+=n.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class rn{constructor(t,e,s){this._stream=t,this._begin=e,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function on(c){let t=!0,e=s("filename\\*","i").exec(c);if(e){e=e[1];let h=r(e);return h=unescape(h),h=o(h),h=l(h),n(h)}if(e=a(c),e){const h=l(e);return n(h)}if(e=s("filename","i").exec(c),e){e=e[1];let h=r(e);return h=l(h),n(h)}function s(h,d){return new RegExp("(?:^|;)\\s*"+h+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',d)}function i(h,d){if(h){if(!/^[\x00-\xFF]+$/.test(d))return d;try{const u=new TextDecoder(h,{fatal:!0}),f=xe(d);d=u.decode(f),t=!1}catch{}}return d}function n(h){return t&&/[\x80-\xff]/.test(h)&&(h=i("utf-8",h),t&&(h=i("iso-8859-1",h))),h}function a(h){const d=[];let u;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(u=f.exec(h))!==null;){let[,g,b,m]=u;if(g=parseInt(g,10),g in d){if(g===0)break;continue}d[g]=[b,m]}const p=[];for(let g=0;g<d.length&&g in d;++g){let[b,m]=d[g];m=r(m),b&&(m=unescape(m),g===0&&(m=o(m))),p.push(m)}return p.join("")}function r(h){if(h.startsWith('"')){const d=h.slice(1).split('\\"');for(let u=0;u<d.length;++u){const f=d[u].indexOf('"');f!==-1&&(d[u]=d[u].slice(0,f),d.length=u+1),d[u]=d[u].replaceAll(/\\(.)/g,"$1")}h=d.join('"')}return h}function o(h){const d=h.indexOf("'");if(d===-1)return h;const u=h.slice(0,d),p=h.slice(d+1).replace(/^[^']*'/,"");return i(u,p)}function l(h){return!h.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(h)?h:h.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(d,u,f,p){if(f==="q"||f==="Q")return p=p.replaceAll("_"," "),p=p.replaceAll(/=([0-9a-fA-F]{2})/g,function(g,b){return String.fromCharCode(parseInt(b,16))}),i(u,p);try{p=atob(p)}catch{}return i(u,p)})}return""}function is(c,t){const e=new Headers;if(!c||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function ns({responseHeaders:c,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(c.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||c.get("Accept-Ranges")!=="bytes"||(c.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function as(c){const t=c.get("Content-Disposition");if(t){let e=on(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(Ke(e))return e}return null}function ke(c,t){return c===404||c===0&&t.startsWith("file:")?new Ot('Missing PDF "'+t+'".'):new Se(`Unexpected server response (${c}) while retrieving PDF "${t}".`,c)}function $s(c){return c===200||c===206}function Ws(c,t,e){return{method:"GET",headers:c,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function Vs(c){return c instanceof Uint8Array?c.buffer:c instanceof ArrayBuffer?c:(F(`getArrayBuffer - unexpected data format: ${c}`),new Uint8Array(c).buffer)}class Cs{constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=is(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return J(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new ln(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new hn(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class ln{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const s=new Headers(t.headers),i=e.url;fetch(i,Ws(s,this._withCredentials,this._abortController)).then(n=>{if(!$s(n.status))throw ke(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const a=n.headers,{allowRangeRequests:r,suggestedLength:o}=ns({responseHeaders:a,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=o||this._contentLength,this._filename=as(a),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Nt("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Vs(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class hn{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const a=i.url;fetch(a,Ws(n,this._withCredentials,this._abortController)).then(r=>{if(!$s(r.status))throw ke(r.status,a);this._readCapability.resolve(),this._reader=r.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Vs(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const De=200,Oe=206;function cn(c){const t=c.response;return typeof t!="string"?t:xe(t).buffer}class dn{constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=is(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,s){const i={begin:t,end:e};for(const n in s)i[n]=s[n];return this.request(i)}requestFull(t){return this.request(t)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,a]of this.headers)e.setRequestHeader(n,a);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=Oe):i.expectedStatus=De,e.responseType="arraybuffer",t.onError&&(e.onerror=function(n){t.onError(e.status)}),e.onreadystatechange=this.onStateChange.bind(this,s),e.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=t.onHeadersReceived,i.onDone=t.onDone,i.onError=t.onError,i.onProgress=t.onProgress,e.send(null),s}onProgress(t,e){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),i.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],i.status===0&&this.isHttp){s.onError?.(i.status);return}const n=i.status||De;if(!(n===De&&s.expectedStatus===Oe)&&n!==s.expectedStatus){s.onError?.(i.status);return}const r=cn(i);if(n===Oe){const o=i.getResponseHeader("Content-Range"),l=/bytes (\d+)-(\d+)\/(\d+)/.exec(o);s.onDone({begin:parseInt(l[1],10),chunk:r})}else r?s.onDone({begin:0,chunk:r}):s.onError?.(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class un{constructor(t){this._source=t,this._manager=new dn(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return J(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new fn(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new pn(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class fn{constructor(t,e){this._manager=t;const s={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(s),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),s=new Headers(e.getAllResponseHeaders().trim().split(/[\r\n]+/).map(a=>{const[r,...o]=a.split(": ");return[r,o.join(": ")]})),{allowRangeRequests:i,suggestedLength:n}=ns({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=as(s),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=ke(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class pn{constructor(t,e,s){this._manager=t;const i={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(e,s,i),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=ke(t,this._url);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const gn=/^[a-z][a-z0-9\-+.]+:/i;function mn(c){if(gn.test(c))return new URL(c);const t=Rt.get("url");return new URL(t.pathToFileURL(c))}function qs(c,t,e){return c.protocol==="http:"?Rt.get("http").request(c,{headers:t},e):Rt.get("https").request(c,{headers:t},e)}class bn{constructor(t){this.source=t,this.url=mn(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=is(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return J(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new yn(this):new An(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=this.isFsUrl?new vn(this,t,e):new _n(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Xs{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new Nt("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Ys{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const e=t.source;this._isStreamingSupported=!e.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}}class An extends Xs{constructor(t){super(t);const e=Object.fromEntries(t.headers),s=i=>{if(i.statusCode===404){const o=new Ot(`Missing PDF "${this._url}".`);this._storedError=o,this._headersCapability.reject(o);return}this._headersCapability.resolve(),this._setReadableStream(i);const n=new Headers(this._readableStream.headers),{allowRangeRequests:a,suggestedLength:r}=ns({responseHeaders:n,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=a,this._contentLength=r||this._contentLength,this._filename=as(n)};this._request=qs(this._url,e,s),this._request.on("error",i=>{this._storedError=i,this._headersCapability.reject(i)}),this._request.end()}}class _n extends Ys{constructor(t,e,s){super(t);const i=Object.fromEntries(t.headers);i.Range=`bytes=${e}-${s-1}`;const n=a=>{if(a.statusCode===404){const r=new Ot(`Missing PDF "${this._url}".`);this._storedError=r;return}this._setReadableStream(a)};this._request=qs(this._url,i,n),this._request.on("error",a=>{this._storedError=a}),this._request.end()}}class yn extends Xs{constructor(t){super(t);const e=Rt.get("fs");e.promises.lstat(this._url).then(s=>{this._contentLength=s.size,this._setReadableStream(e.createReadStream(this._url)),this._headersCapability.resolve()},s=>{s.code==="ENOENT"&&(s=new Ot(`Missing PDF "${this._url}".`)),this._storedError=s,this._headersCapability.reject(s)})}}class vn extends Ys{constructor(t,e,s){super(t);const i=Rt.get("fs");this._setReadableStream(i.createReadStream(this._url,{start:e,end:s-1}))}}const wn=1e5,lt=30,En=.8;class nt{#t=Promise.withResolvers();#e=null;#s=!1;#n=!!globalThis.FontInspector?.enabled;#a=null;#i=null;#l=0;#h=0;#c=null;#o=null;#d=0;#r=0;#u=Object.create(null);#p=[];#f=null;#b=[];#m=new WeakMap;#g=null;static#A=new Map;static#y=new Map;static#C=new WeakMap;static#E=null;static#S=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#f=t;else if(typeof t=="object")this.#f=new ReadableStream({start(o){o.enqueue(t),o.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#o=e,this.#r=s.scale*(globalThis.devicePixelRatio||1),this.#d=s.rotation,this.#i={div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:a,pageY:r}=s.rawDims;this.#g=[1,0,0,-1,-a,r+n],this.#h=i,this.#l=n,nt.#R(),Ft(e,s),this.#t.promise.finally(()=>{nt.#S.delete(this),this.#i=null,this.#u=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=rt.platform;return D(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{this.#c.read().then(({value:e,done:s})=>{if(s){this.#t.resolve();return}this.#a??=e.lang,Object.assign(this.#u,e.styles),this.#D(e.items),t()},this.#t.reject)};return this.#c=this.#f.getReader(),nt.#S.add(this),t(),this.#t.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#d&&(e?.(),this.#d=i,Ft(this.#o,{rotation:i})),s!==this.#r){e?.(),this.#r=s;const n={div:null,properties:null,ctx:nt.#x(this.#a)};for(const a of this.#b)n.properties=this.#m.get(a),n.div=a,this.#v(n)}}cancel(){const t=new Nt("TextLayer task cancelled.");this.#c?.cancel(t).catch(()=>{}),this.#c=null,this.#t.reject(t)}get textDivs(){return this.#b}get textContentItemsStr(){return this.#p}#D(t){if(this.#s)return;this.#i.ctx??=nt.#x(this.#a);const e=this.#b,s=this.#p;for(const i of t){if(e.length>wn){F("Ignoring additional textDivs for performance reasons."),this.#s=!0;return}if(i.str===void 0){if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){const n=this.#e;this.#e=document.createElement("span"),this.#e.classList.add("markedContent"),i.id!==null&&this.#e.setAttribute("id",`${i.id}`),n.append(this.#e)}else i.type==="endMarkedContent"&&(this.#e=this.#e.parentNode);continue}s.push(i.str),this.#T(i)}}#T(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#b.push(e);const i=S.transform(this.#g,t.transform);let n=Math.atan2(i[1],i[0]);const a=this.#u[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#n&&a.fontSubstitution||a.fontFamily;r=nt.fontFamilyMap.get(r)||r;const o=Math.hypot(i[2],i[3]),l=o*nt.#L(r,this.#a);let h,d;n===0?(h=i[4],d=i[5]-l):(h=i[4]+l*Math.sin(n),d=i[5]-l*Math.cos(n));const u="calc(var(--scale-factor)*",f=e.style;this.#e===this.#o?(f.left=`${(100*h/this.#h).toFixed(2)}%`,f.top=`${(100*d/this.#l).toFixed(2)}%`):(f.left=`${u}${h.toFixed(2)}px)`,f.top=`${u}${d.toFixed(2)}px)`),f.fontSize=`${u}${(nt.#E*o).toFixed(2)}px)`,f.fontFamily=r,s.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#n&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const g=Math.abs(t.transform[0]),b=Math.abs(t.transform[3]);g!==b&&Math.max(g,b)/Math.min(g,b)>1.5&&(p=!0)}if(p&&(s.canvasWidth=a.vertical?t.height:t.width),this.#m.set(e,s),this.#i.div=e,this.#i.properties=s,this.#v(this.#i),s.hasText&&this.#e.append(e),s.hasEOL){const g=document.createElement("br");g.setAttribute("role","presentation"),this.#e.append(g)}}#v(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;let a="";if(nt.#E>1&&(a=`scale(${1/nt.#E})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:r}=n,{canvasWidth:o,fontSize:l}=s;nt.#k(i,l*this.#r,r);const{width:h}=i.measureText(e.textContent);h>0&&(a=`scaleX(${o*this.#r/h}) ${a}`)}s.angle!==0&&(a=`rotate(${s.angle}deg) ${a}`),a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#S.size>0)){this.#A.clear();for(const{canvas:t}of this.#y.values())t.remove();this.#y.clear()}}static#x(t=null){let e=this.#y.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#y.set(t,e),this.#C.set(e,{size:0,family:""})}return e}static#k(t,e,s){const i=this.#C.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#R(){if(this.#E!==null)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.#E=t.getBoundingClientRect().height,t.remove()}static#L(t,e){const s=this.#A.get(t);if(s)return s;const i=this.#x(e);i.canvas.width=i.canvas.height=lt,this.#k(i,lt,t);const n=i.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const h=a/(a+r);return this.#A.set(t,h),i.canvas.width=i.canvas.height=0,h}i.strokeStyle="red",i.clearRect(0,0,lt,lt),i.strokeText("g",0,0);let o=i.getImageData(0,0,lt,lt).data;r=0;for(let h=o.length-1-3;h>=0;h-=4)if(o[h]>0){r=Math.ceil(h/4/lt);break}i.clearRect(0,0,lt,lt),i.strokeText("A",0,lt),o=i.getImageData(0,0,lt,lt).data,a=0;for(let h=0,d=o.length;h<d;h+=4)if(o[h]>0){a=lt-Math.floor(h/4/lt);break}i.canvas.width=i.canvas.height=0;const l=a?a/(a+r):En;return this.#A.set(t,l),l}}class ae{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){if(!n)return;let a=null;const r=n.name;if(r==="#text")a=n.value;else if(ae.shouldBuildText(r))n?.attributes?.textContent?a=n.attributes.textContent:n.value&&(a=n.value);else return;if(a!==null&&e.push({str:a}),!!n.children)for(const o of n.children)i(o)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const Sn=65536,xn=100,Cn=5e3,Tn=it?Hi:Di,kn=it?Bi:Bs,Rn=it?Ni:Oi,Mn=it?zi:js;function Pn(c={}){typeof c=="string"||c instanceof URL?c={url:c}:(c instanceof ArrayBuffer||ArrayBuffer.isView(c))&&(c={data:c});const t=new rs,{docId:e}=t,s=c.url?Ln(c.url):null,i=c.data?In(c.data):null,n=c.httpHeaders||null,a=c.withCredentials===!0,r=c.password??null,o=c.range instanceof Ks?c.range:null,l=Number.isInteger(c.rangeChunkSize)&&c.rangeChunkSize>0?c.rangeChunkSize:Sn;let h=c.worker instanceof $t?c.worker:null;const d=c.verbosity,u=typeof c.docBaseUrl=="string"&&!Te(c.docBaseUrl)?c.docBaseUrl:null,f=typeof c.cMapUrl=="string"?c.cMapUrl:null,p=c.cMapPacked!==!1,g=c.CMapReaderFactory||kn,b=typeof c.standardFontDataUrl=="string"?c.standardFontDataUrl:null,m=c.StandardFontDataFactory||Mn,A=c.stopAtErrors!==!0,y=Number.isInteger(c.maxImageSize)&&c.maxImageSize>-1?c.maxImageSize:-1,_=c.isEvalSupported!==!1,v=typeof c.isOffscreenCanvasSupported=="boolean"?c.isOffscreenCanvasSupported:!it,w=typeof c.isChrome=="boolean"?c.isChrome:!rt.platform.isFirefox&&typeof window<"u"&&!!window?.chrome,E=Number.isInteger(c.canvasMaxAreaInBytes)?c.canvasMaxAreaInBytes:-1,C=typeof c.disableFontFace=="boolean"?c.disableFontFace:it,x=c.fontExtraProperties===!0,O=c.enableXfa===!0,P=c.ownerDocument||globalThis.document,B=c.disableRange===!0,z=c.disableStream===!0,X=c.disableAutoFetch===!0,N=c.pdfBug===!0,U=c.CanvasFactory||Tn,T=c.FilterFactory||Rn,L=c.enableHWA===!0,Ct=o?o.length:c.length??NaN,yt=typeof c.useSystemFonts=="boolean"?c.useSystemFonts:!it&&!C,ut=typeof c.useWorkerFetch=="boolean"?c.useWorkerFetch:g===Bs&&m===js&&f&&b&&te(f,document.baseURI)&&te(b,document.baseURI);c.canvasFactory&&ps("`canvasFactory`-instance option, please use `CanvasFactory` instead."),c.filterFactory&&ps("`filterFactory`-instance option, please use `FilterFactory` instead.");const tt=null;ui(d);const Y={canvasFactory:new U({ownerDocument:P,enableHWA:L}),filterFactory:new T({docId:e,ownerDocument:P}),cMapReaderFactory:ut?null:new g({baseUrl:f,isCompressed:p}),standardFontDataFactory:ut?null:new m({baseUrl:b})};if(!h){const ot={verbosity:d,port:ne.workerPort};h=ot.port?$t.fromPort(ot):new $t(ot),t._worker=h}const Bt={docId:e,apiVersion:"4.8.69",data:i,password:r,disableAutoFetch:X,rangeChunkSize:l,length:Ct,docBaseUrl:u,enableXfa:O,evaluatorOptions:{maxImageSize:y,disableFontFace:C,ignoreErrors:A,isEvalSupported:_,isOffscreenCanvasSupported:v,isChrome:w,canvasMaxAreaInBytes:E,fontExtraProperties:x,useSystemFonts:yt,cMapUrl:ut?f:null,standardFontDataUrl:ut?b:null}},Xt={disableFontFace:C,fontExtraProperties:x,ownerDocument:P,pdfBug:N,styleElement:tt,loadingParams:{disableAutoFetch:X,enableXfa:O}};return h.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(h.destroyed)throw new Error("Worker was destroyed");const ot=h.messageHandler.sendWithPromise("GetDocRequest",Bt,i?[i.buffer]:null);let j;if(o)j=new nn(o,{disableRange:B,disableStream:z});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let Yt;it?Yt=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&te(s)?Cs:bn:Yt=te(s)?Cs:un,j=new Yt({url:s,length:Ct,httpHeaders:n,withCredentials:a,rangeChunkSize:l,disableRange:B,disableStream:z})}return ot.then(Yt=>{if(t.destroyed)throw new Error("Loading aborted");if(h.destroyed)throw new Error("Worker was destroyed");const Re=new ee(e,Yt,h.port),oi=new Nn(Re,t,j,Xt,Y);t._transport=oi,Re.send("Ready",null)})}).catch(t._capability.reject),t}function Ln(c){if(c instanceof URL)return c.href;try{return new URL(c,window.location).href}catch{if(it&&typeof c=="string")return c}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function In(c){if(it&&typeof Buffer<"u"&&c instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(c instanceof Uint8Array&&c.byteLength===c.buffer.byteLength)return c;if(typeof c=="string")return xe(c);if(c instanceof ArrayBuffer||ArrayBuffer.isView(c)||typeof c=="object"&&!isNaN(c?.length))return new Uint8Array(c);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function Ts(c){return typeof c=="object"&&Number.isInteger(c?.num)&&c.num>=0&&Number.isInteger(c?.gen)&&c.gen>=0}class rs{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${rs.#t++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class Ks{constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){H("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Fn{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return D(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()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class Dn{#t=null;#e=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new fs:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new Qs,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new re({viewBox:this.view,scale:t,rotation:e,offsetX:s,offsetY:i,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 D(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=Tt.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:l=null,printAnnotationStorage:h=null,isEditing:d=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(s,i,h,d),{renderingIntent:f,cacheKey:p}=u;this.#e=!1,this.#n(),r||=this._transport.getOptionalContentConfig(f);let g=this._intentStates.get(p);g||(g=Object.create(null),this._intentStates.set(p,g)),g.streamReaderCancelTimeout&&(clearTimeout(g.streamReaderCancelTimeout),g.streamReaderCancelTimeout=null);const b=!!(f&dt.PRINT);g.displayReadyCapability||(g.displayReadyCapability=Promise.withResolvers(),g.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(u));const m=_=>{g.renderTasks.delete(A),(this._maybeCleanupAfterRender||b)&&(this.#e=!0),this.#s(!b),_?(A.capability.reject(_),this._abortOperatorList({intentState:g,reason:_ instanceof Error?_:new Error(_)})):A.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},A=new jt({callback:m,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:o,operatorList:g.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:l});(g.renderTasks||=new Set).add(A);const y=A.task;return Promise.all([g.displayReadyCapability.promise,r]).then(([_,v])=>{if(this.destroyed){m();return}if(this._stats?.time("Rendering"),!(v.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:_,optionalContentConfig:v}),A.operatorListChanged()}).catch(m),y}getOperatorList({intent:t="display",annotationMode:e=Tt.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(o))}const a=this._transport.getRenderingIntent(t,e,s,i,!0);let r=this._intentStates.get(a.cacheKey);r||(r=Object.create(null),this._intentStates.set(a.cacheKey,r));let o;return r.opListReadCapability||(o=Object.create(null),o.operatorListChanged=n,r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(o),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(a)),r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:e===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(s=>ae.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){a.read().then(function({value:o,done:l}){if(l){s(r);return}r.lang??=o.lang,Object.assign(r.styles,o.styles),r.items.push(...o.items),n()},i)}const a=e.getReader(),r={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#e=!1,this.#n(),Promise.all(t)}cleanup(t=!1){this.#e=!0;const e=this.#s(!1);return t&&e&&(this._stats&&=new fs),e}#s(t=!1){if(this.#n(),!this.#e||this.destroyed)return!1;if(t)return this.#t=setTimeout(()=>{this.#t=null,this.#s(!1)},Cn),!1;for(const{renderTasks:e,operatorList:s}of this._intentStates.values())if(e.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#n(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&this.#s(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:a}=s,o=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},a).getReader(),l=this._intentStates.get(e);l.streamReader=o;const h=()=>{o.read().then(({value:d,done:u})=>{if(u){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(d,l),h())},d=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const u of l.renderTasks)u.operatorListChanged();this.#s(!0)}if(l.displayReadyCapability)l.displayReadyCapability.reject(d);else if(l.opListReadCapability)l.opListReadCapability.reject(d);else throw d}})};h()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof Ye){let i=xn;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}}if(t.streamReader.cancel(new Nt(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[i,n]of this._intentStates)if(n===t){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}class On{#t=new Map;#e=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#e.then(()=>{for(const[i]of this.#t)i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted){F("LoopbackPort - cannot use an `aborted` signal.");return}const a=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",a),n.addEventListener("abort",a)}this.#t.set(e,i)}removeEventListener(t,e){this.#t.get(e)?.(),this.#t.delete(e)}terminate(){for(const[,t]of this.#t)t?.();this.#t.clear()}}var ye,Lt,It,Wt,be,Vt,Ae;const G=class G{constructor({name:t=null,port:e=null,verbosity:s=fi()}={}){zt(this,Wt);if(this.name=t,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(mt(G,It)?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(mt(G,It)||Kt(G,It,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return it?Promise.all([Rt.promise,this._readyCapability.promise]):this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new ee("main","worker",t),this._messageHandler.on("ready",function(){}),he(this,Wt,be).call(this)}_initialize(){if(mt(G,Lt)||mt(G,Vt,Ae)){this._setupFakeWorker();return}let{workerSrc:t}=G;try{G._isSameOrigin(window.location.href,t)||(t=G._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new ee("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",()=>{this._webWorker||i()},{signal:n.signal}),s.on("test",r=>{if(n.abort(),this.destroyed||!r){i();return}this._messageHandler=s,this._port=e,this._webWorker=e,he(this,Wt,be).call(this)}),s.on("ready",r=>{if(n.abort(),this.destroyed){i();return}try{a()}catch{this._setupFakeWorker()}});const a=()=>{const r=new Uint8Array;s.send("test",r,[r.buffer])};a();return}catch{Ee("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){mt(G,Lt)||(F("Setting up fake worker."),Kt(G,Lt,!0)),G._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new On;this._port=e;const s=`fake${ds(G,ye)._++}`,i=new ee(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new ee(s,s+"_worker",e),he(this,Wt,be).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),mt(G,It)?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=mt(this,It)?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new G(t)}static get workerSrc(){if(ne.workerSrc)return ne.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return D(this,"_setupFakeWorkerGlobal",(async()=>mt(this,Vt,Ae)?mt(this,Vt,Ae):(await import(this.workerSrc)).WorkerMessageHandler)())}};ye=new WeakMap,Lt=new WeakMap,It=new WeakMap,Wt=new WeakSet,be=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Vt=new WeakSet,Ae=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},zt(G,Vt),zt(G,ye,0),zt(G,Lt,!1),zt(G,It),it&&(Kt(G,Lt,!0),ne.workerSrc||="./pdf.worker.mjs"),G._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},G._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let $t=G;class Nn{#t=new Map;#e=new Map;#s=new Map;#n=new Map;#a=null;constructor(t,e,s,i,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new Qs,this.fontLoader=new Ii({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#i(t,e=null){const s=this.#t.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return this.#t.set(t,i),i}get annotationStorage(){return D(this,"annotationStorage",new ts)}getRenderingIntent(t,e=Tt.ENABLE,s=null,i=!1,n=!1){let a=dt.DISPLAY,r=Ue;switch(t){case"any":a=dt.ANY;break;case"display":break;case"print":a=dt.PRINT;break;default:F(`getRenderingIntent - invalid intent: ${t}`)}const o=a&dt.PRINT&&s instanceof Os?s:this.annotationStorage;switch(e){case Tt.DISABLE:a+=dt.ANNOTATIONS_DISABLE;break;case Tt.ENABLE:break;case Tt.ENABLE_FORMS:a+=dt.ANNOTATIONS_FORMS;break;case Tt.ENABLE_STORAGE:a+=dt.ANNOTATIONS_STORAGE,r=o.serializable;break;default:F(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(a+=dt.IS_EDITING),n&&(a+=dt.OPLIST);const{ids:l,hash:h}=o.modifiedIds,d=[a,r.hash,h];return{renderingIntent:a,cacheKey:d.join("_"),annotationStorageSerializable:r,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#a?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#e.values())t.push(s._destroy());this.#e.clear(),this.#s.clear(),this.#n.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),nt.cleanup(),this._networkStream?.cancelAllRequests(new Nt("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(s,i)=>{J(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=n=>{this._lastProgress={loaded:n.loaded,total:n.total}},i.onPull=()=>{this._fullReader.read().then(function({value:n,done:a}){if(a){i.close();return}J(n instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(n),1,[n])}).catch(n=>{i.error(n)})},i.onCancel=n=>{this._fullReader.cancel(n),i.ready.catch(a=>{if(!this.destroyed)throw a})}}),t.on("ReaderHeadersReady",async s=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:a}=this._fullReader;return(!i||!n)&&(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=r=>{e.onProgress?.({loaded:r.loaded,total:r.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:a}}),t.on("GetRangeReader",(s,i)=>{J(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const n=this._networkStream.getRangeReader(s.begin,s.end);if(!n){i.close();return}i.onPull=()=>{n.read().then(function({value:a,done:r}){if(r){i.close();return}J(a instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(a),1,[a])}).catch(a=>{i.error(a)})},i.onCancel=a=>{n.cancel(a),i.ready.catch(r=>{if(!this.destroyed)throw r})}}),t.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new Fn(s,this))}),t.on("DocException",function(s){let i;switch(s.name){case"PasswordException":i=new He(s.message,s.code);break;case"InvalidPDFException":i=new Ls(s.message);break;case"MissingPDFException":i=new Ot(s.message);break;case"UnexpectedResponseException":i=new Se(s.message,s.status);break;case"UnknownErrorException":i=new Be(s.message,s.details);break;default:H("DocException - expected a valid Error.")}e._capability.reject(i)}),t.on("PasswordRequest",s=>{if(this.#a=Promise.withResolvers(),e.onPassword){const i=n=>{n instanceof Error?this.#a.reject(n):this.#a.resolve({password:n})};try{e.onPassword(i,s.code)}catch(n){this.#a.reject(n)}}else this.#a.reject(new He(s.message,s.code));return this.#a.promise}),t.on("DataLoaded",s=>{e.onProgress?.({loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;this.#e.get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:a,fontExtraProperties:r,pdfBug:o}=this._params;if("error"in n){const u=n.error;F(`Error during font loading: ${u}`),this.commonObjs.resolve(s,u);break}const l=o&&globalThis.FontInspector?.enabled?(u,f)=>globalThis.FontInspector.fontAdded(u,f):null,h=new Fi(n,{disableFontFace:a,inspectFont:l});this.fontLoader.bind(h).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!r&&h.data&&(h.data=null),this.commonObjs.resolve(s,h)});break;case"CopyLocalImage":const{imageRef:d}=n;J(d,"The imageRef must be defined.");for(const u of this.#e.values())for(const[,f]of u.objs)if(f?.ref===d)return f.dataLen?(this.commonObjs.resolve(s,structuredClone(f)),f.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(s,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([s,i,n,a])=>{if(this.destroyed)return;const r=this.#e.get(i);if(!r.objs.has(s)){if(r._intentStates.size===0){a?.bitmap?.close();return}switch(n){case"Image":r.objs.resolve(s,a),a?.dataLen>li&&(r._maybeCleanupAfterRender=!0);break;case"Pattern":r.objs.resolve(s,a);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{this.destroyed||e.onProgress?.({loaded:s.loaded,total:s.total})}),t.on("FetchBuiltInCMap",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),t.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&F("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.#s.get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(n=>{if(this.destroyed)throw new Error("Transport destroyed");n.refStr&&this.#n.set(n.refStr,t);const a=new Dn(e,n,this,this._params.pdfBug);return this.#e.set(e,a),a});return this.#s.set(e,i),i}getPageIndex(t){return Ts(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#i("GetFieldObjects")}hasJSActions(){return this.#i("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?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)}getDocJSActions(){return this.#i("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#i("GetOptionalContentConfig").then(e=>new sn(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#t.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(i=>({info:i[0],metadata:i[1]?new tn(i[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#t.set(t,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const e of this.#e.values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),nt.cleanup()}}cachedPageNumber(t){if(!Ts(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#n.get(e)??null}}const pe=Symbol("INITIAL_DATA");class Qs{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:pe}}get(t,e=null){if(e){const i=this.#e(t);return i.promise.then(()=>e(i.data)),null}const s=this.#t[t];if(!s||s.data===pe)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#t[t];return!!e&&e.data!==pe}resolve(t,e=null){const s=this.#e(t);s.data=e,s.resolve()}clear(){for(const t in this.#t){const{data:e}=this.#t[t];e?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(const t in this.#t){const{data:e}=this.#t[t];e!==pe&&(yield[t,e])}}}class Hn{#t=null;constructor(t){this.#t=t,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(t=0){this.#t.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#t.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#t;return t.form||t.canvas&&e?.size>0}}class jt{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:u=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=d,this.pageColors=u,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=h===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Hn(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.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(jt.#e.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.");jt.#e.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:n,background:a}=this.params;this.gfx=new Gt(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#t&&(window.cancelAnimationFrame(this.#t),this.#t=null),jt.#e.delete(this._canvas),this.callback(t||new Ye(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#t=window.requestAnimationFrame(()=>{this.#t=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),jt.#e.delete(this._canvas),this.callback())))}}const Bn="4.8.69",zn="3634dab10";function ks(c){return Math.floor(Math.max(0,Math.min(1,c))*255).toString(16).padStart(2,"0")}function Zt(c){return Math.max(0,Math.min(255,255*c))}class Rs{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=Zt(t),[t,t,t]}static G_HTML([t]){const e=ks(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(Zt)}static RGB_HTML(t){return`#${t.map(ks).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[Zt(1-Math.min(1,t+i)),Zt(1-Math.min(1,s+i)),Zt(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,a=1-s,r=Math.min(i,n,a);return["CMYK",i,n,a,r]}}class Un{create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){H("Abstract method `_createSVG` called.")}}class os extends Un{_createSVG(t){return document.createElementNS(Et,t)}}class Js{static setupStorage(t,e,s,i,n){const a=i.getValue(e,{value:null});switch(s.name){case"textarea":if(a.value!==null&&(t.textContent=a.value),n==="print")break;t.addEventListener("input",r=>{i.setValue(e,{value:r.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(a.value===s.attributes.xfaOn?t.setAttribute("checked",!0):a.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",r=>{i.setValue(e,{value:r.target.checked?r.target.getAttribute("xfaOn"):r.target.getAttribute("xfaOff")})})}else{if(a.value!==null&&t.setAttribute("value",a.value),n==="print")break;t.addEventListener("input",r=>{i.setValue(e,{value:r.target.value})})}break;case"select":if(a.value!==null){t.setAttribute("value",a.value);for(const r of s.children)r.attributes.value===a.value?r.attributes.selected=!0:r.attributes.hasOwnProperty("selected")&&delete r.attributes.selected}t.addEventListener("input",r=>{const o=r.target.options,l=o.selectedIndex===-1?"":o[o.selectedIndex].value;i.setValue(e,{value:l})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${i}`);for(const[o,l]of Object.entries(a))if(l!=null)switch(o){case"class":l.length&&t.setAttribute(o,l.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",l);break;case"style":Object.assign(t.style,l);break;case"textContent":t.textContent=l;break;default:(!r||o!=="href"&&o!=="newWindow")&&t.setAttribute(o,l)}r&&n.addLinkAttributes(t,a.href,a.newWindow),s&&a.dataId&&this.setupStorage(t,a.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",a=document.createElement(i.name);i.attributes&&this.setAttributes({html:a,element:i,intent:n,linkService:s});const r=n!=="richText",o=t.div;if(o.append(a),t.viewport){const d=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=d}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const d=document.createTextNode(i.value);a.append(d),r&&ae.shouldBuildText(i.name)&&l.push(d)}return{textDivs:l}}const h=[[i,-1,a]];for(;h.length>0;){const[d,u,f]=h.at(-1);if(u+1===d.children.length){h.pop();continue}const p=d.children[++h.at(-1)[1]];if(p===null)continue;const{name:g}=p;if(g==="#text"){const m=document.createTextNode(p.value);l.push(m),f.append(m);continue}const b=p?.attributes?.xmlns?document.createElementNS(p.attributes.xmlns,g):document.createElement(g);if(f.append(b),p.attributes&&this.setAttributes({html:b,element:p,storage:e,intent:n,linkService:s}),p.children?.length>0)h.push([p,-1,b]);else if(p.value){const m=document.createTextNode(p.value);r&&ae.shouldBuildText(g)&&l.push(m),b.append(m)}}for(const d of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))d.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 le=1e3,jn=9,Dt=new WeakSet;function xt(c){return{width:c[2]-c[0],height:c[3]-c[1]}}class Gn{static create(t){switch(t.data.annotationType){case K.LINK:return new Zs(t);case K.TEXT:return new $n(t);case K.WIDGET:switch(t.data.fieldType){case"Tx":return new Wn(t);case"Btn":return t.data.radioButton?new ti(t):t.data.checkBox?new qn(t):new Xn(t);case"Ch":return new Yn(t);case"Sig":return new Vn(t)}return new Ht(t);case K.POPUP:return new We(t);case K.FREETEXT:return new ei(t);case K.LINE:return new Qn(t);case K.SQUARE:return new Jn(t);case K.CIRCLE:return new Zn(t);case K.POLYLINE:return new si(t);case K.CARET:return new ea(t);case K.INK:return new ls(t);case K.POLYGON:return new ta(t);case K.HIGHLIGHT:return new ii(t);case K.UNDERLINE:return new sa(t);case K.SQUIGGLY:return new ia(t);case K.STRIKEOUT:return new na(t);case K.STAMP:return new ni(t);case K.FILEATTACHMENT:return new aa(t);default:return new V(t)}}}class V{#t=null;#e=!1;#s=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!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.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t?.str||e?.str||s?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return V._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#t||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#n(e),this.#s?.popup.updateEdited(t)}resetEdited(){this.#t&&(this.#n(this.#t.rect),this.#s?.popup.resetEdited(),this.#t=null)}#n(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;s?.splice(0,4,...t);const{width:l,height:h}=xt(t);e.left=`${100*(t[0]-r)/n}%`,e.top=`${100*(a-t[3]+o)/a}%`,i===0?(e.width=`${100*l/n}%`,e.height=`${100*h/a}%`):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Ht||(n.tabIndex=le);const{style:a}=n;if(a.zIndex=this.parent.zIndex++,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof We){const{rotation:g}=e;return!e.hasOwnCanvas&&g!==0&&this.setRotation(g,n),n}const{width:r,height:o}=xt(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const g=e.borderStyle.horizontalCornerRadius,b=e.borderStyle.verticalCornerRadius;if(g>0||b>0){const A=`calc(${g}px * var(--scale-factor)) / calc(${b}px * var(--scale-factor))`;a.borderRadius=A}else if(this instanceof ti){const A=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=A}switch(e.borderStyle.style){case Qt.SOLID:a.borderStyle="solid";break;case Qt.DASHED:a.borderStyle="dashed";break;case Qt.BEVELED:F("Unimplemented border style: beveled");break;case Qt.INSET:F("Unimplemented border style: inset");break;case Qt.UNDERLINE:a.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,a.borderColor=S.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):a.borderWidth=0}const l=S.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:h,pageHeight:d,pageX:u,pageY:f}=i.rawDims;a.left=`${100*(l[0]-u)/h}%`,a.top=`${100*(l[1]-f)/d}%`;const{rotation:p}=e;return e.hasOwnCanvas||p===0?(a.width=`${100*r/h}%`,a.height=`${100*o/d}%`):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:n,height:a}=xt(this.data.rect);let r,o;t%180===0?(r=100*n/s,o=100*a/i):(r=100*a/s,o=100*n/i),e.style.width=`${r}%`,e.style.height=`${o}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],a=n[0],r=n.slice(1);i.target.style[s]=Rs[`${a}_HTML`](r),this.annotationStorage.setValue(this.data.id,{[s]:Rs[`${a}_rgb`](r)})};return D(this,"_commonActions",{display:e=>{const{display:s}=e.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{const{hidden:s}=e.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:e=>{const s=e.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail))(t[i]||s[i])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const a=s[i];if(a){const r={detail:{[i]:n},target:t};a(r),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(g=>Math.fround(g));if(t.length===8){const[g,b,m,A]=t.subarray(2,6);if(i===g&&n===b&&e===m&&s===A)return}const{style:a}=this.container;let r;if(this.#e){const{borderColor:g,borderWidth:b}=a;a.borderWidth=0,r=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${g}" stroke-width="${b}">`],this.container.classList.add("hasBorder")}const o=i-e,l=n-s,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0);const u=h.createElement("defs");d.append(u);const f=h.createElement("clipPath"),p=`clippath_${this.data.id}`;f.setAttribute("id",p),f.setAttribute("clipPathUnits","objectBoundingBox"),u.append(f);for(let g=2,b=t.length;g<b;g+=8){const m=t[g],A=t[g+1],y=t[g+2],_=t[g+3],v=h.createElement("rect"),w=(y-e)/o,E=(n-A)/l,C=(m-y)/o,x=(A-_)/l;v.setAttribute("x",w),v.setAttribute("y",E),v.setAttribute("width",C),v.setAttribute("height",x),f.append(v),r?.push(`<rect vector-effect="non-scaling-stroke" x="${w}" y="${E}" width="${C}" height="${x}"/>`)}this.#e&&(r.push("</g></svg>')"),a.backgroundImage=r.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#s=new We({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){H("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:a,exportValues:r}of i){if(n===-1||a===e)continue;const o=typeof r=="string"?r:null,l=document.querySelector(`[data-element-id="${a}"]`);if(l&&!Dt.has(l)){F(`_getElementsByName - element not allowed: ${a}`);continue}s.push({id:a,exportValue:o,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,a=i.getAttribute("data-element-id");a!==e&&Dt.has(i)&&s.push({id:a,exportValue:n,domElement:i})}return s}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})})}}class Zs extends V{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,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action),i=!0):t.attachment?(this.#e(s,t.attachment,t.attachmentDest),i=!0):t.setOCGState?(this.#s(s,t.setOCGState),i=!0):t.dest?(this._bindLink(s,t.dest),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(s),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||e==="")&&this.#t()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#t()}#e(t,e,s=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#t()}#s(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#t()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}t.onclick||(t.onclick=()=>!1),this.#t()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects){F('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1);return}t.onclick=()=>{s?.();const{fields:i,refs:n,include:a}=e,r=[];if(i.length!==0||n.length!==0){const h=new Set(n);for(const d of i){const u=this._fieldObjects[d]||[];for(const{id:f}of u)h.add(f)}for(const d of Object.values(this._fieldObjects))for(const u of d)h.has(u.id)===a&&r.push(u)}else for(const h of Object.values(this._fieldObjects))r.push(...h);const o=this.annotationStorage,l=[];for(const h of r){const{id:d}=h;switch(l.push(d),h.type){case"text":{const f=h.defaultValue||"";o.setValue(d,{value:f});break}case"checkbox":case"radiobutton":{const f=h.defaultValue===h.exportValues;o.setValue(d,{value:f});break}case"combobox":case"listbox":{const f=h.defaultValue||"";o.setValue(d,{value:f});break}default:continue}const u=document.querySelector(`[data-element-id="${d}"]`);if(u){if(!Dt.has(u)){F(`_bindResetFormAction - element not allowed: ${d}`);continue}}else continue;u.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:l,name:"ResetForm"}}),!1}}}class $n extends V{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class Ht extends V{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return rt.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,a=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(a),shift:a.shiftKey,modifier:this._getKeyModifier(a)}})}):t.addEventListener(s,a=>{if(s==="blur"){if(!e.focused||!a.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(a)}})})}_setEventListeners(t,e,s,i){for(const[n,a]of s)(a==="Action"||this.data.actions?.[a])&&((a==="Focus"||a==="Blur")&&(e||={focused:!1}),this._setEventListener(t,e,n,a,i),a==="Focus"&&!this.data.actions?.Blur?this._setEventListener(t,e,"blur","Blur",null):a==="Blur"&&!this.data.actions?.Focus&&this._setEventListener(t,e,"focus","Focus",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":S.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||jn,n=t.style;let a;const r=2,o=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-r),h=Math.round(l/(Pe*i))||1,d=l/h;a=Math.min(i,o(d/Pe))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-r);a=Math.min(i,o(l/Pe))}n.fontSize=`calc(${a}px * var(--scale-factor))`,n.color=S.makeHexColor(s[0],s[1],s[2]),this.data.textAlignment!==null&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class Wn extends Ht{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=s),n.setValue(a.id,{[i]:s})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=i.formattedValue||this.data.textContent?.join(`
`)||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=r??n,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",r??n),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),Dt.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=le,this._setRequired(s,this.data.required),a&&(s.maxLength=a),s.addEventListener("input",h=>{t.setValue(e,{value:h.target.value}),this.setPropertyOnSiblings(s,"value",h.target.value,"value"),o.formattedValue=null}),s.addEventListener("resetform",h=>{const d=this.data.defaultFieldValue??"";s.value=o.userValue=d,o.formattedValue=null});let l=h=>{const{formattedValue:d}=o;d!=null&&(h.target.value=d),h.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",d=>{if(o.focused)return;const{target:u}=d;o.userValue&&(u.value=o.userValue),o.lastCommittedValue=u.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)}),s.addEventListener("updatefromsandbox",d=>{this.showElementAndHideCanvas(d.target);const u={value(f){o.userValue=f.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),f.target.value=o.userValue},formattedValue(f){const{formattedValue:p}=f.detail;o.formattedValue=p,p!=null&&f.target!==document.activeElement&&(f.target.value=p),t.setValue(e,{formattedValue:p})},selRange(f){f.target.setSelectionRange(...f.detail.selRange)},charLimit:f=>{const{charLimit:p}=f.detail,{target:g}=f;if(p===0){g.removeAttribute("maxLength");return}g.setAttribute("maxLength",p);let b=o.userValue;!b||b.length<=p||(b=b.slice(0,p),g.value=o.userValue=b,t.setValue(e,{value:b}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:g.selectionStart,selEnd:g.selectionEnd}}))}};this._dispatchEventFromSandbox(u,d)}),s.addEventListener("keydown",d=>{o.commitKey=1;let u=-1;if(d.key==="Escape"?u=0:d.key==="Enter"&&!this.data.multiLine?u=2:d.key==="Tab"&&(o.commitKey=3),u===-1)return;const{value:f}=d.target;o.lastCommittedValue!==f&&(o.lastCommittedValue=f,o.userValue=f,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:f,willCommit:!0,commitKey:u,selStart:d.target.selectionStart,selEnd:d.target.selectionEnd}}))});const h=l;l=null,s.addEventListener("blur",d=>{if(!o.focused||!d.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:u}=d.target;o.userValue=u,o.lastCommittedValue!==u&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:u,willCommit:!0,commitKey:o.commitKey,selStart:d.target.selectionStart,selEnd:d.target.selectionEnd}}),h(d)}),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",d=>{o.lastCommittedValue=null;const{data:u,target:f}=d,{value:p,selectionStart:g,selectionEnd:b}=f;let m=g,A=b;switch(d.inputType){case"deleteWordBackward":{const y=p.substring(0,g).match(/\w*[^\w]*$/);y&&(m-=y[0].length);break}case"deleteWordForward":{const y=p.substring(g).match(/^[^\w]*\w*/);y&&(A+=y[0].length);break}case"deleteContentBackward":g===b&&(m-=1);break;case"deleteContentForward":g===b&&(A+=1);break}d.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:p,change:u||"",willCommit:!1,selStart:m,selEnd:A}})}),this._setEventListeners(s,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],d=>d.target.value)}if(l&&s.addEventListener("blur",l),this.data.comb){const d=(this.data.rect[2]-this.data.rect[0])/a;s.classList.add("comb"),s.style.letterSpacing=`calc(${d}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Vn extends Ht{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class qn extends Ht{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",t.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return Dt.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=le,n.addEventListener("change",a=>{const{name:r,checked:o}=a.target;for(const l of this._getElementsByName(r,s)){const h=o&&l.exportValue===e.exportValue;l.domElement&&(l.domElement.checked=h),t.setValue(l.id,{value:h})}t.setValue(s,{value:o})}),n.addEventListener("resetform",a=>{const r=e.defaultFieldValue||"Off";a.target.checked=r===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",a=>{const r={value(o){o.target.checked=o.detail.value!=="Off",t.setValue(s,{value:o.target.checked})}};this._dispatchEventFromSandbox(r,a)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],a=>a.target.checked)),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class ti extends Ht{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if(typeof i=="string"&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const a of this._getElementsByName(e.fieldName,s))t.setValue(a.id,{value:!1});const n=document.createElement("input");if(Dt.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=le,n.addEventListener("change",a=>{const{name:r,checked:o}=a.target;for(const l of this._getElementsByName(r,s))t.setValue(l.id,{value:!1});t.setValue(s,{value:o})}),n.addEventListener("resetform",a=>{const r=e.defaultFieldValue;a.target.checked=r!=null&&r===e.buttonValue}),this.enableScripting&&this.hasJSActions){const a=e.buttonValue;n.addEventListener("updatefromsandbox",r=>{const o={value:l=>{const h=a===l.detail.value;for(const d of this._getElementsByName(l.target.name)){const u=h&&d.id===s;d.domElement&&(d.domElement.checked=u),t.setValue(d.id,{value:u})}}};this._dispatchEventFromSandbox(o,r)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],r=>r.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Xn extends Zs{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",s=>{this._dispatchEventFromSandbox({},s)})),t}}class Yn extends Ht{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,s=t.getValue(e,{value:this.data.fieldValue}),i=document.createElement("select");Dt.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=le;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",h=>{const d=this.data.defaultFieldValue;for(const u of i.options)u.selected=u.value===d});for(const h of this.data.options){const d=document.createElement("option");d.textContent=h.displayValue,d.value=h.exportValue,s.value.includes(h.exportValue)&&(d.setAttribute("selected",!0),n=!1),i.append(d)}let a=null;if(n){const h=document.createElement("option");h.value=" ",h.setAttribute("hidden",!0),h.setAttribute("selected",!0),i.prepend(h),a=()=>{h.remove(),i.removeEventListener("input",a),a=null},i.addEventListener("input",a)}const r=h=>{const d=h?"value":"textContent",{options:u,multiple:f}=i;return f?Array.prototype.filter.call(u,p=>p.selected).map(p=>p[d]):u.selectedIndex===-1?null:u[u.selectedIndex][d]};let o=r(!1);const l=h=>{const d=h.target.options;return Array.prototype.map.call(d,u=>({displayValue:u.textContent,exportValue:u.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",h=>{const d={value(u){a?.();const f=u.detail.value,p=new Set(Array.isArray(f)?f:[f]);for(const g of i.options)g.selected=p.has(g.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(u){i.multiple=!0},remove(u){const f=i.options,p=u.detail.remove;f[p].selected=!1,i.remove(p),f.length>0&&Array.prototype.findIndex.call(f,b=>b.selected)===-1&&(f[0].selected=!0),t.setValue(e,{value:r(!0),items:l(u)}),o=r(!1)},clear(u){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(u){const{index:f,displayValue:p,exportValue:g}=u.detail.insert,b=i.children[f],m=document.createElement("option");m.textContent=p,m.value=g,b?b.before(m):i.append(m),t.setValue(e,{value:r(!0),items:l(u)}),o=r(!1)},items(u){const{items:f}=u.detail;for(;i.length!==0;)i.remove(0);for(const p of f){const{displayValue:g,exportValue:b}=p,m=document.createElement("option");m.textContent=g,m.value=b,i.append(m)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:r(!0),items:l(u)}),o=r(!1)},indices(u){const f=new Set(u.detail.indices);for(const p of u.target.options)p.selected=f.has(p.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(u){u.target.disabled=!u.detail.editable}};this._dispatchEventFromSandbox(d,h)}),i.addEventListener("input",h=>{const d=r(!0),u=r(!1);t.setValue(e,{value:d}),h.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:u,changeEx:d,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],h=>h.target.value)):i.addEventListener("input",function(h){t.setValue(e,{value:r(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class We extends V{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:V._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Kn({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,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}),e=[];for(const s of this.elements)s.popup=t,s.container.ariaHasPopup="dialog",e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(s=>`${Xe}${s}`).join(",")),this.container}}class Kn{#t=this.#D.bind(this);#e=this.#k.bind(this);#s=this.#x.bind(this);#n=this.#v.bind(this);#a=null;#i=null;#l=null;#h=null;#c=null;#o=null;#d=null;#r=!1;#u=null;#p=null;#f=null;#b=null;#m=null;#g=null;#A=!1;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#i=t,this.#m=i,this.#l=a,this.#b=r,this.#o=o,this.#a=e,this.#f=l,this.#d=h,this.#c=s,this.#h=Fs.toDateObject(n),this.trigger=s.flatMap(u=>u.getElementsToTriggerPopup());for(const u of this.trigger)u.addEventListener("click",this.#n),u.addEventListener("mouseenter",this.#s),u.addEventListener("mouseleave",this.#e),u.classList.add("popupTriggerArea");for(const u of s)u.container?.addEventListener("keydown",this.#t);this.#i.hidden=!0,d&&this.#v()}render(){if(this.#u)return;const t=this.#u=document.createElement("div");if(t.className="popup",this.#a){const n=t.style.outlineColor=S.makeHexColor(...this.#a);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`:t.style.backgroundColor=S.makeHexColor(...this.#a.map(r=>Math.floor(.7*(255-r)+r)))}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");if(e.append(s),{dir:s.dir,str:s.textContent}=this.#m,t.append(e),this.#h){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),n.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#h.valueOf()})),e.append(n)}const i=this.#y;if(i)Js.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(this.#l);t.append(n)}this.#i.append(t)}get#y(){const t=this.#b,e=this.#l;return t?.str&&(!e?.str||e.str===t.str)&&this.#b.html||null}get#C(){return this.#y?.attributes?.style?.fontSize||0}get#E(){return this.#y?.attributes?.style?.color||null}#S(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#E,fontSize:this.#C?`calc(${this.#C}px * var(--scale-factor))`:""}};for(const n of t.split(`
`))e.push({name:"span",value:n,attributes:i});return s}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.classList.add("popupContent"),s.dir=e;const i=t.split(/(?:\r\n?|\n)/);for(let n=0,a=i.length;n<a;++n){const r=i[n];s.append(document.createTextNode(r)),n<a-1&&s.append(document.createElement("br"))}return s}#D(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&this.#r)&&this.#v()}updateEdited({rect:t,popupContent:e}){this.#g||={contentsObj:this.#l,richText:this.#b},t&&(this.#p=null),e&&(this.#b=this.#S(e),this.#l=null),this.#u?.remove(),this.#u=null}resetEdited(){this.#g&&({contentsObj:this.#l,richText:this.#b}=this.#g,this.#g=null,this.#u?.remove(),this.#u=null,this.#p=null)}#T(){if(this.#p!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#o;let a=!!this.#d,r=a?this.#d:this.#f;for(const p of this.#c)if(!r||S.intersect(p.data.rect,r)!==null){r=p.data.rect,a=!0;break}const o=S.normalizeRect([r[0],t[3]-r[1]+t[1],r[2],t[3]-r[3]+t[1]]),h=a?r[2]-r[0]+5:0,d=o[0]+h,u=o[1];this.#p=[100*(d-i)/e,100*(u-n)/s];const{style:f}=this.#i;f.left=`${this.#p[0]}%`,f.top=`${this.#p[1]}%`}#v(){this.#r=!this.#r,this.#r?(this.#x(),this.#i.addEventListener("click",this.#n),this.#i.addEventListener("keydown",this.#t)):(this.#k(),this.#i.removeEventListener("click",this.#n),this.#i.removeEventListener("keydown",this.#t))}#x(){this.#u||this.render(),this.isVisible?this.#r&&this.#i.classList.add("focused"):(this.#T(),this.#i.hidden=!1,this.#i.style.zIndex=parseInt(this.#i.style.zIndex)+1e3)}#k(){this.#i.classList.remove("focused"),!(this.#r||!this.isVisible)&&(this.#i.hidden=!0,this.#i.style.zIndex=parseInt(this.#i.style.zIndex)-1e3)}forceHide(){this.#A=this.isVisible,this.#A&&(this.#i.hidden=!0)}maybeShow(){this.#A&&(this.#u||this.#x(),this.#A=!1,this.#i.hidden=!1)}get isVisible(){return this.#i.hidden===!1}}class ei extends V{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=I.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Qn extends V{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=xt(t.rect),i=this.svgFactory.create(e,s,!0),n=this.#t=this.svgFactory.createElement("svg:line");return n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),i.append(n),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Jn extends V{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=xt(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,a=this.#t=this.svgFactory.createElement("svg:rect");return a.setAttribute("x",n/2),a.setAttribute("y",n/2),a.setAttribute("width",e-n),a.setAttribute("height",s-n),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),i.append(a),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Zn extends V{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=xt(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,a=this.#t=this.svgFactory.createElement("svg:ellipse");return a.setAttribute("cx",e/2),a.setAttribute("cy",s/2),a.setAttribute("rx",e/2-n/2),a.setAttribute("ry",s/2-n/2),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),i.append(a),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class si extends V{#t=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:s,popupRef:i}}=this;if(!e)return this.container;const{width:n,height:a}=xt(t),r=this.svgFactory.create(n,a,!0);let o=[];for(let h=0,d=e.length;h<d;h+=2){const u=e[h]-t[0],f=t[3]-e[h+1];o.push(`${u},${f}`)}o=o.join(" ");const l=this.#t=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",o),l.setAttribute("stroke-width",s.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),r.append(l),this.container.append(r),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class ta extends si{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class ea extends V{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class ls extends V{#t=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?I.HIGHLIGHT:I.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,inkLists:e,borderStyle:s,popupRef:i}}=this,{width:n,height:a}=xt(t),r=this.svgFactory.create(n,a,!0);for(const o of e){let l=[];for(let d=0,u=o.length;d<u;d+=2){const f=o[d]-t[0],p=t[3]-o[d+1];l.push(`${f},${p}`)}l=l.join(" ");const h=this.svgFactory.createElement(this.svgElementName);this.#t.push(h),h.setAttribute("points",l),h.setAttribute("stroke-width",s.width||1),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),r.append(h)}return!i&&this.hasPopupData&&this._createPopup(),this.container.append(r),this._editOnDoubleClick(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class ii extends V{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=I.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class sa extends V{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class ia extends V{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class na extends V{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class ni extends V{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=I.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class aa extends V{#t=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let s;e.hasAppearance||e.fillAlpha===0?s=document.createElement("div"):(s=document.createElement("img"),s.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(s.style=`filter: opacity(${Math.round(e.fillAlpha*100)}%);`)),s.addEventListener("dblclick",this.#e.bind(this)),this.#t=s;const{isMac:i}=rt.platform;return t.addEventListener("keydown",n=>{n.key==="Enter"&&(i?n.metaKey:n.ctrlKey)&&this.#e()}),!e.popupRef&&this.hasPopupData?this._createPopup():s.classList.add("popupTriggerArea"),t.append(s),t}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class ra{#t=null;#e=null;#s=new Map;#n=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:a,structTreeLayer:r}){this.div=t,this.#t=e,this.#e=s,this.#n=r||null,this.page=n,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return this.#s.size>0}async#a(t,e){const s=t.firstChild||t,i=s.id=`${Xe}${e}`,n=await this.#n?.getAriaAttributes(i);if(n)for(const[a,r]of n)s.setAttribute(a,r);this.div.append(t),this.#t?.moveElementInDOM(this.div,t,s,!1)}async render(t){const{annotations:e}=t,s=this.div;Ft(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new os,annotationStorage:t.annotationStorage||new ts,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const a of e){if(a.noHTML)continue;const r=a.annotationType===K.POPUP;if(r){const h=i.get(a.id);if(!h)continue;n.elements=h}else{const{width:h,height:d}=xt(a.rect);if(h<=0||d<=0)continue}n.data=a;const o=Gn.create(n);if(!o.isRenderable)continue;if(!r&&a.popupRef){const h=i.get(a.popupRef);h?h.push(o):i.set(a.popupRef,[o])}const l=o.render();a.hidden&&(l.style.visibility="hidden"),await this.#a(l,a.id),o._isEditable&&(this.#s.set(o.data.id,o),this._annotationEditorUIManager?.renderAnnotationElement(o))}this.#i()}update({viewport:t}){const e=this.div;this.viewport=t,Ft(e,{rotation:t.rotation}),this.#i(),e.hidden=!1}#i(){if(!this.#e)return;const t=this.div;for(const[e,s]of this.#e){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?n.nodeName==="CANVAS"?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#s.values())}getEditableAnnotation(t){return this.#s.get(t)}}const ge=/\r\n?|\n/g;class Q extends k{#t;#e="";#s=`${this.id}-editor`;#n=null;#a;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Q.prototype,e=n=>n.isEmpty(),s=kt.TRANSLATE_SMALL,i=kt.TRANSLATE_BIG;return D(this,"_keyboardManager",new oe([[["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:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=I.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#t=t.color||Q._defaultColor||k._defaultLineColor,this.#a=t.fontSize||Q._defaultFontSize}static initialize(t,e){k.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case R.FREETEXT_SIZE:Q._defaultFontSize=e;break;case R.FREETEXT_COLOR:Q._defaultColor=e;break}}updateParams(t,e){switch(t){case R.FREETEXT_SIZE:this.#i(e);break;case R.FREETEXT_COLOR:this.#l(e);break}}static get defaultPropertiesToUpdate(){return[[R.FREETEXT_SIZE,Q._defaultFontSize],[R.FREETEXT_COLOR,Q._defaultColor||k._defaultLineColor]]}get propertiesToUpdate(){return[[R.FREETEXT_SIZE,this.#a],[R.FREETEXT_COLOR,this.#t]]}#i(t){const e=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-this.#a)*this.parentScale),this.#a=i,this.#c()},s=this.#a;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:R.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#l(t){const e=i=>{this.#t=this.editorDiv.style.color=i},s=this.#t;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:R.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Q._internalPadding*t,-(Q._internalPadding+this.#a)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(I.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#n=new AbortController;const t=this._uiManager.combinedSignal(this.#n);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})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#s),this._isDraggable=!0,this.#n?.abort(),this.#n=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#h(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&s.nodeName==="BR"||(t.push(Q.#o(s)),e=s);return t.join(`
`)}#c(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:i,div:n}=this,a=n.style.display,r=n.classList.contains("hidden");n.classList.remove("hidden"),n.style.display="hidden",i.div.append(this.div),s=n.getBoundingClientRect(),n.remove(),n.style.display=a,n.classList.toggle("hidden",r)}this.rotation%180===this.parentRotation%180?(this.width=s.width/t,this.height=s.height/e):(this.width=s.height/t,this.height=s.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#e,e=this.#e=this.#h().trimEnd();if(t===e)return;const s=i=>{if(this.#e=i,!i){this.remove();return}this.#d(),this._uiManager.rebuild(this),this.#c()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#c()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&t.key==="Enter"&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Q._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)}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#s),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:s}=this.editorDiv;if(s.fontSize=`calc(${this.#a}px * var(--scale-factor))`,s.color=this.#t,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),_e(this,this.div,["dblclick","keydown"]),this.width){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:a}=this._initialData;let[r,o]=this.getInitialTranslation();[r,o]=this.pageTranslationToScreen(r,o);const[l,h]=this.pageDimensions,[d,u]=this.pageTranslation;let f,p;switch(this.rotation){case 0:f=t+(a[0]-d)/l,p=e+this.height-(a[1]-u)/h;break;case 90:f=t+(a[0]-d)/l,p=e-(a[1]-u)/h,[r,o]=[o,-r];break;case 180:f=t-this.width+(a[0]-d)/l,p=e-(a[1]-u)/h,[r,o]=[-r,-o];break;case 270:f=t+(a[0]-d-this.height*h)/l,p=e+(a[1]-u-this.width*l)/h,[r,o]=[-o,r];break}this.setAt(f*i,p*n,r,o)}else this.setAt(t*i,e*n,this.width*i,this.height*n);this.#d(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#o(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(ge,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(s.length===1&&s[0]==="text/plain")return;t.preventDefault();const i=Q.#u(e.getData("text")||"").replaceAll(ge,`
`);if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!i.includes(`
`)){a.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),n.collapseToStart();return}const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const f=r.parentElement;if(h.push(r.nodeValue.slice(o).replaceAll(ge,"")),f!==this.editorDiv){let p=l;for(const g of this.editorDiv.childNodes){if(g===f){p=h;continue}p.push(Q.#o(g))}}l.push(r.nodeValue.slice(0,o).replaceAll(ge,""))}else if(r===this.editorDiv){let f=l,p=0;for(const g of this.editorDiv.childNodes)p++===o&&(f=h),f.push(Q.#o(g))}this.#e=`${l.join(`
`)}${i}${h.join(`
`)}`,this.#d();const d=new Range;let u=l.reduce((f,p)=>f+p.length,0);for(const{firstChild:f}of this.editorDiv.childNodes)if(f.nodeType===Node.TEXT_NODE){const p=f.nodeValue.length;if(u<=p){d.setStart(f,u),d.setEnd(f,u);break}u-=p}n.removeAllRanges(),n.addRange(d)}#d(){if(this.editorDiv.replaceChildren(),!!this.#e)for(const t of this.#e.split(`
`)){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#r(){return this.#e.replaceAll(" "," ")}static#u(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,s){let i=null;if(t instanceof ei){const{data:{defaultAppearanceData:{fontSize:a,fontColor:r},rect:o,rotation:l,id:h,popupRef:d},textContent:u,textPosition:f,parent:{page:{pageNumber:p}}}=t;if(!u||u.length===0)return null;i=t={annotationType:I.FREETEXT,color:Array.from(r),fontSize:a,value:u.join(`
`),position:f,pageIndex:p-1,rect:o.slice(0),rotation:l,id:h,deleted:!1,popupRef:d}}const n=await super.deserialize(t,e,s);return n.#a=t.fontSize,n.#t=S.makeHexColor(...t.color),n.#e=Q.#u(t.value),n.annotationElementId=t.id||null,n._initialData=i,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=Q._internalPadding*this.parentScale,s=this.getRect(e,e),i=k._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#t),n={annotationType:I.FREETEXT,color:i,fontSize:this.#a,value:this.#r(),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#p(n)?null:(n.id=this.annotationElementId,n)}#p(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some((a,r)=>a!==i[r])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:s}=e;s.fontSize=`calc(${this.#a}px * var(--scale-factor))`,s.color=this.#t,e.replaceChildren();for(const n of this.#e.split(`
`)){const a=document.createElement("div");a.append(n?document.createTextNode(n):document.createElement("br")),e.append(a)}const i=Q._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#e}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class ai{toSVGPath(){H("Abstract method `toSVGPath` must be implemented.")}get box(){H("Abstract getter `box` must be implemented.")}serialize(t,e){H("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){H("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){H("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}class Pt{#t;#e=[];#s;#n;#a=[];#i=new Float64Array(18);#l;#h;#c;#o;#d;#r;#u=[];static#p=8;static#f=2;static#b=Pt.#p+Pt.#f;constructor({x:t,y:e},s,i,n,a,r=0){this.#t=s,this.#r=n*i,this.#n=a,this.#i.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=r,this.#o=Pt.#p*i,this.#c=Pt.#b*i,this.#d=i,this.#u.push(t,e)}isEmpty(){return isNaN(this.#i[8])}#m(){const t=this.#i.subarray(4,6),e=this.#i.subarray(16,18),[s,i,n,a]=this.#t;return[(this.#l+(t[0]-e[0])/2-s)/n,(this.#h+(t[1]-e[1])/2-i)/a,(this.#l+(e[0]-t[0])/2-s)/n,(this.#h+(e[1]-t[1])/2-i)/a]}add({x:t,y:e}){this.#l=t,this.#h=e;const[s,i,n,a]=this.#t;let[r,o,l,h]=this.#i.subarray(8,12);const d=t-l,u=e-h,f=Math.hypot(d,u);if(f<this.#c)return!1;const p=f-this.#o,g=p/f,b=g*d,m=g*u;let A=r,y=o;r=l,o=h,l+=b,h+=m,this.#u?.push(t,e);const _=-m/p,v=b/p,w=_*this.#r,E=v*this.#r;return this.#i.set(this.#i.subarray(2,8),0),this.#i.set([l+w,h+E],4),this.#i.set(this.#i.subarray(14,18),12),this.#i.set([l-w,h-E],16),isNaN(this.#i[6])?(this.#a.length===0&&(this.#i.set([r+w,o+E],2),this.#a.push(NaN,NaN,NaN,NaN,(r+w-s)/n,(o+E-i)/a),this.#i.set([r-w,o-E],14),this.#e.push(NaN,NaN,NaN,NaN,(r-w-s)/n,(o-E-i)/a)),this.#i.set([A,y,r,o,l,h],6),!this.isEmpty()):(this.#i.set([A,y,r,o,l,h],6),Math.abs(Math.atan2(y-o,A-r)-Math.atan2(m,b))<Math.PI/2?([r,o,l,h]=this.#i.subarray(2,6),this.#a.push(NaN,NaN,NaN,NaN,((r+l)/2-s)/n,((o+h)/2-i)/a),[r,o,A,y]=this.#i.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((A+r)/2-s)/n,((y+o)/2-i)/a),!0):([A,y,r,o,l,h]=this.#i.subarray(0,6),this.#a.push(((A+5*r)/6-s)/n,((y+5*o)/6-i)/a,((5*r+l)/6-s)/n,((5*o+h)/6-i)/a,((r+l)/2-s)/n,((o+h)/2-i)/a),[l,h,r,o,A,y]=this.#i.subarray(12,18),this.#e.push(((A+5*r)/6-s)/n,((y+5*o)/6-i)/a,((5*r+l)/6-s)/n,((5*o+h)/6-i)/a,((r+l)/2-s)/n,((o+h)/2-i)/a),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#a,e=this.#e;if(isNaN(this.#i[6])&&!this.isEmpty())return this.#g();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#y(s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return this.#A(s),s.join(" ")}#g(){const[t,e,s,i]=this.#t,[n,a,r,o]=this.#m();return`M${(this.#i[2]-t)/s} ${(this.#i[3]-e)/i} L${(this.#i[4]-t)/s} ${(this.#i[5]-e)/i} L${n} ${a} L${r} ${o} L${(this.#i[16]-t)/s} ${(this.#i[17]-e)/i} L${(this.#i[14]-t)/s} ${(this.#i[15]-e)/i} Z`}#A(t){const e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#y(t){const[e,s,i,n]=this.#t,a=this.#i.subarray(4,6),r=this.#i.subarray(16,18),[o,l,h,d]=this.#m();t.push(`L${(a[0]-e)/i} ${(a[1]-s)/n} L${o} ${l} L${h} ${d} L${(r[0]-e)/i} ${(r[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,a){return new ri(t,e,s,i,n,a)}getOutlines(){const t=this.#a,e=this.#e,s=this.#i,[i,n,a,r]=this.#t,o=new Float64Array((this.#u?.length??0)+2);for(let d=0,u=o.length-2;d<u;d+=2)o[d]=(this.#u[d]-i)/a,o[d+1]=(this.#u[d+1]-n)/r;if(o[o.length-2]=(this.#l-i)/a,o[o.length-1]=(this.#h-n)/r,isNaN(s[6])&&!this.isEmpty())return this.#C(o);const l=new Float64Array(this.#a.length+24+this.#e.length);let h=t.length;for(let d=0;d<h;d+=2){if(isNaN(t[d])){l[d]=l[d+1]=NaN;continue}l[d]=t[d],l[d+1]=t[d+1]}h=this.#S(l,h);for(let d=e.length-6;d>=6;d-=6)for(let u=0;u<6;u+=2){if(isNaN(e[d+u])){l[h]=l[h+1]=NaN,h+=2;continue}l[h]=e[d+u],l[h+1]=e[d+u+1],h+=2}return this.#E(l,h),this.newFreeDrawOutline(l,o,this.#t,this.#d,this.#s,this.#n)}#C(t){const e=this.#i,[s,i,n,a]=this.#t,[r,o,l,h]=this.#m(),d=new Float64Array(36);return d.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/a,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/a,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/a],0),this.newFreeDrawOutline(d,t,this.#t,this.#d,this.#s,this.#n)}#E(t,e){const s=this.#e;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6}#S(t,e){const s=this.#i.subarray(4,6),i=this.#i.subarray(16,18),[n,a,r,o]=this.#t,[l,h,d,u]=this.#m();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o],e),e+=24}}class ri extends ai{#t;#e=null;#s;#n;#a;#i;#l;constructor(t,e,s,i,n,a){super(),this.#l=t,this.#a=e,this.#t=s,this.#i=i,this.#s=n,this.#n=a,this.#o(a);const{x:r,y:o,width:l,height:h}=this.#e;for(let d=0,u=t.length;d<u;d+=2)t[d]=(t[d]-r)/l,t[d+1]=(t[d+1]-o)/h;for(let d=0,u=e.length;d<u;d+=2)e[d]=(e[d]-r)/l,e[d+1]=(e[d+1]-o)/h}toSVGPath(){const t=[`M${this.#l[4]} ${this.#l[5]}`];for(let e=6,s=this.#l.length;e<s;e+=6){if(isNaN(this.#l[e])){t.push(`L${this.#l[e+4]} ${this.#l[e+5]}`);continue}t.push(`C${this.#l[e]} ${this.#l[e+1]} ${this.#l[e+2]} ${this.#l[e+3]} ${this.#l[e+4]} ${this.#l[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const a=s-t,r=i-e;let o,l;switch(n){case 0:o=this.#h(this.#l,t,i,a,-r),l=this.#h(this.#a,t,i,a,-r);break;case 90:o=this.#c(this.#l,t,e,a,r),l=this.#c(this.#a,t,e,a,r);break;case 180:o=this.#h(this.#l,s,e,-a,r),l=this.#h(this.#a,s,e,-a,r);break;case 270:o=this.#c(this.#l,s,i,-a,-r),l=this.#c(this.#a,s,i,-a,-r);break}return{outline:Array.from(o),points:[Array.from(l)]}}#h(t,e,s,i,n){const a=new Float64Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r]*i,a[r+1]=s+t[r+1]*n;return a}#c(t,e,s,i,n){const a=new Float64Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r+1]*i,a[r+1]=s+t[r]*n;return a}#o(t){const e=this.#l;let s=e[4],i=e[5],n=s,a=i,r=s,o=i,l=s,h=i;const d=t?Math.max:Math.min;for(let b=6,m=e.length;b<m;b+=6){if(isNaN(e[b]))n=Math.min(n,e[b+4]),a=Math.min(a,e[b+5]),r=Math.max(r,e[b+4]),o=Math.max(o,e[b+5]),h<e[b+5]?(l=e[b+4],h=e[b+5]):h===e[b+5]&&(l=d(l,e[b+4]));else{const A=S.bezierBoundingBox(s,i,...e.slice(b,b+6));n=Math.min(n,A[0]),a=Math.min(a,A[1]),r=Math.max(r,A[2]),o=Math.max(o,A[3]),h<A[3]?(l=A[2],h=A[3]):h===A[3]&&(l=d(l,A[2]))}s=e[b+4],i=e[b+5]}const u=n-this.#s,f=a-this.#s,p=r-n+2*this.#s,g=o-a+2*this.#s;this.#e={x:u,y:f,width:p,height:g,lastPoint:[l,h]}}get box(){return this.#e}newOutliner(t,e,s,i,n,a=0){return new Pt(t,e,s,i,n,a)}getNewOutline(t,e){const{x:s,y:i,width:n,height:a}=this.#e,[r,o,l,h]=this.#t,d=n*l,u=a*h,f=s*l+r,p=i*h+o,g=this.newOutliner({x:this.#a[0]*d+f,y:this.#a[1]*u+p},this.#t,this.#i,t,this.#n,e??this.#s);for(let b=2;b<this.#a.length;b+=2)g.add({x:this.#a[b]*d+f,y:this.#a[b+1]*u+p});return g.getOutlines()}get mustRemoveSelfIntersections(){return!0}}class Ms{#t;#e=[];#s=[];constructor(t,e=0,s=0,i=!0){let n=1/0,a=-1/0,r=1/0,o=-1/0;const l=10**-4;for(const{x:b,y:m,width:A,height:y}of t){const _=Math.floor((b-e)/l)*l,v=Math.ceil((b+A+e)/l)*l,w=Math.floor((m-e)/l)*l,E=Math.ceil((m+y+e)/l)*l,C=[_,w,E,!0],x=[v,w,E,!1];this.#e.push(C,x),n=Math.min(n,_),a=Math.max(a,v),r=Math.min(r,w),o=Math.max(o,E)}const h=a-n+2*s,d=o-r+2*s,u=n-s,f=r-s,p=this.#e.at(i?-1:-2),g=[p[0],p[2]];for(const b of this.#e){const[m,A,y]=b;b[0]=(m-u)/h,b[1]=(A-f)/d,b[2]=(y-f)/d}this.#t={x:u,y:f,width:h,height:d,lastPoint:g}}getOutlines(){this.#e.sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of this.#e)e[3]?(t.push(...this.#h(e)),this.#i(e)):(this.#l(e),t.push(...this.#h(e)));return this.#n(t)}#n(t){const e=[],s=new Set;for(const a of t){const[r,o,l]=a;e.push([r,o,a],[r,l,a])}e.sort((a,r)=>a[1]-r[1]||a[0]-r[0]);for(let a=0,r=e.length;a<r;a+=2){const o=e[a][2],l=e[a+1][2];o.push(l),l.push(o),s.add(o),s.add(l)}const i=[];let n;for(;s.size>0;){const a=s.values().next().value;let[r,o,l,h,d]=a;s.delete(a);let u=r,f=o;for(n=[r,l],i.push(n);;){let p;if(s.has(h))p=h;else if(s.has(d))p=d;else break;s.delete(p),[r,o,l,h,d]=p,u!==r&&(n.push(u,f,r,f===o?o:l),u=r),f=f===o?l:o}n.push(u,f)}return new oa(i,this.#t)}#a(t){const e=this.#s;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,a=e[n][0];if(a===t)return n;a<t?s=n+1:i=n-1}return i+1}#i([,t,e]){const s=this.#a(t);this.#s.splice(s,0,[t,e])}#l([,t,e]){const s=this.#a(t);for(let i=s;i<this.#s.length;i++){const[n,a]=this.#s[i];if(n!==t)break;if(n===t&&a===e){this.#s.splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,a]=this.#s[i];if(n!==t)break;if(n===t&&a===e){this.#s.splice(i,1);return}}}#h(t){const[e,s,i]=t,n=[[e,s,i]],a=this.#a(i);for(let r=0;r<a;r++){const[o,l]=this.#s[r];for(let h=0,d=n.length;h<d;h++){const[,u,f]=n[h];if(!(l<=u||f<=o)){if(u>=o){if(f>l)n[h][1]=l;else{if(d===1)return[];n.splice(h,1),h--,d--}continue}n[h][2]=o,f>l&&n.push([e,l,f])}}}return n}}class oa extends ai{#t;#e;constructor(t,e){super(),this.#e=t,this.#t=e}toSVGPath(){const t=[];for(const e of this.#e){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const a=e[n],r=e[n+1];a===s?(t.push(`V${r}`),i=r):r===i&&(t.push(`H${a}`),s=a)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const a=[],r=s-t,o=i-e;for(const l of this.#e){const h=new Array(l.length);for(let d=0;d<l.length;d+=2)h[d]=t+l[d]*r,h[d+1]=i-l[d+1]*o;a.push(h)}return a}get box(){return this.#t}get classNamesForDrawing(){return["highlight"]}get classNamesForOutlining(){return["highlightOutline"]}}class Ve extends Pt{newFreeDrawOutline(t,e,s,i,n,a){return new la(t,e,s,i,n,a)}get classNamesForDrawing(){return["highlight","free"]}}class la extends ri{get classNamesForDrawing(){return["highlight","free"]}get classNamesForOutlining(){return["highlightOutline","free"]}newOutliner(t,e,s,i,n,a=0){return new Ve(t,e,s,i,n,a)}}class pt{#t=null;#e=null;#s;#n=null;#a=!1;#i=!1;#l=null;#h;#c=null;#o=null;#d;static#r=null;static get _keyboardManager(){return D(this,"_keyboardManager",new oe([[["Escape","mac+Escape"],pt.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],pt.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],pt.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],pt.prototype._moveToPrevious],[["Home","mac+Home"],pt.prototype._moveToBeginning],[["End","mac+End"],pt.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#i=!1,this.#d=R.HIGHLIGHT_COLOR,this.#l=t):(this.#i=!0,this.#d=R.HIGHLIGHT_DEFAULT_COLOR),this.#o=t?._uiManager||e,this.#h=this.#o._eventBus,this.#s=t?.color||this.#o?.highlightColors.values().next().value||"#FFFF98",pt.#r||=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.#t=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=this.#o._signal;t.addEventListener("click",this.#b.bind(this),{signal:e}),t.addEventListener("keydown",this.#f.bind(this),{signal:e});const s=this.#e=document.createElement("span");return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=this.#s,t.append(s),t}renderMainDropdown(){const t=this.#n=this.#u();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#u(){const t=document.createElement("div"),e=this.#o._signal;t.addEventListener("contextmenu",gt,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of this.#o.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",pt.#r[s]);const a=document.createElement("span");n.append(a),a.className="swatch",a.style.backgroundColor=i,n.setAttribute("aria-selected",i===this.#s),n.addEventListener("click",this.#p.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#f.bind(this),{signal:e}),t}#p(t,e){e.stopPropagation(),this.#h.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#t){this.#b(t);return}const e=t.target.getAttribute("data-color");e&&this.#p(e,t)}_moveToNext(t){if(!this.#g){this.#b(t);return}if(t.target===this.#t){this.#n.firstChild?.focus();return}t.target.nextSibling?.focus()}_moveToPrevious(t){if(t.target===this.#n?.firstChild||t.target===this.#t){this.#g&&this._hideDropdownFromKeyboard();return}this.#g||this.#b(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#g){this.#b(t);return}this.#n.firstChild?.focus()}_moveToEnd(t){if(!this.#g){this.#b(t);return}this.#n.lastChild?.focus()}#f(t){pt._keyboardManager.exec(this,t)}#b(t){if(this.#g){this.hideDropdown();return}if(this.#a=t.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener("pointerdown",this.#m.bind(this),{signal:this.#o.combinedSignal(this.#c)})),this.#n){this.#n.classList.remove("hidden");return}const e=this.#n=this.#u();this.#t.append(e)}#m(t){this.#n?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#n?.classList.add("hidden"),this.#c?.abort(),this.#c=null}get#g(){return this.#n&&!this.#n.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#i){if(!this.#g){this.#l?.unselect();return}this.hideDropdown(),this.#t.focus({preventScroll:!0,focusVisible:this.#a})}}updateColor(t){if(this.#e&&(this.#e.style.backgroundColor=t),!this.#n)return;const e=this.#o.highlightColors.values();for(const s of this.#n.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#n?.remove(),this.#n=null}}class W extends k{#t=null;#e=0;#s;#n=null;#a=null;#i=null;#l=null;#h=0;#c=null;#o=null;#d=null;#r=!1;#u=null;#p;#f=null;#b="";#m;#g="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=I.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=W.prototype;return D(this,"_keyboardManager",new oe([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||W._defaultColor,this.#m=t.thickness||W._defaultThickness,this.#p=t.opacity||W._defaultOpacity,this.#s=t.boxes||null,this.#g=t.methodOfCreation||"",this.#b=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#r=!0,this.#y(t),this.#T()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#l=t.focusNode,this.#h=t.focusOffset,this.#A(),this.#T(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#r?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#m,methodOfCreation:this.#g}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#A(){const t=new Ms(this.#s,.001);this.#o=t.getOutlines(),{x:this.x,y:this.y,width:this.width,height:this.height}=this.#o.box;const e=new Ms(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#i=e.getOutlines();const{lastPoint:s}=this.#i.box;this.#u=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#y({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#o=t;const i=1.5;if(this.#i=t.getNewOutline(this.#m/2+i,.0025),e>=0)this.#d=e,this.#n=s,this.parent.drawLayer.finalizeLine(e,t),this.#f=this.parent.drawLayer.drawOutline(this.#i);else if(this.parent){const h=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#d,t),this.parent.drawLayer.updateBox(this.#d,W.#v(this.#o.box,(h-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#f,this.#i),this.parent.drawLayer.updateBox(this.#f,W.#v(this.#i.box,h))}const{x:n,y:a,width:r,height:o}=t.box;switch(this.rotation){case 0:this.x=n,this.y=a,this.width=r,this.height=o;break;case 90:{const[h,d]=this.parentDimensions;this.x=a,this.y=1-n,this.width=r*d/h,this.height=o*h/d;break}case 180:this.x=1-n,this.y=1-a,this.width=r,this.height=o;break;case 270:{const[h,d]=this.parentDimensions;this.x=1-a,this.y=n,this.width=r*d/h,this.height=o*h/d;break}}const{lastPoint:l}=this.#i.box;this.#u=[(l[0]-n)/r,(l[1]-a)/o]}static initialize(t,e){k.initialize(t,e),W._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case R.HIGHLIGHT_DEFAULT_COLOR:W._defaultColor=e;break;case R.HIGHLIGHT_THICKNESS:W._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#u}updateParams(t,e){switch(t){case R.HIGHLIGHT_COLOR:this.#C(e);break;case R.HIGHLIGHT_THICKNESS:this.#E(e);break}}static get defaultPropertiesToUpdate(){return[[R.HIGHLIGHT_DEFAULT_COLOR,W._defaultColor],[R.HIGHLIGHT_THICKNESS,W._defaultThickness]]}get propertiesToUpdate(){return[[R.HIGHLIGHT_COLOR,this.color||W._defaultColor],[R.HIGHLIGHT_THICKNESS,this.#m||W._defaultThickness],[R.HIGHLIGHT_FREE,this.#r]]}#C(t){const e=(n,a)=>{this.color=n,this.parent?.drawLayer.changeColor(this.#d,n),this.#a?.updateColor(n),this.#p=a,this.parent?.drawLayer.changeOpacity(this.#d,a)},s=this.color,i=this.#p;this.addCommands({cmd:e.bind(this,t,W._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:R.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#E(t){const e=this.#m,s=i=>{this.#m=i,this.#S(i)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:R.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#a=new pt({editor:this}),t.addColorPicker(this.#a)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#R())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#R())}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#D(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#T(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#D():t&&(this.#T(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#S(t){if(!this.#r)return;this.#y({highlightOutlines:this.#o.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#D(){this.#d===null||!this.parent||(this.parent.drawLayer.remove(this.#d),this.#d=null,this.parent.drawLayer.remove(this.#f),this.#f=null)}#T(t=this.parent){this.#d===null&&({id:this.#d,clipPathId:this.#n}=t.drawLayer.draw(this.#o,this.color,this.#p),this.#f=t.drawLayer.drawOutline(this.#i),this.#c&&(this.#c.style.clipPath=this.#n))}static#v({x:t,y:e,width:s,height:i},n){switch(n){case 90:return{x:1-e-i,y:t,width:i,height:s};case 180:return{x:1-t-s,y:1-e-i,width:s,height:i};case 270:return{x:e,y:1-t-s,width:i,height:s}}return{x:t,y:e,width:s,height:i}}rotate(t){const{drawLayer:e}=this.parent;let s;this.#r?(t=(t-this.rotation+360)%360,s=W.#v(this.#o.box,t)):s=W.#v(this,t),e.rotate(this.#d,t),e.rotate(this.#f,t),e.updateBox(this.#d,s),e.updateBox(this.#f,W.#v(this.#i.box,t))}render(){if(this.div)return this.div;const t=super.render();this.#b&&(t.setAttribute("aria-label",this.#b),t.setAttribute("role","mark")),this.#r?t.classList.add("free"):this.div.addEventListener("keydown",this.#x.bind(this),{signal:this._uiManager._signal});const e=this.#c=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#n;const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),_e(this,this.#c,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent.drawLayer.addClass(this.#f,"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(this.#f,"hovered")}#x(t){W._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#k(!0);break;case 1:case 3:this.#k(!1);break}}#k(t){if(!this.#t)return;const e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#l,this.#h)}select(){super.select(),this.#f&&(this.parent?.drawLayer.removeClass(this.#f,"hovered"),this.parent?.drawLayer.addClass(this.#f,"selected"))}unselect(){super.unselect(),this.#f&&(this.parent?.drawLayer.removeClass(this.#f,"selected"),this.#r||this.#k(!1))}get _mustFixPosition(){return!this.#r}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(this.#d,t),this.parent.drawLayer.show(this.#f,t))}#R(){return this.#r?this.rotation:0}#L(){if(this.#r)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#s,a=new Float32Array(n.length*8);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const u=o*t+s,f=(1-l-d)*e+i;a[r]=a[r+4]=u,a[r+1]=a[r+3]=f,a[r+2]=a[r+6]=u+h*t,a[r+5]=a[r+7]=f+d*e,r+=8}return a}#w(t){return this.#o.serialize(t,this.#R())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:a,y:r,width:o,height:l}=s.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),u=p=>{p.preventDefault(),p.stopPropagation()},f=p=>{h.abort(),this.#I(t,p)};window.addEventListener("blur",f,{signal:d}),window.addEventListener("pointerup",f,{signal:d}),window.addEventListener("pointerdown",u,{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",gt,{signal:d}),s.addEventListener("pointermove",this.#_.bind(this,t),{signal:d}),this._freeHighlight=new Ve({x:i,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static#_(t,e){this._freeHighlight.add(e)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#I(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,s){let i=null;if(t instanceof ii){const{data:{quadPoints:p,rect:g,rotation:b,id:m,color:A,opacity:y,popupRef:_},parent:{page:{pageNumber:v}}}=t;i=t={annotationType:I.HIGHLIGHT,color:Array.from(A),opacity:y,quadPoints:p,boxes:null,pageIndex:v-1,rect:g.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}else if(t instanceof ls){const{data:{inkLists:p,rect:g,rotation:b,id:m,color:A,borderStyle:{rawWidth:y},popupRef:_},parent:{page:{pageNumber:v}}}=t;i=t={annotationType:I.HIGHLIGHT,color:Array.from(A),thickness:y,inkLists:p,boxes:null,pageIndex:v-1,rect:g.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,s);l.color=S.makeHexColor(...n),l.#p=o||1,r&&(l.#m=t.thickness),l.annotationElementId=t.id||null,l._initialData=i;const[h,d]=l.pageDimensions,[u,f]=l.pageTranslation;if(a){const p=l.#s=[];for(let g=0;g<a.length;g+=8)p.push({x:(a[g]-u)/h,y:1-(a[g+1]-f)/d,width:(a[g+2]-a[g])/h,height:(a[g+1]-a[g+5])/d});l.#A(),l.#T(),l.rotate(l.rotation)}else if(r){l.#r=!0;const p=r[0],g={x:p[0]-u,y:d-(p[1]-f)},b=new Ve(g,[0,0,h,d],1,l.#m/2,!0,.001);for(let y=0,_=p.length;y<_;y+=2)g.x=p[y]-u,g.y=d-(p[y+1]-f),b.add(g);const{id:m,clipPathId:A}=e.drawLayer.draw(b,l.color,l._defaultOpacity,!0);l.#y({highlightOutlines:b.getOutlines(),highlightId:m,clipPathId:A}),l.#T()}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),s=k._colorManager.convert(this.color),i={annotationType:I.HIGHLIGHT,color:s,opacity:this.#p,thickness:this.#m,quadPoints:this.#L(),outlines:this.#w(e),pageIndex:this.pageIndex,rect:e,rotation:this.#R(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#F(i)?null:(i.id=this.annotationElementId,i)}#F(t){const{color:e}=this._initialData;return t.color.some((s,i)=>s!==e[i])}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class Z extends k{#t=0;#e=0;#s=null;#n=new Path2D;#a=!1;#i=null;#l=!1;#h=!1;#c=null;#o=null;#d=0;#r=0;#u=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=I.INK;constructor(t){super({...t,name:"inkEditor"}),this.color=t.color||null,this.thickness=t.thickness||null,this.opacity=t.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(t,e){k.initialize(t,e)}static updateDefaultParams(t,e){switch(t){case R.INK_THICKNESS:Z._defaultThickness=e;break;case R.INK_COLOR:Z._defaultColor=e;break;case R.INK_OPACITY:Z._defaultOpacity=e/100;break}}updateParams(t,e){switch(t){case R.INK_THICKNESS:this.#p(e);break;case R.INK_COLOR:this.#f(e);break;case R.INK_OPACITY:this.#b(e);break}}static get defaultPropertiesToUpdate(){return[[R.INK_THICKNESS,Z._defaultThickness],[R.INK_COLOR,Z._defaultColor||k._defaultLineColor],[R.INK_OPACITY,Math.round(Z._defaultOpacity*100)]]}get propertiesToUpdate(){return[[R.INK_THICKNESS,this.thickness||Z._defaultThickness],[R.INK_COLOR,this.color||Z._defaultColor||k._defaultLineColor],[R.INK_OPACITY,Math.round(100*(this.opacity??Z._defaultOpacity))]]}#p(t){const e=i=>{this.thickness=i,this.#M()},s=this.thickness;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:R.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#f(t){const e=i=>{this.color=i,this.#v()},s=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:R.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#b(t){const e=i=>{this.opacity=i,this.#v()};t/=100;const s=this.opacity;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:R.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(this.#L(),this.#w()),this.isAttachedToDOM||(this.parent.add(this),this.#_()),this.#M()))}remove(){this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#s&&(clearTimeout(this.#s),this.#s=null),this.#c?.disconnect(),this.#c=null,super.remove())}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&t===null&&this._uiManager.addShouldRescale(this),super.setParent(t)}onScaleChanging(){const[t,e]=this.parentDimensions,s=this.width*t,i=this.height*e;this.setDimensions(s,i)}enableEditMode(){this.#a||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,this.#x())}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.#k())}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}#m(){const{parentRotation:t,parentDimensions:[e,s]}=this;switch(t){case 90:return[0,s,s,e];case 180:return[e,s,e,s];case 270:return[e,0,s,e];default:return[0,0,e,s]}}#g(){const{ctx:t,color:e,opacity:s,thickness:i,parentScale:n,scaleFactor:a}=this;t.lineWidth=i*n/a,t.lineCap="round",t.lineJoin="round",t.miterLimit=10,t.strokeStyle=`${e}${Ri(s)}`}#A(t,e){this.canvas.addEventListener("contextmenu",gt,{signal:this._uiManager._signal}),this.#k(),this.#i=new AbortController;const s=this._uiManager.combinedSignal(this.#i);this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:s}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:s}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:s}),this.isEditing=!0,this.#h||(this.#h=!0,this.#_(),this.thickness||=Z._defaultThickness,this.color||=Z._defaultColor||k._defaultLineColor,this.opacity??=Z._defaultOpacity),this.currentPath.push([t,e]),this.#l=!1,this.#g(),this.#u=()=>{this.#S(),this.#u&&window.requestAnimationFrame(this.#u)},window.requestAnimationFrame(this.#u)}#y(t,e){const[s,i]=this.currentPath.at(-1);if(this.currentPath.length>1&&t===s&&e===i)return;const n=this.currentPath;let a=this.#n;if(n.push([t,e]),this.#l=!0,n.length<=2){a.moveTo(...n[0]),a.lineTo(t,e);return}n.length===3&&(this.#n=a=new Path2D,a.moveTo(...n[0])),this.#D(a,...n.at(-3),...n.at(-2),t,e)}#C(){if(this.currentPath.length===0)return;const t=this.currentPath.at(-1);this.#n.lineTo(...t)}#E(t,e){this.#u=null,t=Math.min(Math.max(t,0),this.canvas.width),e=Math.min(Math.max(e,0),this.canvas.height),this.#y(t,e),this.#C();let s;if(this.currentPath.length!==1)s=this.#T();else{const o=[t,e];s=[[o,o.slice(),o.slice(),o]]}const i=this.#n,n=this.currentPath;this.currentPath=[],this.#n=new Path2D;const a=()=>{this.allRawPaths.push(n),this.paths.push(s),this.bezierPath2D.push(i),this._uiManager.rebuild(this)},r=()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(this.#L(),this.#w()),this.#M())};this.addCommands({cmd:a,undo:r,mustExec:!0})}#S(){if(!this.#l)return;this.#l=!1;const t=Math.ceil(this.thickness*this.parentScale),e=this.currentPath.slice(-3),s=e.map(a=>a[0]),i=e.map(a=>a[1]);Math.min(...s)-t,Math.max(...s)+t,Math.min(...i)-t,Math.max(...i)+t;const{ctx:n}=this;n.save(),n.clearRect(0,0,this.canvas.width,this.canvas.height);for(const a of this.bezierPath2D)n.stroke(a);n.stroke(this.#n),n.restore()}#D(t,e,s,i,n,a,r){const o=(e+i)/2,l=(s+n)/2,h=(i+a)/2,d=(n+r)/2;t.bezierCurveTo(o+2*(i-o)/3,l+2*(n-l)/3,h+2*(i-h)/3,d+2*(n-d)/3,h,d)}#T(){const t=this.currentPath;if(t.length<=2)return[[t[0],t[0],t.at(-1),t.at(-1)]];const e=[];let s,[i,n]=t[0];for(s=1;s<t.length-2;s++){const[u,f]=t[s],[p,g]=t[s+1],b=(u+p)/2,m=(f+g)/2,A=[i+2*(u-i)/3,n+2*(f-n)/3],y=[b+2*(u-b)/3,m+2*(f-m)/3];e.push([[i,n],A,y,[b,m]]),[i,n]=[b,m]}const[a,r]=t[s],[o,l]=t[s+1],h=[i+2*(a-i)/3,n+2*(r-n)/3],d=[o+2*(a-o)/3,l+2*(r-l)/3];return e.push([[i,n],h,d,[o,l]]),e}#v(){if(this.isEmpty()){this.#F();return}this.#g();const{canvas:t,ctx:e}=this;e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height),this.#F();for(const s of this.bezierPath2D)e.stroke(s)}commit(){this.#a||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),this.#a=!0,this.div.classList.add("disabled"),this.#M(!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),this.enableEditMode())}#x(){if(this.#o)return;this.#o=new AbortController;const t=this._uiManager.combinedSignal(this.#o);this.canvas.addEventListener("pointerdown",this.canvasPointerdown.bind(this),{signal:t})}#k(){this.pointerdownAC?.abort(),this.pointerdownAC=null}canvasPointerdown(t){t.button!==0||!this.isInEditMode()||this.#a||(this.setInForeground(),t.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),this.#A(t.offsetX,t.offsetY))}canvasPointermove(t){t.preventDefault(),this.#y(t.offsetX,t.offsetY)}canvasPointerup(t){t.preventDefault(),this.#R(t)}canvasPointerleave(t){this.#R(t)}#R(t){this.#i?.abort(),this.#i=null,this.#x(),this.#s&&clearTimeout(this.#s),this.#s=setTimeout(()=>{this.#s=null,this.canvas.removeEventListener("contextmenu",gt)},10),this.#E(t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#L(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#w(){this.#c=new ResizeObserver(t=>{const e=t[0].contentRect;e.width&&e.height&&this.setDimensions(e.width,e.height)}),this.#c.observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{this.#c?.disconnect(),this.#c=null},{once:!0})}get isResizable(){return!this.isEmpty()&&this.#a}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[s,i,n,a]=this.#m();if(this.setAt(s,i,0,0),this.setDims(n,a),this.#L(),this.width){const[r,o]=this.parentDimensions;this.setAspectRatio(this.width*r,this.height*o),this.setAt(t*r,e*o,this.width*r,this.height*o),this.#h=!0,this.#_(),this.setDims(this.width*r,this.height*o),this.#v(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#w(),this.div}#_(){if(!this.#h)return;const[t,e]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*e),this.#F()}setDimensions(t,e){const s=Math.round(t),i=Math.round(e);if(this.#d===s&&this.#r===i)return;this.#d=s,this.#r=i,this.canvas.style.visibility="hidden";const[n,a]=this.parentDimensions;this.width=t/n,this.height=e/a,this.fixAndSetPosition(),this.#a&&this.#I(t,e),this.#_(),this.#v(),this.canvas.style.visibility="visible",this.fixDims()}#I(t,e){const s=this.#U(),i=(t-s)/this.#e,n=(e-s)/this.#t;this.scaleFactor=Math.min(i,n)}#F(){const t=this.#U()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static#O(t){const e=new Path2D;for(let s=0,i=t.length;s<i;s++){const[n,a,r,o]=t[s];s===0&&e.moveTo(...n),e.bezierCurveTo(a[0],a[1],r[0],r[1],o[0],o[1])}return e}static#j(t,e,s){const[i,n,a,r]=e;switch(s){case 0:for(let o=0,l=t.length;o<l;o+=2)t[o]+=i,t[o+1]=r-t[o+1];break;case 90:for(let o=0,l=t.length;o<l;o+=2){const h=t[o];t[o]=t[o+1]+i,t[o+1]=h+n}break;case 180:for(let o=0,l=t.length;o<l;o+=2)t[o]=a-t[o],t[o+1]+=n;break;case 270:for(let o=0,l=t.length;o<l;o+=2){const h=t[o];t[o]=a-t[o+1],t[o+1]=r-h}break;default:throw new Error("Invalid rotation")}return t}static#B(t,e,s){const[i,n,a,r]=e;switch(s){case 0:for(let o=0,l=t.length;o<l;o+=2)t[o]-=i,t[o+1]=r-t[o+1];break;case 90:for(let o=0,l=t.length;o<l;o+=2){const h=t[o];t[o]=t[o+1]-n,t[o+1]=h-i}break;case 180:for(let o=0,l=t.length;o<l;o+=2)t[o]=a-t[o],t[o+1]-=n;break;case 270:for(let o=0,l=t.length;o<l;o+=2){const h=t[o];t[o]=r-t[o+1],t[o+1]=a-h}break;default:throw new Error("Invalid rotation")}return t}#N(t,e,s,i){const n=[],a=this.thickness/2,r=t*e+a,o=t*s+a;for(const l of this.paths){const h=[],d=[];for(let u=0,f=l.length;u<f;u++){const[p,g,b,m]=l[u];if(p[0]===m[0]&&p[1]===m[1]&&f===1){const O=t*p[0]+r,P=t*p[1]+o;h.push(O,P),d.push(O,P);break}const A=t*p[0]+r,y=t*p[1]+o,_=t*g[0]+r,v=t*g[1]+o,w=t*b[0]+r,E=t*b[1]+o,C=t*m[0]+r,x=t*m[1]+o;u===0&&(h.push(A,y),d.push(A,y)),h.push(_,v,w,E,C,x),d.push(_,v),u===f-1&&d.push(C,x)}n.push({bezier:Z.#j(h,i,this.rotation),points:Z.#j(d,i,this.rotation)})}return n}#H(){let t=1/0,e=-1/0,s=1/0,i=-1/0;for(const n of this.paths)for(const[a,r,o,l]of n){const h=S.bezierBoundingBox(...a,...r,...o,...l);t=Math.min(t,h[0]),s=Math.min(s,h[1]),e=Math.max(e,h[2]),i=Math.max(i,h[3])}return[t,s,e,i]}#U(){return this.#a?Math.ceil(this.thickness*this.parentScale):0}#M(t=!1){if(this.isEmpty())return;if(!this.#a){this.#v();return}const e=this.#H(),s=this.#U();this.#e=Math.max(k.MIN_SIZE,e[2]-e[0]),this.#t=Math.max(k.MIN_SIZE,e[3]-e[1]);const i=Math.ceil(s+this.#e*this.scaleFactor),n=Math.ceil(s+this.#t*this.scaleFactor),[a,r]=this.parentDimensions;this.width=i/a,this.height=n/r,this.setAspectRatio(i,n);const o=this.translationX,l=this.translationY;this.translationX=-e[0],this.translationY=-e[1],this.#_(),this.#v(),this.#d=i,this.#r=n,this.setDims(i,n);const h=t?s/this.scaleFactor/2:0;this.translate(o-this.translationX-h,l-this.translationY-h)}static async deserialize(t,e,s){if(t instanceof ls)return null;const i=await super.deserialize(t,e,s);i.thickness=t.thickness,i.color=S.makeHexColor(...t.color),i.opacity=t.opacity;const[n,a]=i.pageDimensions,r=i.width*n,o=i.height*a,l=i.parentScale,h=t.thickness/2;i.#a=!0,i.#d=Math.round(r),i.#r=Math.round(o);const{paths:d,rect:u,rotation:f}=t;for(let{bezier:g}of d){g=Z.#B(g,u,f);const b=[];i.paths.push(b);let m=l*(g[0]-h),A=l*(g[1]-h);for(let _=2,v=g.length;_<v;_+=6){const w=l*(g[_]-h),E=l*(g[_+1]-h),C=l*(g[_+2]-h),x=l*(g[_+3]-h),O=l*(g[_+4]-h),P=l*(g[_+5]-h);b.push([[m,A],[w,E],[C,x],[O,P]]),m=O,A=P}const y=this.#O(b);i.bezierPath2D.push(y)}const p=i.#H();return i.#e=Math.max(k.MIN_SIZE,p[2]-p[0]),i.#t=Math.max(k.MIN_SIZE,p[3]-p[1]),i.#I(r,o),i}serialize(){if(this.isEmpty())return null;const t=this.getRect(0,0),e=k._colorManager.convert(this.ctx.strokeStyle);return{annotationType:I.INK,color:e,thickness:this.thickness,opacity:this.opacity,paths:this.#N(this.scaleFactor/this.parentScale,this.translationX,this.translationY,t),pageIndex:this.pageIndex,rect:t,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}}class hs extends k{#t=null;#e=null;#s=null;#n=null;#a=null;#i="";#l=null;#h=null;#c=null;#o=!1;#d=!1;static _type="stamp";static _editorType=I.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#n=t.bitmapUrl,this.#a=t.bitmapFile}static initialize(t,e){k.initialize(t,e)}static get supportedTypes(){return D(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(e=>`image/${e}`))}static get supportedTypesStr(){return D(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(I.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}}#r(t,e=!1){if(!t){this.remove();return}this.#t=t.bitmap,e||(this.#e=t.id,this.#o=t.isSvg),t.file&&(this.#i=t.file.name),this.#f()}#u(){if(this.#s=null,this._uiManager.enableWaiting(!1),!!this.#l){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){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:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await s.guess({name:"altText",request:{data:i,width:n,height:a,channels:i.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#p(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(s=>this.#r(s,!0)).finally(()=>this.#u());return}if(this.#n){const s=this.#n;this.#n=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(s).then(i=>this.#r(i)).finally(()=>this.#u());return}if(this.#a){const s=this.#a;this.#a=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(s).then(i=>this.#r(i)).finally(()=>this.#u());return}const t=document.createElement("input");t.type="file",t.accept=hs.supportedTypesStr;const e=this._uiManager._signal;this.#s=new Promise(s=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#r(i)}s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#u()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#l?.remove(),this.#l=null,this.#h?.disconnect(),this.#h=null,this.#c&&(clearTimeout(this.#c),this.#c=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#p();return}super.rebuild(),this.div!==null&&(this.#e&&this.#l===null&&this.#p(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#n||this.#a||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#t?this.#f():this.#p(),this.width&&!this.annotationElementId){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i)}return this.div}#f(){const{div:t}=this;let{width:e,height:s}=this.#t;const[i,n]=this.pageDimensions,a=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>a*i||s>a*n){const h=Math.min(a*i/e,a*n/s);e*=h,s*=h}const[r,o]=this.parentDimensions;this.setDims(e*r/i,s*o/n),this._uiManager.enableWaiting(!1);const l=this.#l=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),this.#g(e,s),this.#y(),this.#d||(this.parent.addUndoableEditor(this),this.#d=!0),this._reportTelemetry({action:"inserted_image"}),this.#i&&l.setAttribute("aria-label",this.#i)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,a=new ze;let r=this.#t,o=i,l=n,h=null;if(e){if(i>e||n>e){const w=Math.min(e/i,e/n);o=Math.floor(i*w),l=Math.floor(n*w)}h=document.createElement("canvas");const u=h.width=Math.ceil(o*a.sx),f=h.height=Math.ceil(l*a.sy);this.#o||(r=this.#m(u,f));const p=h.getContext("2d");p.filter=this._uiManager.hcmFilter;let g="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(g="#8f8f9d",b="#42414d");const m=15,A=m*a.sx,y=m*a.sy,_=new OffscreenCanvas(A*2,y*2),v=_.getContext("2d");v.fillStyle=g,v.fillRect(0,0,A*2,y*2),v.fillStyle=b,v.fillRect(0,0,A,y),v.fillRect(A,y,A,y),p.fillStyle=p.createPattern(_,"repeat"),p.fillRect(0,0,u,f),p.drawImage(r,0,0,r.width,r.height,0,0,u,f)}let d=null;if(s){let u,f;if(a.symmetric&&r.width<t&&r.height<t)u=r.width,f=r.height;else if(r=this.#t,i>t||n>t){const b=Math.min(t/i,t/n);u=Math.floor(i*b),f=Math.floor(n*b),this.#o||(r=this.#m(u,f))}const g=new OffscreenCanvas(u,f).getContext("2d",{willReadFrequently:!0});g.drawImage(r,0,0,r.width,r.height,0,0,u,f),d={width:u,height:f,data:g.getImageData(0,0,u,f).data}}return{canvas:h,width:o,height:l,imageData:d}}#b(t,e){const[s,i]=this.parentDimensions;this.width=t/s,this.height=e/i,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this.#c!==null&&clearTimeout(this.#c);const n=200;this.#c=setTimeout(()=>{this.#c=null,this.#g(t,e)},n)}#m(t,e){const{width:s,height:i}=this.#t;let n=s,a=i,r=this.#t;for(;n>2*t||a>2*e;){const o=n,l=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const h=new OffscreenCanvas(n,a);h.getContext("2d").drawImage(r,0,0,o,l,0,0,n,a),r=h.transferToImageBitmap()}return r}#g(t,e){const s=new ze,i=Math.ceil(t*s.sx),n=Math.ceil(e*s.sy),a=this.#l;if(!a||a.width===i&&a.height===n)return;a.width=i,a.height=n;const r=this.#o?this.#t:this.#m(i,n),o=a.getContext("2d");o.filter=this._uiManager.hcmFilter,o.drawImage(r,0,0,r.width,r.height,0,0,i,n)}getImageForAltText(){return this.#l}#A(t){if(t){if(this.#o){const i=this._uiManager.imageManager.getSvgUrl(this.#e);if(i)return i}const e=document.createElement("canvas");return{width:e.width,height:e.height}=this.#t,e.getContext("2d").drawImage(this.#t,0,0),e.toDataURL()}if(this.#o){const[e,s]=this.pageDimensions,i=Math.round(this.width*e*qt.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*qt.PDF_TO_CSS_UNITS),a=new OffscreenCanvas(i,n);return a.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,i,n),a.transferToImageBitmap()}return structuredClone(this.#t)}#y(){this._uiManager._signal&&(this.#h=new ResizeObserver(t=>{const e=t[0].contentRect;e.width&&e.height&&this.#b(e.width,e.height)}),this.#h.observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{this.#h?.disconnect(),this.#h=null},{once:!0}))}static async deserialize(t,e,s){let i=null;if(t instanceof ni){const{data:{rect:p,rotation:g,id:b,structParent:m,popupRef:A},container:y,parent:{page:{pageNumber:_}}}=t,v=y.querySelector("canvas"),w=s.imageManager.getFromCanvas(y.id,v);v.remove();const E=(await e._structTree.getAriaAttributes(`${Xe}${b}`))?.get("aria-label")||"";i=t={annotationType:I.STAMP,bitmapId:w.id,bitmap:w.bitmap,pageIndex:_-1,rect:p.slice(0),rotation:g,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:E},isSvg:!1,structParent:m,popupRef:A}}const n=await super.deserialize(t,e,s),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:d}=t;l&&s.imageManager.isValidId(l)?(n.#e=l,r&&(n.#t=r)):n.#n=o,n.#o=h;const[u,f]=n.pageDimensions;return n.width=(a[2]-a[0])/u,n.height=(a[3]-a[1])/f,n.annotationElementId=t.id||null,d&&(n.altTextData=d),n._initialData=i,n.#d=!!i,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:I.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#o,structTreeParentId:this._structTreeParentId};if(t)return s.bitmapUrl=this.#A(!0),s.accessibilityData=this.serializeAltText(!0),s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const r=this.#C(s);if(r.isSame)return null;r.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1}if(s.id=this.annotationElementId,e===null)return s;e.stamps||=new Map;const a=this.#o?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(!e.stamps.has(this.#e))e.stamps.set(this.#e,{area:a,serialized:s}),s.bitmap=this.#A(!1);else if(this.#o){const r=e.stamps.get(this.#e);a>r.area&&(r.area=a,r.serialized.bitmap.close(),r.serialized.bitmap=this.#A(!1))}return s}#C(t){const{rect:e,pageIndex:s,accessibilityData:{altText:i}}=this._initialData,n=t.rect.every((o,l)=>Math.abs(o-e[l])<1),a=t.pageIndex===s,r=(t.accessibilityData?.alt||"")===i;return{isSame:n&&a&&r,isSameAltText:r}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class St{#t;#e=!1;#s=null;#n=null;#a=null;#i=new Map;#l=!1;#h=!1;#c=!1;#o=null;#d=null;#r;static _initialized=!1;static#u=new Map([Q,Z,hs,W].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...St.#u.values()];if(!St._initialized){St._initialized=!0;for(const u of d)u.initialize(h,t)}t.registerEditorTypes(d),this.#r=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=a,this.viewport=l,this.#o=o,this.drawLayer=r,this._structTree=i,this.#r.addLayer(this)}get isEmpty(){return this.#i.size===0}get isInvisible(){return this.isEmpty&&this.#r.getMode()===I.NONE}updateToolbar(t){this.#r.updateToolbar(t)}updateMode(t=this.#r.getMode()){switch(this.#g(),t){case I.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case I.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case I.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;for(const s of St.#u.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#o?.div}addInkEditorIfNeeded(t){if(this.#r.getMode()!==I.INK)return;if(!t){for(const s of this.#i.values())if(s.isEmpty()){s.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){this.#r.setEditingState(t)}addCommands(t){this.#r.addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#s?.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of this.#i.values())s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#r.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!this.#s)return;const e=this.#s.getEditableAnnotations();for(const s of e){if(s.hide(),this.#r.isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}}disable(){this.#c=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#i.values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()}if(this.#s){const i=this.#s.getEditableAnnotations();for(const n of i){const{id:a}=n.data;if(this.#r.isDeletedAnnotationElement(a))continue;let r=e.get(a);if(r){r.resetAnnotationElement(n),r.show(!1),n.show();continue}r=t.get(a),r&&(this.#r.addChangedExistingAnnotation(r),r.renderAnnotationElement(n)&&r.show(!1)),n.show()}}this.#g(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of St.#u.values())s.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#c=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#r.getActive()!==t&&this.#r.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#o?.div&&!this.#d){this.#d=new AbortController;const t=this.#r.combinedSignal(this.#d);this.#o.div.addEventListener("pointerdown",this.#p.bind(this),{signal:t}),this.#o.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#o?.div&&this.#d&&(this.#d.abort(),this.#d=null,this.#o.div.classList.remove("highlighting"))}#p(t){this.#r.unselectAll();const{target:e}=t;if(e===this.#o.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&this.#o.div.contains(e)){const{isMac:s}=rt.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#r.showAllEditors("highlight",!0,!0),this.#o.div.classList.add("free"),this.toggleDrawing(),W.startHighlighting(this,this.#r.direction==="ltr",{target:this.#o.div,x:t.x,y:t.y}),this.#o.div.addEventListener("pointerup",()=>{this.#o.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#r._signal}),t.preventDefault()}}enableClick(){if(this.#n)return;this.#n=new AbortController;const t=this.#r.combinedSignal(this.#n);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){this.#n?.abort(),this.#n=null}attach(t){this.#i.set(t.id,t);const{annotationElementId:e}=t;e&&this.#r.isDeletedAnnotationElement(e)&&this.#r.removeDeletedAnnotationElement(t)}detach(t){this.#i.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#c&&t.annotationElementId&&this.#r.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#r.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,this.#h||this.addInkEditorIfNeeded(!1)}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#r.addDeletedAnnotationElement(t.annotationElementId),k.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),this.#r.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),this.#r.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#a&&(t._focusEventsAllowed=!1,this.#a=setTimeout(()=>{this.#a=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#r._signal}),e.focus())},0)),t._structTreeParentId=this.#t?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const e=()=>t._uiManager.rebuild(t),s=()=>{t.remove()};this.addCommands({cmd:e,undo:s,mustExec:!1})}getNextId(){return this.#r.getId()}get#f(){return St.#u.get(this.#r.getMode())}combinedSignal(t){return this.#r.combinedSignal(t)}#b(t){const e=this.#f;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#f?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#r.updateToolbar(t),this.#r.updateMode(t);const{offsetX:s,offsetY:i}=this.#m(),n=this.getNextId(),a=this.#b({parent:this,id:n,x:s,y:i,uiManager:this.#r,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await St.#u.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#r)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#b({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#r,isCentered:e,...s});return n&&this.add(n),n}#m(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=Math.min(window.innerWidth,t+s),o=Math.min(window.innerHeight,e+i),l=(n+r)/2-t,h=(a+o)/2-e,[d,u]=this.viewport.rotation%180===0?[l,h]:[h,l];return{offsetX:d,offsetY:u}}addNewEditor(){this.createAndAddNewEditor(this.#m(),!0)}setSelected(t){this.#r.setSelected(t)}toggleSelected(t){this.#r.toggleSelected(t)}unselect(t){this.#r.unselect(t)}pointerup(t){const{isMac:e}=rt.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&this.#l){if(this.#l=!1,!this.#e){this.#e=!0;return}if(this.#r.getMode()===I.STAMP){this.#r.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#r.getMode()===I.HIGHLIGHT&&this.enableTextSelection(),this.#l){this.#l=!1;return}const{isMac:e}=rt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;this.#l=!0;const s=this.#r.getActive();this.#e=!s||s.isEmpty()}findNewParent(t,e,s){const i=this.#r.findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}destroy(){this.#r.getActive()?.parent===this&&(this.#r.commitOrRemove(),this.#r.setActiveEditor(null)),this.#a&&(clearTimeout(this.#a),this.#a=null);for(const t of this.#i.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#i.clear(),this.#r.removeLayer(this)}#g(){this.#h=!0;for(const t of this.#i.values())t.isEmpty()&&t.remove();this.#h=!1}render({viewport:t}){this.viewport=t,Ft(this.div,t);for(const e of this.#r.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#r.commitOrRemove(),this.#g();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,Ft(this.div,{rotation:s}),e!==s)for(const i of this.#i.values())i.rotate(s);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#r.viewParameters.realScale}}class st{#t=null;#e=0;#s=new Map;#n=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(!this.#t){this.#t=t;return}if(this.#t!==t){if(this.#s.size>0)for(const e of this.#s.values())e.remove(),t.append(e);this.#t=t}}static get _svgFactory(){return D(this,"_svgFactory",new os)}static#a(t,{x:e=0,y:s=0,width:i=1,height:n=1}={}){const{style:a}=t;a.top=`${100*s}%`,a.left=`${100*e}%`,a.width=`${100*i}%`,a.height=`${100*n}%`}#i(t){const e=st._svgFactory.create(1,1,!0);return this.#t.append(e),e.setAttribute("aria-hidden",!0),st.#a(e,t),e}#l(t,e){const s=st._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=st._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}draw(t,e,s,i=!1){const n=this.#e++,a=this.#i(t.box);a.classList.add(...t.classNamesForDrawing);const r=st._svgFactory.createElement("defs");a.append(r);const o=st._svgFactory.createElement("path");r.append(o);const l=`path_p${this.pageIndex}_${n}`;o.setAttribute("id",l),o.setAttribute("d",t.toSVGPath()),i&&this.#n.set(n,o);const h=this.#l(r,l),d=st._svgFactory.createElement("use");return a.append(d),a.setAttribute("fill",e),a.setAttribute("fill-opacity",s),d.setAttribute("href",`#${l}`),this.#s.set(n,a),{id:n,clipPathId:`url(#${h})`}}drawOutline(t){const e=this.#e++,s=this.#i(t.box);s.classList.add(...t.classNamesForOutlining);const i=st._svgFactory.createElement("defs");s.append(i);const n=st._svgFactory.createElement("path");i.append(n);const a=`path_p${this.pageIndex}_${e}`;n.setAttribute("id",a),n.setAttribute("d",t.toSVGPath()),n.setAttribute("vector-effect","non-scaling-stroke");let r;if(t.mustRemoveSelfIntersections){const h=st._svgFactory.createElement("mask");i.append(h),r=`mask_p${this.pageIndex}_${e}`,h.setAttribute("id",r),h.setAttribute("maskUnits","objectBoundingBox");const d=st._svgFactory.createElement("rect");h.append(d),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("fill","white");const u=st._svgFactory.createElement("use");h.append(u),u.setAttribute("href",`#${a}`),u.setAttribute("stroke","none"),u.setAttribute("fill","black"),u.setAttribute("fill-rule","nonzero"),u.classList.add("mask")}const o=st._svgFactory.createElement("use");s.append(o),o.setAttribute("href",`#${a}`),r&&o.setAttribute("mask",`url(#${r})`);const l=o.cloneNode();return s.append(l),o.classList.add("mainOutline"),l.classList.add("secondaryOutline"),this.#s.set(e,s),e}finalizeLine(t,e){const s=this.#n.get(t);this.#n.delete(t),this.updateBox(t,e.box),s.setAttribute("d",e.toSVGPath())}updateLine(t,e){this.#s.get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}updatePath(t,e){this.#n.get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){st.#a(this.#s.get(t),e)}show(t,e){this.#s.get(t).classList.toggle("hidden",!e)}rotate(t,e){this.#s.get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){this.#s.get(t).setAttribute("fill",e)}changeOpacity(t,e){this.#s.get(t).setAttribute("fill-opacity",e)}addClass(t,e){this.#s.get(t).classList.add(e)}removeClass(t,e){this.#s.get(t).classList.remove(e)}getSVGRoot(t){return this.#s.get(t)}remove(t){this.#n.delete(t),this.#t!==null&&(this.#s.get(t).remove(),this.#s.delete(t))}destroy(){this.#t=null;for(const t of this.#s.values())t.remove();this.#s.clear(),this.#n.clear()}}var da=M.AbortException,ua=M.AnnotationEditorLayer,fa=M.AnnotationEditorParamsType,pa=M.AnnotationEditorType,ga=M.AnnotationEditorUIManager,ma=M.AnnotationLayer,ba=M.AnnotationMode,Aa=M.ColorPicker,_a=M.DOMSVGFactory,ya=M.DrawLayer,va=M.FeatureTest,wa=M.GlobalWorkerOptions,Ea=M.ImageKind,Sa=M.InvalidPDFException,xa=M.MissingPDFException,Ca=M.OPS,Ta=M.OutputScale,ka=M.PDFDataRangeTransport,Ra=M.PDFDateString,Ma=M.PDFWorker,Pa=M.PasswordResponses,La=M.PermissionFlag,Ia=M.PixelsPerInch,Fa=M.RenderingCancelledException,Da=M.TextLayer,Oa=M.UnexpectedResponseException,Na=M.Util,Ha=M.VerbosityLevel,Ba=M.XfaLayer,za=M.build,Ua=M.createValidAbsoluteUrl,ja=M.fetchData,Ga=M.getDocument,$a=M.getFilenameFromUrl,Wa=M.getPdfFilenameFromUrl,Va=M.getXfaPageViewport,qa=M.isDataScheme,Xa=M.isPdfFile,Ya=M.noContextMenu,Ka=M.normalizeUnicode,Qa=M.setLayerDimensions,Ja=M.shadow,Za=M.version;export{da as AbortException,ua as AnnotationEditorLayer,fa as AnnotationEditorParamsType,pa as AnnotationEditorType,ga as AnnotationEditorUIManager,ma as AnnotationLayer,ba as AnnotationMode,Aa as ColorPicker,_a as DOMSVGFactory,ya as DrawLayer,va as FeatureTest,wa as GlobalWorkerOptions,Ea as ImageKind,Sa as InvalidPDFException,xa as MissingPDFException,Ca as OPS,Ta as OutputScale,ka as PDFDataRangeTransport,Ra as PDFDateString,Ma as PDFWorker,Pa as PasswordResponses,La as PermissionFlag,Ia as PixelsPerInch,Fa as RenderingCancelledException,Da as TextLayer,Oa as UnexpectedResponseException,Na as Util,Ha as VerbosityLevel,Ba as XfaLayer,za as build,Ua as createValidAbsoluteUrl,ja as fetchData,Ga as getDocument,$a as getFilenameFromUrl,Wa as getPdfFilenameFromUrl,Va as getXfaPageViewport,qa as isDataScheme,Xa as isPdfFile,Ya as noContextMenu,Ka as normalizeUnicode,Qa as setLayerDimensions,Ja as shadow,Za as version};