1 |
- "use strict";(self.webpackChunkamis_editor_demo=self.webpackChunkamis_editor_demo||[]).push([[9304],{89304:function(t,e,s){s.r(e),s.d(e,{default:function(){return Sn}});var i={};s.r(i),s.d(i,{dU:function(){return yi},ng:function(){return Ai},EA:function(){return wi},Tm:function(){return xi},D6:function(){return _i},YE:function(){return Ei}});var n=s(3460),a=s(69291),r=s(47659),o={d:(t,e)=>{for(var s in e)o.o(e,s)&&!o.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},h=globalThis.pdfjsLib={};o.d(h,{AbortException:()=>B,AnnotationEditorLayer:()=>bi,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>g,AnnotationEditorUIManager:()=>Rt,AnnotationLayer:()=>ai,AnnotationMode:()=>p,CMapCompressionType:()=>y,ColorPicker:()=>pi,DOMSVGFactory:()=>at,DrawLayer:()=>vi,FeatureTest:()=>$,GlobalWorkerOptions:()=>Ae,ImageKind:()=>b,InvalidPDFException:()=>D,MissingPDFException:()=>F,OPS:()=>A,Outliner:()=>hi,PDFDataRangeTransport:()=>us,PDFDateString:()=>bt,PDFWorker:()=>bs,PasswordResponses:()=>w,PermissionFlag:()=>f,PixelsPerInch:()=>et,RenderingCancelledException:()=>ot,TextLayer:()=>ts,UnexpectedResponseException:()=>O,Util:()=>V,VerbosityLevel:()=>v,XfaLayer:()=>Ms,build:()=>Es,createValidAbsoluteUrl:()=>k,fetchData:()=>st,getDocument:()=>ls,getFilenameFromUrl:()=>ct,getPdfFilenameFromUrl:()=>dt,getXfaPageViewport:()=>vt,isDataScheme:()=>ht,isPdfFile:()=>lt,noContextMenu:()=>gt,normalizeUnicode:()=>q,renderTextLayer:()=>es,setLayerDimensions:()=>xt,shadow:()=>P,updateTextLayer:()=>ss,version:()=>_s});const l=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),c=[1,0,0,1,0,0],d=[.001,0,0,.001,0,0],u=1.35,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={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},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},v={ERRORS:0,WARNINGS:1,INFOS:5},y={NONE:0,BINARY:1},A={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},w={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let x=v.WARNINGS;function _(t){Number.isInteger(t)&&(x=t)}function E(){return x}function C(t){x>=v.INFOS&&console.log(`Info: ${t}`)}function S(t){x>=v.WARNINGS&&console.log(`Warning: ${t}`)}function T(t){throw new Error(t)}function M(t,e){t||T(e)}function k(t,e=null,s=null){if(!t)return null;try{if(s&&"string"==typeof t){if(s.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(s.tryConvertEncoding)try{t=decodeURIComponent(escape(t))}catch{}}const i=e?new URL(t,e):new URL(t);if(function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(i))return i}catch{}return null}function P(t,e,s,i=!1){return Object.defineProperty(t,e,{value:s,enumerable:!i,configurable:!0,writable:!1}),s}const R=function(){function t(e,s){this.constructor===t&&T("Cannot initialize BaseException."),this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class L extends R{constructor(t,e){super(t,"PasswordException"),this.code=e}}class I extends R{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class D extends R{constructor(t){super(t,"InvalidPDFException")}}class F extends R{constructor(t){super(t,"MissingPDFException")}}class O extends R{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class N extends R{constructor(t){super(t,"FormatError")}}class B extends R{constructor(t){super(t,"AbortException")}}function H(t){"object"==typeof t&&void 0!==t?.length||T("Invalid argument for bytesToString");const e=t.length,s=8192;if(e<s)return String.fromCharCode.apply(null,t);const i=[];for(let n=0;n<e;n+=s){const a=Math.min(n+s,e),r=t.subarray(n,a);i.push(String.fromCharCode.apply(null,r))}return i.join("")}function z(t){"string"!=typeof t&&T("Invalid argument for stringToBytes");const e=t.length,s=new Uint8Array(e);for(let i=0;i<e;++i)s[i]=255&t.charCodeAt(i);return s}function j(t){const e=Object.create(null);for(const[s,i]of t)e[s]=i;return e}class ${static get isLittleEndian(){return P(this,"isLittleEndian",function(){const t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return P(this,"isEvalSupported",function(){try{return new Function(""),!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return P(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?P(this,"platform",{isMac:navigator.platform.includes("Mac")}):P(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return P(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const U=Array.from(Array(256).keys(),(t=>t.toString(16).padStart(2,"0")));class V{static makeHexColor(t,e,s){return`#${U[t]}${U[e]}${U[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){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s]}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,h=r+o||1,l=r-o||1;return[Math.sqrt(h),Math.sqrt(l)]}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,h,l){if(h<=0||h>=1)return;const c=1-h,d=h*h,u=d*h,p=c*(c*(c*t+3*h*e)+3*d*s)+u*i,g=c*(c*(c*n+3*h*a)+3*d*r)+u*o;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],g),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],g)}static#e(t,e,s,i,n,a,r,o,h,l,c,d){if(Math.abs(h)<1e-12)return void(Math.abs(l)>=1e-12&&this.#t(t,e,s,i,n,a,r,o,-c/l,d));const u=l**2-4*c*h;if(u<0)return;const p=Math.sqrt(u),g=2*h;this.#t(t,e,s,i,n,a,r,o,(-l+p)/g,d),this.#t(t,e,s,i,n,a,r,o,(-l-p)/g,d)}static bezierBoundingBox(t,e,s,i,n,a,r,o,h){return h?(h[0]=Math.min(h[0],t,r),h[1]=Math.min(h[1],e,o),h[2]=Math.max(h[2],t,r),h[3]=Math.max(h[3],e,o)):h=[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*(3*(s-n)-t+r),6*(t-2*s+n),3*(s-t),h),this.#e(t,s,n,r,e,i,a,o,3*(3*(i-a)-e+o),6*(e-2*i+a),3*(i-e),h),h}}let G=null,W=null;function q(t){return G||(G=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,W=new Map([["ſt","ſt"]])),t.replaceAll(G,((t,e,s)=>e?e.normalize("NFKC"):W.get(s)))}const K="pdfjs_internal_id_";class X{constructor(){this.constructor===X&&T("Cannot initialize BaseFilterFactory.")}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 Y{constructor(){this.constructor===Y&&T("Cannot initialize BaseCanvasFactory.")}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")}}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){T("Abstract method `_createCanvas` called.")}}class Q{constructor({baseUrl:t=null,isCompressed:e=!0}){this.constructor===Q&&T("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, 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":""),s=this.isCompressed?y.BINARY:y.NONE;return this._fetchData(e,s).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}_fetchData(t,e){T("Abstract method `_fetchData` called.")}}class J{constructor({baseUrl:t=null}){this.constructor===J&&T("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, 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._fetchData(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}_fetchData(t){T("Abstract method `_fetchData` called.")}}class Z{constructor(){this.constructor===Z&&T("Cannot initialize BaseSVGFactory.")}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("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){T("Abstract method `_createSVG` called.")}}const tt="http://www.w3.org/2000/svg";class et{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function st(t,e="text"){if(pt(t,document.baseURI)){const s=await fetch(t);if(!s.ok)throw new Error(s.statusText);switch(e){case"arraybuffer":return s.arrayBuffer();case"blob":return s.blob();case"json":return s.json()}return s.text()}return new Promise(((s,i)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)i(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void s(n.response)}s(n.responseText)}},n.send(null)}))}class it extends Q{_fetchData(t,e){return st(t,this.isCompressed?"arraybuffer":"text").then((t=>({cMapData:t instanceof ArrayBuffer?new Uint8Array(t):z(t),compressionType:e})))}}class nt extends J{_fetchData(t){return st(t,"arraybuffer").then((t=>new Uint8Array(t)))}}class at extends Z{_createSVG(t){return document.createElementNS(tt,t)}}class rt{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 h,l,c,d,u,p,g,m;switch((s%=360)<0&&(s+=360),s){case 180:h=-1,l=0,c=0,d=1;break;case 90:h=0,l=1,c=1,d=0;break;case 270:h=0,l=-1,c=-1,d=0;break;case 0:h=1,l=0,c=0,d=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(c=-c,d=-d),0===h?(u=Math.abs(o-t[1])*e+i,p=Math.abs(r-t[0])*e+n,g=(t[3]-t[1])*e,m=(t[2]-t[0])*e):(u=Math.abs(r-t[0])*e+i,p=Math.abs(o-t[1])*e+n,g=(t[2]-t[0])*e,m=(t[3]-t[1])*e),this.transform=[h*e,l*e,c*e,d*e,u-h*e*r-c*e*o,p-l*e*r-d*e*o],this.width=g,this.height=m}get rawDims(){const{viewBox:t}=this;return P(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 rt({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return V.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=V.applyTransform([t[0],t[1]],this.transform),s=V.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return V.applyInverseTransform([t,e],this.transform)}}class ot extends R{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function ht(t){const e=t.length;let s=0;for(;s<e&&""===t[s].trim();)s++;return"data:"===t.substring(s,s+5).toLowerCase()}function lt(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function ct(t){return[t]=t.split(/[#?]/,1),t.substring(t.lastIndexOf("/")+1)}function dt(t,e="document.pdf"){if("string"!=typeof t)return e;if(ht(t))return S('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;const s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(t);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||e}class ut{started=Object.create(null);times=[];time(t){t in this.started&&S(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||S(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms\n`);return t.join("")}}function pt(t,e){try{const{protocol:s}=e?new URL(t,e):new URL(t);return"http:"===s||"https:"===s}catch{return!1}}function gt(t){t.preventDefault()}function mt(t){console.log("Deprecated API usage: "+t)}let ft;class bt{static toDateObject(t){if(!t||"string"!=typeof t)return null;ft||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=ft.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 h=e[7]||"Z";let l=parseInt(e[8],10);l=l>=0&&l<=23?l:0;let c=parseInt(e[9],10)||0;return c=c>=0&&c<=59?c:0,"-"===h?(a+=l,r+=c):"+"===h&&(a-=l,r-=c),new Date(Date.UTC(s,i,n,a,r,o))}}function vt(t,{scale:e=1,rotation:s=0}){const{width:i,height:n}=t.attributes.style,a=[0,0,parseInt(i),parseInt(n)];return new rt({viewBox:a,scale:e,rotation:s})}function yt(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map((t=>parseInt(t))):t.startsWith("rgba(")?t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3):(S(`Not a valid color format: "${t}"`),[0,0,0])}function At(t){const{a:e,b:s,c:i,d:n,e:a,f:r}=t.getTransform();return[e,s,i,n,a,r]}function wt(t){const{a:e,b:s,c:i,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,s,i,n,a,r]}function xt(t,e,s=!1,i=!0){if(e instanceof rt){const{pageWidth:i,pageHeight:n}=e.rawDims,{style:a}=t,r=$.isCSSRoundSupported,o=`var(--scale-factor) * ${i}px`,h=`var(--scale-factor) * ${n}px`,l=r?`round(${o}, 1px)`:`calc(${o})`,c=r?`round(${h}, 1px)`:`calc(${h})`;s&&e.rotation%180!=0?(a.width=c,a.height=l):(a.width=l,a.height=c)}i&&t.setAttribute("data-main-rotation",e.rotation)}class _t{#s=null;#i=null;#n;#a=null;constructor(t){this.#n=t}render(){const t=this.#s=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",gt),t.addEventListener("pointerdown",_t.#r);const e=this.#a=document.createElement("div");e.className="buttons",t.append(e);const s=this.#n.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#n._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return this.#o(),t}static#r(t){t.stopPropagation()}#h(t){this.#n._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()}#l(t){this.#n._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()}#c(t){t.addEventListener("focusin",this.#h.bind(this),{capture:!0}),t.addEventListener("focusout",this.#l.bind(this),{capture:!0}),t.addEventListener("contextmenu",gt)}hide(){this.#s.classList.add("hidden"),this.#i?.hideDropdown()}show(){this.#s.classList.remove("hidden")}#o(){const t=document.createElement("button");t.className="delete",t.tabIndex=0,t.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#n.editorType}-button`),this.#c(t),t.addEventListener("click",(t=>{this.#n._uiManager.delete()})),this.#a.append(t)}get#d(){const t=document.createElement("div");return t.className="divider",t}addAltTextButton(t){this.#c(t),this.#a.prepend(t,this.#d)}addColorPicker(t){this.#i=t;const e=t.renderButton();this.#c(e),this.#a.prepend(e,this.#d)}remove(){this.#s.remove(),this.#i?.destroy(),this.#i=null}}class Et{#a=null;#s=null;#u;constructor(t){this.#u=t}#p(){const t=this.#s=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",gt);const e=this.#a=document.createElement("div");return e.className="buttons",t.append(e),this.#g(),t}#m(t,e){let s=0,i=0;for(const n of t){const t=n.y+n.height;if(t<s)continue;const a=n.x+(e?n.width:0);t>s?(i=a,s=t):e?a>i&&(i=a):a<i&&(i=a)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#m(e,s),{style:a}=this.#s||=this.#p();t.append(this.#s),a.insetInlineEnd=100*i+"%",a.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#s.remove()}#g(){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"),t.addEventListener("contextmenu",gt),t.addEventListener("click",(()=>{this.#u.highlightSelection("floating_button")})),this.#a.append(t)}}function Ct(t,e,s){for(const i of s)e.addEventListener(i,t[i].bind(t))}class St{#f=0;get id(){return"pdfjs_internal_editor_"+this.#f++}}class Tt{#b=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<32;e++)t[e]=Math.floor(255*Math.random());return H(t)}();#f=0;#v=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d"),e=new Image;return e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',P(this,"_isSVGFittingCanvas",e.decode().then((()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]))))}async#y(t,e){this.#v||=new Map;let s=this.#v.get(t);if(null===s)return null;if(s?.bitmap)return s.refCounter+=1,s;try{let t;if(s||={bitmap:null,id:`image_${this.#b}_${this.#f++}`,refCounter:0,isSvg:!1},"string"==typeof e?(s.url=e,t=await st(e,"blob")):t=s.file=e,"image/svg+xml"===t.type){const e=Tt._isSVGFittingCanvas,i=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{s.bitmap=n,s.isSvg=!0,t()},i.onload=async()=>{const t=s.svgUrl=i.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=i.onerror=a}));i.readAsDataURL(t),await a}else s.bitmap=await createImageBitmap(t);s.refCounter=1}catch(t){console.error(t),s=null}return this.#v.set(t,s),s&&this.#v.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#y(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#y(t,t)}async getFromId(t){this.#v||=new Map;const e=this.#v.get(t);return e?e.bitmap?(e.refCounter+=1,e):e.file?this.getFromFile(e.file):this.getFromUrl(e.url):null}getSvgUrl(t){const e=this.#v.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#v||=new Map;const e=this.#v.get(t);e&&(e.refCounter-=1,0===e.refCounter&&(e.bitmap=null))}isValidId(t){return t.startsWith(`image_${this.#b}_`)}}class Mt{#A=[];#w=!1;#x;#_=-1;constructor(t=128){this.#x=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(i&&t(),this.#w)return;const o={cmd:t,undo:e,post:s,type:n};if(-1===this.#_)return this.#A.length>0&&(this.#A.length=0),this.#_=0,void this.#A.push(o);if(a&&this.#A[this.#_].type===n)return r&&(o.undo=this.#A[this.#_].undo),void(this.#A[this.#_]=o);const h=this.#_+1;h===this.#x?this.#A.splice(0,1):(this.#_=h,h<this.#A.length&&this.#A.splice(h)),this.#A.push(o)}undo(){if(-1===this.#_)return;this.#w=!0;const{undo:t,post:e}=this.#A[this.#_];t(),e?.(),this.#w=!1,this.#_-=1}redo(){if(this.#_<this.#A.length-1){this.#_+=1,this.#w=!0;const{cmd:t,post:e}=this.#A[this.#_];t(),e?.(),this.#w=!1}}hasSomethingToUndo(){return-1!==this.#_}hasSomethingToRedo(){return this.#_<this.#A.length-1}destroy(){this.#A=null}}class kt{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=$.platform;for(const[s,i,n={}]of t)for(const t of s){const s=t.startsWith("mac+");e&&s?(this.callbacks.set(t.slice(4),{callback:i,options:n}),this.allKeys.add(t.split("+").at(-1))):e||s||(this.callbacks.set(t,{callback:i,options:n}),this.allKeys.add(t.split("+").at(-1)))}}#E(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.#E(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 Pt{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return function(t){const e=document.createElement("span");e.style.visibility="hidden",document.body.append(e);for(const s of t.keys()){e.style.color=s;const i=window.getComputedStyle(e).color;t.set(s,yt(i))}e.remove()}(t),P(this,"_colors",t)}convert(t){const e=yt(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,s]of this._colors)if(s.every(((t,s)=>t===e[s])))return Pt._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?V.makeHexColor(...e):t}}class Rt{#C=null;#S=new Map;#T=new Map;#M=null;#k=null;#P=null;#R=new Mt;#L=0;#I=new Set;#D=null;#F=null;#O=new Set;#N=!1;#B=null;#H=null;#z=null;#j=!1;#$=null;#U=new St;#V=!1;#G=!1;#W=null;#q=null;#K=null;#X=g.NONE;#Y=new Set;#Q=null;#J=null;#Z=null;#tt=this.blur.bind(this);#et=this.focus.bind(this);#st=this.copy.bind(this);#it=this.cut.bind(this);#nt=this.paste.bind(this);#at=this.keydown.bind(this);#rt=this.keyup.bind(this);#ot=this.onEditingAction.bind(this);#ht=this.onPageChanging.bind(this);#lt=this.onScaleChanging.bind(this);#ct=this.#dt.bind(this);#ut=this.onRotationChanging.bind(this);#pt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#gt=[0,0];#mt=null;#ft=null;#bt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Rt.prototype,e=t=>t.#ft.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),s=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return P(this,"_keyboardManager",new kt([[["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:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ft.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ft.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,h){this.#ft=t,this.#bt=e,this.#M=s,this._eventBus=i,this._eventBus._on("editingaction",this.#ot),this._eventBus._on("pagechanging",this.#ht),this._eventBus._on("scalechanging",this.#lt),this._eventBus._on("rotationchanging",this.#ut),this.#vt(),this.#yt(),this.#k=n.annotationStorage,this.#B=n.filterFactory,this.#J=a,this.#z=r||null,this.#N=o,this.#K=h||null,this.viewParameters={realScale:et.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#At(),this.#wt(),this._eventBus._off("editingaction",this.#ot),this._eventBus._off("pagechanging",this.#ht),this._eventBus._off("scalechanging",this.#lt),this._eventBus._off("rotationchanging",this.#ut);for(const t of this.#T.values())t.destroy();this.#T.clear(),this.#S.clear(),this.#O.clear(),this.#C=null,this.#Y.clear(),this.#R.destroy(),this.#M?.destroy(),this.#$?.hide(),this.#$=null,this.#H&&(clearTimeout(this.#H),this.#H=null),this.#mt&&(clearTimeout(this.#mt),this.#mt=null),this.#xt()}async mlGuess(t){return this.#K?.guess(t)||null}get hasMLManager(){return!!this.#K}get hcmFilter(){return P(this,"hcmFilter",this.#J?this.#B.addHCMFilter(this.#J.foreground,this.#J.background):"none")}get direction(){return P(this,"direction",getComputedStyle(this.#ft).direction)}get highlightColors(){return P(this,"highlightColors",this.#z?new Map(this.#z.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return P(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setMainHighlightColorPicker(t){this.#q=t}editAltText(t){this.#M?.editAltText(this,t)}onPageChanging({pageNumber:t}){this.#L=t-1}focusMainContainer(){this.#ft.focus()}findParent(t,e){for(const s of this.#T.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.#bt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#O.add(t)}removeShouldRescale(t){this.#O.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*et.PDF_TO_CSS_UNITS;for(const t of this.#O)t.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#_t({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#_t(e).closest(".textLayer"),h=this.getSelectionBoxes(o);if(h){e.empty(),this.#X===g.NONE&&(this._eventBus.dispatch("showannotationeditorui",{source:this,mode:g.HIGHLIGHT}),this.showAllEditors("highlight",!0,!0));for(const e of this.#T.values())if(e.hasTextLayer(o)){e.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:a,text:r});break}}}#Et(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#_t(t).closest(".textLayer"),s=this.getSelectionBoxes(e);s&&(this.#$||=new Et(this),this.#$.show(e,s,"ltr"===this.direction))}addToAnnotationStorage(t){t.isEmpty()||!this.#k||this.#k.has(t.id)||this.#k.setValue(t.id,t)}#dt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#Q&&(this.#$?.hide(),this.#Q=null,this.#Ct({hasSelectedText:!1})));const{anchorNode:e}=t;if(e!==this.#Q)if(this.#_t(t).closest(".textLayer")){if(this.#$?.hide(),this.#Q=e,this.#Ct({hasSelectedText:!0}),(this.#X===g.HIGHLIGHT||this.#X===g.NONE)&&(this.#X===g.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#j=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=e=>{"pointerup"===e.type&&0!==e.button||(window.removeEventListener("pointerup",t),window.removeEventListener("blur",t),"pointerup"===e.type&&this.#St("main_toolbar"))};window.addEventListener("pointerup",t),window.addEventListener("blur",t)}}else this.#Q&&(this.#$?.hide(),this.#Q=null,this.#Ct({hasSelectedText:!1}))}#St(t=""){this.#X===g.HIGHLIGHT?this.highlightSelection(t):this.#N&&this.#Et()}#vt(){document.addEventListener("selectionchange",this.#ct)}#xt(){document.removeEventListener("selectionchange",this.#ct)}#Tt(){window.addEventListener("focus",this.#et),window.addEventListener("blur",this.#tt)}#wt(){window.removeEventListener("focus",this.#et),window.removeEventListener("blur",this.#tt)}blur(){if(this.isShiftKeyDown=!1,this.#j&&(this.#j=!1,this.#St("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#Y)if(e.div.contains(t)){this.#W=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#W)return;const[t,e]=this.#W;this.#W=null,e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0}),e.focus()}#yt(){window.addEventListener("keydown",this.#at),window.addEventListener("keyup",this.#rt)}#At(){window.removeEventListener("keydown",this.#at),window.removeEventListener("keyup",this.#rt)}#Mt(){document.addEventListener("copy",this.#st),document.addEventListener("cut",this.#it),document.addEventListener("paste",this.#nt)}#kt(){document.removeEventListener("copy",this.#st),document.removeEventListener("cut",this.#it),document.removeEventListener("paste",this.#nt)}addEditListeners(){this.#yt(),this.#Mt()}removeEditListeners(){this.#At(),this.#kt()}copy(t){if(t.preventDefault(),this.#C?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#Y){const s=t.serialize(!0);s&&e.push(s)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#F)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(t){return void S(`paste: "${t.message}".`)}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const t=[];for(const e of s){const s=i.deserialize(e);if(!s)return;t.push(s)}const e=()=>{for(const e of t)this.#Pt(e);this.#Rt(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){S(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#X===g.NONE||this.isEditorHandlingKeyboard||Rt._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#j&&(this.#j=!1,this.#St("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#Ct(t){Object.entries(t).some((([t,e])=>this.#pt[t]!==e))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#pt,t)}),this.#X===g.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Lt([[m.HIGHLIGHT_FREE,!0]]))}#Lt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Tt(),this.#Mt(),this.#Ct({isEditing:this.#X!==g.NONE,isEmpty:this.#It(),hasSomethingToUndo:this.#R.hasSomethingToUndo(),hasSomethingToRedo:this.#R.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#wt(),this.#kt(),this.#Ct({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#F){this.#F=t;for(const t of this.#F)this.#Lt(t.defaultPropertiesToUpdate)}}getId(){return this.#U.id}get currentLayer(){return this.#T.get(this.#L)}getLayer(t){return this.#T.get(t)}get currentPageIndex(){return this.#L}addLayer(t){this.#T.set(t.pageIndex,t),this.#V?t.enable():t.disable()}removeLayer(t){this.#T.delete(t.pageIndex)}updateMode(t,e=null,s=!1){if(this.#X!==t){if(this.#X=t,t===g.NONE)return this.setEditingState(!1),void this.#Dt();this.setEditingState(!0),this.#Ft(),this.unselectAll();for(const e of this.#T.values())e.updateMode(t);if(e||!s){if(e)for(const t of this.#S.values())if(t.annotationElementId===e){this.setSelected(t),t.enterInEditMode();break}}else this.addNewEditorFromKeyboard()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#X&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#F){switch(t){case m.CREATE:return void this.currentLayer.addNewEditor();case m.HIGHLIGHT_DEFAULT_COLOR:this.#q?.updateColor(e);break;case m.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#Z||=new Map).set(t,e),this.showAllEditors("highlight",e)}for(const s of this.#Y)s.updateParams(t,e);for(const s of this.#F)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const s of this.#S.values())s.editorType===t&&s.show(e);(this.#Z?.get(m.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Lt([[m.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#G!==t){this.#G=t;for(const e of this.#T.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}#Ft(){if(!this.#V){this.#V=!0;for(const t of this.#T.values())t.enable();for(const t of this.#S.values())t.enable()}}#Dt(){if(this.unselectAll(),this.#V){this.#V=!1;for(const t of this.#T.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.#H&&clearTimeout(this.#H),this.#H=setTimeout((()=>{this.focusMainContainer(),this.#H=null}),0)),this.#S.delete(t.id),this.unselect(t),t.annotationElementId&&this.#I.has(t.annotationElementId)||this.#k?.remove(t.id)}addDeletedAnnotationElement(t){this.#I.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#I.has(t)}removeDeletedAnnotationElement(t){this.#I.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#Pt(t){const e=this.#T.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#C!==t&&(this.#C=t,t&&this.#Lt(t.propertiesToUpdate))}get#Ot(){let t=null;for(t of this.#Y);return t}updateUI(t){this.#Ot===t&&this.#Lt(t.propertiesToUpdate)}toggleSelected(t){if(this.#Y.has(t))return this.#Y.delete(t),t.unselect(),void this.#Ct({hasSelectedEditor:this.hasSelection});this.#Y.add(t),t.select(),this.#Lt(t.propertiesToUpdate),this.#Ct({hasSelectedEditor:!0})}setSelected(t){for(const e of this.#Y)e!==t&&e.unselect();this.#Y.clear(),this.#Y.add(t),t.select(),this.#Lt(t.propertiesToUpdate),this.#Ct({hasSelectedEditor:!0})}isSelected(t){return this.#Y.has(t)}get firstSelectedEditor(){return this.#Y.values().next().value}unselect(t){t.unselect(),this.#Y.delete(t),this.#Ct({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#Y.size}get isEnterHandled(){return 1===this.#Y.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#R.undo(),this.#Ct({hasSomethingToUndo:this.#R.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#It()})}redo(){this.#R.redo(),this.#Ct({hasSomethingToUndo:!0,hasSomethingToRedo:this.#R.hasSomethingToRedo(),isEmpty:this.#It()})}addCommands(t){this.#R.add(t),this.#Ct({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#It()})}#It(){if(0===this.#S.size)return!0;if(1===this.#S.size)for(const t of this.#S.values())return t.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...this.#Y];this.addCommands({cmd:()=>{for(const e of t)e.remove()},undo:()=>{for(const e of t)this.#Pt(e)},mustExec:!0})}commitOrRemove(){this.#C?.commitOrRemove()}hasSomethingToControl(){return this.#C||this.hasSelection}#Rt(t){for(const t of this.#Y)t.unselect();this.#Y.clear();for(const e of t)e.isEmpty()||(this.#Y.add(e),e.select());this.#Ct({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#Y)t.commit();this.#Rt(this.#S.values())}unselectAll(){if((!this.#C||(this.#C.commitOrRemove(),this.#X===g.NONE))&&this.hasSelection){for(const t of this.#Y)t.unselect();this.#Y.clear(),this.#Ct({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#gt[0]+=t,this.#gt[1]+=e;const[i,n]=this.#gt,a=[...this.#Y];this.#mt&&clearTimeout(this.#mt),this.#mt=setTimeout((()=>{this.#mt=null,this.#gt[0]=this.#gt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#S.has(t.id)&&t.translateInPage(i,n)},undo:()=>{for(const t of a)this.#S.has(t.id)&&t.translateInPage(-i,-n)},mustExec:!1})}),1e3);for(const s of a)s.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#D=new Map;for(const t of this.#Y)this.#D.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#D)return!1;this.disableUserSelect(!1);const t=this.#D;this.#D=null;let e=!1;for(const[{x:s,y:i,pageIndex:n},a]of t)a.newX=s,a.newY=i,a.newPageIndex=n,e||=s!==a.savedX||i!==a.savedY||n!==a.savedPageIndex;if(!e)return!1;const s=(t,e,s,i)=>{if(this.#S.has(t.id)){const n=this.#T.get(i);n?t._setParentAndPosition(n,e,s):(t.pageIndex=i,t.x=e,t.y=s)}};return this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:n,newPageIndex:a}]of t)s(e,i,n,a)},undo:()=>{for(const[e,{savedX:i,savedY:n,savedPageIndex:a}]of t)s(e,i,n,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#D)for(const s of this.#D.keys())s.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#Y.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#C===t}getActive(){return this.#C}getMode(){return this.#X}get imageManager(){return P(this,"imageManager",new Tt)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let s=0,i=e.rangeCount;s<i;s++)if(!t.contains(e.getRangeAt(s).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=(t,e,r,o)=>({x:(e-i)/a,y:1-(t+r-s)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-s)/n,y:1-(e+o-i)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-i)/a,y:(t-s)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-s)/n,y:(e-i)/a,width:r/n,height:o/a})}const o=[];for(let t=0,s=e.rangeCount;t<s;t++){const s=e.getRangeAt(t);if(!s.collapsed)for(const{x:t,y:e,width:i,height:n}of s.getClientRects())0!==i&&0!==n&&o.push(r(t,e,i,n))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#P||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#P?.delete(t)}renderAnnotationElement(t){const e=this.#P?.get(t.data.id);if(!e)return;const s=this.#k.getRawValue(e);s&&(this.#X!==g.NONE||s.hasBeenModified)&&s.renderAnnotationElement(t)}}class Lt{#Nt="";#Bt=!1;#Ht=null;#zt=null;#jt=null;#$t=!1;#n=null;static _l10nPromise=null;constructor(t){this.#n=t}static initialize(t){Lt._l10nPromise||=t}async render(){const t=this.#Ht=document.createElement("button");t.className="altText";const e=await Lt._l10nPromise.get("pdfjs-editor-alt-text-button-label");t.textContent=e,t.setAttribute("aria-label",e),t.tabIndex="0",t.addEventListener("contextmenu",gt),t.addEventListener("pointerdown",(t=>t.stopPropagation()));const s=t=>{t.preventDefault(),this.#n._uiManager.editAltText(this.#n)};return t.addEventListener("click",s,{capture:!0}),t.addEventListener("keydown",(e=>{e.target===t&&"Enter"===e.key&&(this.#$t=!0,s(e))})),await this.#Ut(),t}finish(){this.#Ht&&(this.#Ht.focus({focusVisible:this.#$t}),this.#$t=!1)}isEmpty(){return!this.#Nt&&!this.#Bt}get data(){return{altText:this.#Nt,decorative:this.#Bt}}set data({altText:t,decorative:e}){this.#Nt===t&&this.#Bt===e||(this.#Nt=t,this.#Bt=e,this.#Ut())}toggle(t=!1){this.#Ht&&(!t&&this.#jt&&(clearTimeout(this.#jt),this.#jt=null),this.#Ht.disabled=!t)}destroy(){this.#Ht?.remove(),this.#Ht=null,this.#zt=null}async#Ut(){const t=this.#Ht;if(!t)return;if(!this.#Nt&&!this.#Bt)return t.classList.remove("done"),void this.#zt?.remove();t.classList.add("done"),Lt._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((e=>{t.setAttribute("aria-label",e)}));let e=this.#zt;if(!e){this.#zt=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip");const s=e.id=`alt-text-tooltip-${this.#n.id}`;t.setAttribute("aria-describedby",s);const i=100;t.addEventListener("mouseenter",(()=>{this.#jt=setTimeout((()=>{this.#jt=null,this.#zt.classList.add("show"),this.#n._reportTelemetry({action:"alt_text_tooltip"})}),i)})),t.addEventListener("mouseleave",(()=>{this.#jt&&(clearTimeout(this.#jt),this.#jt=null),this.#zt?.classList.remove("show")}))}e.innerText=this.#Bt?await Lt._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#Nt,e.parentNode||t.append(e);const s=this.#n.getImageForAltText();s?.setAttribute("aria-describedby",e.id)}}class It{#Vt=null;#Nt=null;#Gt=!1;#Wt=!1;#qt=null;#Kt=null;#Xt=this.focusin.bind(this);#Yt=this.focusout.bind(this);#Qt=null;#Jt="";#Zt=!1;#te=null;#ee=!1;#se=!1;#ie=!1;#ne=null;#ae=0;#re=0;#oe=null;_initialOptions=Object.create(null);_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#he=!1;#le=It._zIndex++;static _borderLineWidth=-1;static _colorManager=new Pt;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=It.prototype._resizeWithKeyboard,e=Rt.TRANSLATE_SMALL,s=Rt.TRANSLATE_BIG;return P(this,"_resizerKeyboardManager",new kt([[["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"],It.prototype._stopResizingWithKeyboard]]))}constructor(t){this.constructor===It&&T("Cannot initialize AnnotationEditor."),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 P(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Dt({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,s){if(It._l10nPromise||=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map((e=>[e,t.get(e.replaceAll(/([A-Z])/g,(t=>`-${t.toLowerCase()}`)))]))),s?.strings)for(const e of s.strings)It._l10nPromise.set(e,t.get(e));if(-1!==It._borderLineWidth)return;const i=getComputedStyle(document.documentElement);It._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){T("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#he}set _isDraggable(t){this.#he=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/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#le}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#ce(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Zt?this.#Zt=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;e?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.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()}#de([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this.fixAndSetPosition()}translate(t,e){this.#de(this.parentDimensions,t,e)}translateInPage(t,e){this.#te||=[this.x,this.y],this.#de(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#te||=[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:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x: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.#te&&(this.#te[0]!==this.x||this.#te[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=It,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))}this.x=i/=e,this.y=n/=s;const[o,h]=this.getBaseTranslation();i+=o,n+=h;const{style:l}=this.div;l.left=`${(100*i).toFixed(2)}%`,l.top=`${(100*n).toFixed(2)}%`,this.moveInDOM()}static#ue(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 It.#ue(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return It.#ue(t,e,360-this.parentRotation)}#pe(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this,i=e*t,n=s*t;return $.isCSSRoundSupported?[Math.round(i),Math.round(n)]:[i,n]}setDims(t,e){const[s,i]=this.parentDimensions;this.div.style.width=`${(100*t/s).toFixed(2)}%`,this.#Wt||(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.#Wt&&e.endsWith("%");if(i&&n)return;const[a,r]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/a).toFixed(2)}%`),this.#Wt||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#ge(){if(this.#qt)return;this.#qt=document.createElement("div"),this.#qt.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"];for(const e of t){const t=document.createElement("div");this.#qt.append(t),t.classList.add("resizer",e),t.setAttribute("data-resizer-name",e),t.addEventListener("pointerdown",this.#me.bind(this,e)),t.addEventListener("contextmenu",gt),t.tabIndex=-1}this.div.prepend(this.#qt)}#me(t,e){e.preventDefault();const{isMac:s}=$.platform;if(0!==e.button||e.ctrlKey&&s)return;this.#Nt?.toggle(!1);const i=this.#fe.bind(this,t),n=this._isDraggable;this._isDraggable=!1;const a={passive:!0,capture:!0};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",i,a),window.addEventListener("contextmenu",gt);const r=this.x,o=this.y,h=this.width,l=this.height,c=this.parent.div.style.cursor,d=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const u=()=>{this.parent.togglePointerEvents(!0),this.#Nt?.toggle(!0),this._isDraggable=n,window.removeEventListener("pointerup",u),window.removeEventListener("blur",u),window.removeEventListener("pointermove",i,a),window.removeEventListener("contextmenu",gt),this.parent.div.style.cursor=c,this.div.style.cursor=d,this.#be(r,o,h,l)};window.addEventListener("pointerup",u),window.addEventListener("blur",u)}#be(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[t,e]=this.parentDimensions;this.setDims(t*r,e*o),this.fixAndSetPosition()},undo:()=>{this.width=s,this.height=i,this.x=t,this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*s,a*i),this.fixAndSetPosition()},mustExec:!0})}#fe(t,e){const[s,i]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,h=It.MIN_SIZE/s,l=It.MIN_SIZE/i,c=t=>Math.round(1e4*t)/1e4,d=this.#pe(this.rotation),u=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],p=this.#pe(360-this.rotation);let g,m,f=!1,b=!1;switch(t){case"topLeft":f=!0,g=(t,e)=>[0,0],m=(t,e)=>[t,e];break;case"topMiddle":g=(t,e)=>[t/2,0],m=(t,e)=>[t/2,e];break;case"topRight":f=!0,g=(t,e)=>[t,0],m=(t,e)=>[0,e];break;case"middleRight":b=!0,g=(t,e)=>[t,e/2],m=(t,e)=>[0,e/2];break;case"bottomRight":f=!0,g=(t,e)=>[t,e],m=(t,e)=>[0,0];break;case"bottomMiddle":g=(t,e)=>[t/2,e],m=(t,e)=>[t/2,0];break;case"bottomLeft":f=!0,g=(t,e)=>[0,e],m=(t,e)=>[t,0];break;case"middleLeft":b=!0,g=(t,e)=>[0,e/2],m=(t,e)=>[t,e/2]}const v=g(r,o),y=m(r,o);let A=u(...y);const w=c(n+A[0]),x=c(a+A[1]);let _=1,E=1,[C,S]=this.screenToPageTranslation(e.movementX,e.movementY);var T,M;if([C,S]=(T=C/s,M=S/i,[p[0]*T+p[2]*M,p[1]*T+p[3]*M]),f){const t=Math.hypot(r,o);_=E=Math.max(Math.min(Math.hypot(y[0]-v[0]-C,y[1]-v[1]-S)/t,1/r,1/o),h/r,l/o)}else b?_=Math.max(h,Math.min(1,Math.abs(y[0]-v[0]-C)))/r:E=Math.max(l,Math.min(1,Math.abs(y[1]-v[1]-S)))/o;const k=c(r*_),P=c(o*E);A=u(...m(k,P));const R=w-A[0],L=x-A[1];this.width=k,this.height=P,this.x=R,this.y=L,this.setDims(s*k,i*P),this.fixAndSetPosition()}altTextFinish(){this.#Nt?.finish()}async addEditToolbar(){return this.#Qt||this.#se||(this.#Qt=new _t(this),this.div.append(this.#Qt.render()),this.#Nt&&this.#Qt.addAltTextButton(await this.#Nt.render())),this.#Qt}removeEditToolbar(){this.#Qt&&(this.#Qt.remove(),this.#Qt=null,this.#Nt?.destroy())}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#Nt||(Lt.initialize(It._l10nPromise),this.#Nt=new Lt(this),await this.addEditToolbar())}get altTextData(){return this.#Nt?.data}set altTextData(t){this.#Nt&&(this.#Nt.data=t)}hasAltText(){return!this.#Nt?.isEmpty()}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.#Gt?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.div.addEventListener("focusin",this.#Xt),this.div.addEventListener("focusout",this.#Yt);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),Ct(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=$.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#Zt=!0,this._isDraggable?this.#ve(t):this.#ye(t))}#ye(t){const{isMac:e}=$.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#ve(t){const e=this._uiManager.isSelected(this);let s,i;this._uiManager.setUpDragSession(),e&&(this.div.classList.add("moving"),s={passive:!0,capture:!0},this.#ae=t.clientX,this.#re=t.clientY,i=t=>{const{clientX:e,clientY:s}=t,[i,n]=this.screenToPageTranslation(e-this.#ae,s-this.#re);this.#ae=e,this.#re=s,this._uiManager.dragSelectedEditors(i,n)},window.addEventListener("pointermove",i,s));const n=()=>{window.removeEventListener("pointerup",n),window.removeEventListener("blur",n),e&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",i,s)),this.#Zt=!1,this._uiManager.endDragSession()||this.#ye(t)};window.addEventListener("pointerup",n),window.addEventListener("blur",n)}moveInDOM(){this.#ne&&clearTimeout(this.#ne),this.#ne=setTimeout((()=>{this.#ne=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,h=t/i,l=e/i,c=this.x*n,d=this.y*a,u=this.width*n,p=this.height*a;switch(s){case 0:return[c+h+r,a-d-l-p+o,c+h+u+r,a-d-l+o];case 90:return[c+l+r,a-d+h+o,c+l+p+r,a-d+h+u+o];case 180:return[c-h-u+r,a-d+l+o,c-h+r,a-d+l+p+o];case 270:return[c-l-p+r,a-d-h-u+o,c-l+r,a-d-h+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.#se=!0}disableEditMode(){this.#se=!1}isInEditMode(){return this.#se}shouldGetKeyboardEvents(){return this.#ie}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){this.div?.addEventListener("focusin",this.#Xt),this.div?.addEventListener("focusout",this.#Yt)}rotate(t){}serialize(t=!1,e=null){T("An editor must be serializable")}static deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation;const[n,a]=i.pageDimensions,[r,o,h,l]=i.getRectInCurrentCoords(t.rect,a);return i.x=r/n,i.y=o/a,i.width=h/n,i.height=l/a,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.div.removeEventListener("focusin",this.#Xt),this.div.removeEventListener("focusout",this.#Yt),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#ne&&(clearTimeout(this.#ne),this.#ne=null),this.#ce(),this.removeEditToolbar(),this.#oe){for(const t of this.#oe.values())clearTimeout(t);this.#oe=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#ge(),this.#qt.classList.remove("hidden"),Ct(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Kt={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#qt.children;if(!this.#Vt){this.#Vt=Array.from(e);const t=this.#Ae.bind(this),s=this.#we.bind(this);for(const e of this.#Vt){const i=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t),e.addEventListener("blur",s),e.addEventListener("focus",this.#xe.bind(this,i)),It._l10nPromise.get(`pdfjs-editor-resizer-label-${i}`).then((t=>e.setAttribute("aria-label",t)))}}const s=this.#Vt[0];let i=0;for(const t of e){if(t===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Vt.length/4);if(n!==i){if(n<i)for(let t=0;t<i-n;t++)this.#qt.append(this.#qt.firstChild);else if(n>i)for(let t=0;t<n-i;t++)this.#qt.firstChild.before(this.#qt.lastChild);let t=0;for(const s of e){const e=this.#Vt[t++].getAttribute("data-resizer-name");It._l10nPromise.get(`pdfjs-editor-resizer-label-${e}`).then((t=>s.setAttribute("aria-label",t)))}}this.#_e(0),this.#ie=!0,this.#qt.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#Ae(t){It._resizerKeyboardManager.exec(this,t)}#we(t){this.#ie&&t.relatedTarget?.parentNode!==this.#qt&&this.#ce()}#xe(t){this.#Jt=this.#ie?t:""}#_e(t){if(this.#Vt)for(const e of this.#Vt)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#ie&&this.#fe(this.#Jt,{movementX:t,movementY:e})}#ce(){if(this.#ie=!1,this.#_e(-1),this.#Kt){const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#Kt;this.#be(t,e,s,i),this.#Kt=null}}_stopResizingWithKeyboard(){this.#ce(),this.div.focus()}select(){this.makeResizable(),this.div?.classList.add("selectedEditor"),this.#Qt?this.#Qt?.show():this.addEditToolbar().then((()=>{this.div?.classList.contains("selectedEditor")&&this.#Qt?.show()}))}unselect(){this.#qt?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this.#Qt?.hide()}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#ee}set isEditing(t){this.#ee=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#Wt=!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.#oe||=new Map;const{action:e}=t;let s=this.#oe.get(e);return s&&clearTimeout(s),s=setTimeout((()=>{this._reportTelemetry(t),this.#oe.delete(e),0===this.#oe.size&&(this.#oe=null)}),It._telemetryTimeout),void this.#oe.set(e,s)}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.#Gt=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Gt=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class Dt extends It{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex}}}const Ft=3285377520,Ot=4294901760,Nt=65535;class Bt{constructor(t){this.h1=t?4294967295&t:Ft,this.h2=t?4294967295&t:Ft}update(t){let e,s;if("string"==typeof t){e=new Uint8Array(2*t.length),s=0;for(let i=0,n=t.length;i<n;i++){const n=t.charCodeAt(i);n<=255?e[s++]=n:(e[s++]=n>>>8,e[s++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),s=e.byteLength}const i=s>>2,n=s-4*i,a=new Uint32Array(e.buffer,0,i);let r=0,o=0,h=this.h1,l=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let t=0;t<i;t++)1&t?(r=a[t],r=r*c&Ot|r*u&Nt,r=r<<15|r>>>17,r=r*d&Ot|r*p&Nt,h^=r,h=h<<13|h>>>19,h=5*h+3864292196):(o=a[t],o=o*c&Ot|o*u&Nt,o=o<<15|o>>>17,o=o*d&Ot|o*p&Nt,l^=o,l=l<<13|l>>>19,l=5*l+3864292196);switch(r=0,n){case 3:r^=e[4*i+2]<<16;case 2:r^=e[4*i+1]<<8;case 1:r^=e[4*i],r=r*c&Ot|r*u&Nt,r=r<<15|r>>>17,r=r*d&Ot|r*p&Nt,1&i?h^=r:l^=r}this.h1=h,this.h2=l}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&Ot|36045*t&Nt,e=4283543511*e&Ot|(2950163797*(e<<16|t>>>16)&Ot)>>>16,t^=e>>>1,t=444984403*t&Ot|60499*t&Nt,e=3301882366*e&Ot|(3120437893*(e<<16|t>>>16)&Ot)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Ht=Object.freeze({map:null,hash:"",transfer:void 0});class zt{#Ee=!1;#Ce=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=this.#Ce.get(t);return void 0===s?e:Object.assign(e,s)}getRawValue(t){return this.#Ce.get(t)}remove(t){if(this.#Ce.delete(t),0===this.#Ce.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor){for(const t of this.#Ce.values())if(t instanceof It)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#Ce.get(t);let i=!1;if(void 0!==s)for(const[t,n]of Object.entries(e))s[t]!==n&&(i=!0,s[t]=n);else i=!0,this.#Ce.set(t,e);i&&this.#Se(),e instanceof It&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ce.has(t)}getAll(){return this.#Ce.size>0?j(this.#Ce):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#Ce.size}#Se(){this.#Ee||(this.#Ee=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#Ee&&(this.#Ee=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new jt(this)}get serializable(){if(0===this.#Ce.size)return Ht;const t=new Map,e=new Bt,s=[],i=Object.create(null);let n=!1;for(const[s,a]of this.#Ce){const r=a instanceof It?a.serialize(!1,i):a;r&&(t.set(s,r),e.update(`${s}:${JSON.stringify(r)}`),n||=!!r.bitmap)}if(n)for(const e of t.values())e.bitmap&&s.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:Ht}get editorStats(){let t=null;const e=new Map;for(const s of this.#Ce.values()){if(!(s instanceof It))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[t,e]of Object.entries(i)){if("type"===t)continue;let s=a.get(t);s||(s=new Map,a.set(t,s));const i=s.get(e)??0;s.set(e,i+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}}class jt extends zt{#Te;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable,n=structuredClone(e,i?{transfer:i}:null);this.#Te={map:n,hash:s,transfer:i}}get print(){T("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Te}}class $t{#Me=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.#Me.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#Me.has(t.loadedName))if(M(!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.#Me.add(s),e?.(t)}catch{S(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}}else T("Not implemented: loadSystemFont without the Font Loading API.")}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(s){throw S(`Failed to load font '${e.family}': '${s}'.`),t.disableFontFace=!0,s}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise((e=>{const s=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,s)}))}}get isFontLoadingAPISupported(){return P(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;return(l||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),P(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,s={done:!1,complete:function(){for(M(!s.done,"completeRequest() cannot be called twice."),s.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(s),s}get _loadTestFont(){return P(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function s(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function i(t,e,s,i){return t.substring(0,e)+i+t.substring(e+s)}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let h=0;const l=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=i(c,976,l.length,l);const d=1482184792;let u=s(c,16);for(n=0,a=l.length-3;n<a;n+=4)u=u-d+s(l,n)|0;var p;n<l.length&&(u=u-d+s(l+"XXX",n)|0),c=i(c,16,4,(p=u,String.fromCharCode(p>>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${l}";src:url(data:font/opentype;base64,${btoa(c)});}`;this.insertRule(g);const m=this._document.createElement("div");m.style.visibility="hidden",m.style.width=m.style.height="10px",m.style.position="absolute",m.style.top=m.style.left="0px";for(const e of[t.loadedName,l]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,s){if(++h>30)return S("Load test font never loaded."),void s();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?s():setTimeout(t.bind(null,e,s))}(l,(()=>{m.remove(),e.complete()}))}}class Ut{constructor(t,{disableFontFace:e=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e,this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=H(this.data),e=`url(data:${this.mimetype};base64,${btoa(t)});`;let s;if(this.cssFontInfo){let t=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(t+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),s=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${t}src:${e}}`}else s=`@font-face {font-family:"${this.loadedName}";src:${e}}`;return this._inspectFont?.(this,e),s}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];let s;try{s=t.get(this.loadedName+"_path_"+e)}catch(t){S(`getPathGenerator - ignoring character: "${t}".`)}if(!Array.isArray(s)||0===s.length)return this.compiledGlyphs[e]=function(t,e){};const i=[];for(let t=0,e=s.length;t<e;)switch(s[t++]){case 0:{const[e,n,a,r,o,h]=s.slice(t,t+6);i.push((t=>t.bezierCurveTo(e,n,a,r,o,h))),t+=6}break;case 1:{const[e,n]=s.slice(t,t+2);i.push((t=>t.moveTo(e,n))),t+=2}break;case 2:{const[e,n]=s.slice(t,t+2);i.push((t=>t.lineTo(e,n))),t+=2}break;case 3:{const[e,n,a,r]=s.slice(t,t+4);i.push((t=>t.quadraticCurveTo(e,n,a,r))),t+=4}break;case 4:i.push((t=>t.restore()));break;case 5:i.push((t=>t.save()));break;case 6:M(2===i.length,"Scale command is only valid at the third position.");break;case 7:{const[e,n,a,r,o,h]=s.slice(t,t+6);i.push((t=>t.transform(e,n,a,r,o,h))),t+=6}break;case 8:{const[e,n]=s.slice(t,t+2);i.push((t=>t.translate(e,n))),t+=2}}return this.compiledGlyphs[e]=function(t,e){i[0](t),i[1](t),t.scale(e,-e);for(let e=2,s=i.length;e<s;e++)i[e](t)}}}if(l){var Vt=Promise.withResolvers(),Gt=null;(async()=>{const t=await import("fs"),e=await import("http"),s=await import("https"),i=await import("url");return new Map(Object.entries({fs:t,http:e,https:s,url:i,canvas:void 0,path2d:void 0}))})().then((t=>{Gt=t,Vt.resolve()}),(t=>{S(`loadPackages: ${t}`),Gt=new Map,Vt.resolve()}))}class Wt{static get promise(){return Vt.promise}static get(t){return Gt?.get(t)}}const qt=function(t){return Wt.get("fs").promises.readFile(t).then((t=>new Uint8Array(t)))},Kt="Fill",Xt="Stroke",Yt="Shading";function Qt(t,e){if(!e)return;const s=e[2]-e[0],i=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],s,i),t.clip(n)}class Jt{constructor(){this.constructor===Jt&&T("Cannot initialize BaseShadingPattern.")}getPattern(){T("Abstract method `getPattern` called.")}}class Zt extends Jt{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,s,i){let n;if(i===Xt||i===Kt){const a=e.current.getClippedPathBoundingBox(i,At(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,h=e.cachedCanvases.getCanvas("pattern",r,o,!0),l=h.context;l.clearRect(0,0,l.canvas.width,l.canvas.height),l.beginPath(),l.rect(0,0,l.canvas.width,l.canvas.height),l.translate(-a[0],-a[1]),s=V.transform(s,[1,0,0,1,a[0],a[1]]),l.transform(...e.baseTransform),this.matrix&&l.transform(...this.matrix),Qt(l,this._bbox),l.fillStyle=this._createGradient(l),l.fill(),n=t.createPattern(h.canvas,"no-repeat");const c=new DOMMatrix(s);n.setTransform(c)}else Qt(t,this._bbox),n=this._createGradient(t);return n}}function te(t,e,s,i,n,a,r,o){const h=e.coords,l=e.colors,c=t.data,d=4*t.width;let u;h[s+1]>h[i+1]&&(u=s,s=i,i=u,u=a,a=r,r=u),h[i+1]>h[n+1]&&(u=i,i=n,n=u,u=r,r=o,o=u),h[s+1]>h[i+1]&&(u=s,s=i,i=u,u=a,a=r,r=u);const p=(h[s]+e.offsetX)*e.scaleX,g=(h[s+1]+e.offsetY)*e.scaleY,m=(h[i]+e.offsetX)*e.scaleX,f=(h[i+1]+e.offsetY)*e.scaleY,b=(h[n]+e.offsetX)*e.scaleX,v=(h[n+1]+e.offsetY)*e.scaleY;if(g>=v)return;const y=l[a],A=l[a+1],w=l[a+2],x=l[r],_=l[r+1],E=l[r+2],C=l[o],S=l[o+1],T=l[o+2],M=Math.round(g),k=Math.round(v);let P,R,L,I,D,F,O,N;for(let t=M;t<=k;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);P=p-(p-m)*e,R=y-(y-x)*e,L=A-(A-_)*e,I=w-(w-E)*e}else{let e;e=t>v?1:f===v?0:(f-t)/(f-v),P=m-(m-b)*e,R=x-(x-C)*e,L=_-(_-S)*e,I=E-(E-T)*e}let e;e=t<g?0:t>v?1:(g-t)/(g-v),D=p-(p-b)*e,F=y-(y-C)*e,O=A-(A-S)*e,N=w-(w-T)*e;const s=Math.round(Math.min(P,D)),i=Math.round(Math.max(P,D));let n=d*t+4*s;for(let t=s;t<=i;t++)e=(P-t)/(P-D),e<0?e=0:e>1&&(e=1),c[n++]=R-(R-F)*e|0,c[n++]=L-(L-O)*e|0,c[n++]=I-(I-N)*e|0,c[n++]=255}}function ee(t,e,s){const i=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,h=Math.floor(i.length/o)-1,l=o-1;for(a=0;a<h;a++){let e=a*o;for(let a=0;a<l;a++,e++)te(t,s,i[e],i[e+1],i[e+o],n[e],n[e+1],n[e+o]),te(t,s,i[e+o+1],i[e+1],i[e+o],n[e+o+1],n[e+1],n[e+o])}break;case"triangles":for(a=0,r=i.length;a<r;a+=3)te(t,s,i[a],i[a+1],i[a+2],n[a],n[a+1],n[a+2]);break;default:throw new Error("illegal figure")}}class se extends Jt{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 i=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),a=Math.ceil(this._bounds[2])-i,r=Math.ceil(this._bounds[3])-n,o=Math.min(Math.ceil(Math.abs(a*t[0]*1.1)),3e3),h=Math.min(Math.ceil(Math.abs(r*t[1]*1.1)),3e3),l=a/o,c=r/h,d={coords:this._coords,colors:this._colors,offsetX:-i,offsetY:-n,scaleX:1/l,scaleY:1/c},u=o+4,p=h+4,g=s.getCanvas("mesh",u,p,!1),m=g.context,f=m.createImageData(o,h);if(e){const t=f.data;for(let s=0,i=t.length;s<i;s+=4)t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=255}for(const t of this._figures)ee(f,t,d);return m.putImageData(f,2,2),{canvas:g.canvas,offsetX:i-2*l,offsetY:n-2*c,scaleX:l,scaleY:c}}getPattern(t,e,s,i){let n;if(Qt(t,this._bbox),i===Yt)n=V.singularValueDecompose2dScale(At(t));else if(n=V.singularValueDecompose2dScale(e.baseTransform),this.matrix){const t=V.singularValueDecompose2dScale(this.matrix);n=[n[0]*t[0],n[1]*t[1]]}const a=this._createMeshCanvas(n,i===Yt?null:this._background,e.cachedCanvases);return i!==Yt&&(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 ie extends Jt{getPattern(){return"hotpink"}}class ne{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 e=this.operatorList,s=this.bbox,i=this.xstep,n=this.ystep,a=this.paintType,r=this.tilingType,o=this.color,h=this.canvasGraphicsFactory;C("TilingType: "+r);const l=s[0],c=s[1],d=s[2],u=s[3],p=V.singularValueDecompose2dScale(this.matrix),g=V.singularValueDecompose2dScale(this.baseTransform),m=[p[0]*g[0],p[1]*g[1]],f=this.getSizeAndScale(i,this.ctx.canvas.width,m[0]),b=this.getSizeAndScale(n,this.ctx.canvas.height,m[1]),v=t.cachedCanvases.getCanvas("pattern",f.size,b.size,!0),y=v.context,A=h.createCanvasGraphics(y);A.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(A,a,o);let w=l,x=c,_=d,E=u;return l<0&&(w=0,_+=Math.abs(l)),c<0&&(x=0,E+=Math.abs(c)),y.translate(-f.scale*w,-b.scale*x),A.transform(f.scale,0,0,b.scale,0,0),y.save(),this.clipBbox(A,w,x,_,E),A.baseTransform=At(A.ctx),A.executeOperatorList(e),A.endDrawing(),{canvas:v.canvas,scaleX:f.scale,scaleY:b.scale,offsetX:w,offsetY:x}}getSizeAndScale(t,e,s){t=Math.abs(t);const i=Math.max(ne.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(At(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case 1:const t=this.ctx;i.fillStyle=t.fillStyle,i.strokeStyle=t.strokeStyle,n.fillColor=t.fillStyle,n.strokeColor=t.strokeStyle;break;case 2:const a=V.makeHexColor(s[0],s[1],s[2]);i.fillStyle=a,i.strokeStyle=a,n.fillColor=a,n.strokeColor=a;break;default:throw new N(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Yt&&(n=V.transform(n,e.baseTransform),this.matrix&&(n=V.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 ae({src:t,srcPos:e=0,dest:s,width:i,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=$.isLittleEndian?4278190080:255,[h,l]=r?[a,o]:[o,a],c=i>>3,d=7&i,u=t.length;s=new Uint32Array(s.buffer);let p=0;for(let i=0;i<n;i++){for(const i=e+c;e<i;e++){const i=e<u?t[e]:255;s[p++]=128&i?l:h,s[p++]=64&i?l:h,s[p++]=32&i?l:h,s[p++]=16&i?l:h,s[p++]=8&i?l:h,s[p++]=4&i?l:h,s[p++]=2&i?l:h,s[p++]=1&i?l:h}if(0===d)continue;const i=e<u?t[e++]:255;for(let t=0;t<d;t++)s[p++]=i&1<<7-t?l:h}return{srcPos:e,destPos:p}}const re=16;class oe{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return void 0!==this.cache[t]?(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 he(t,e,s,i,n,a,r,o,h,l){const[c,d,u,p,g,m]=At(t);if(0===d&&0===u){const f=r*c+g,b=Math.round(f),v=o*p+m,y=Math.round(v),A=(r+h)*c+g,w=Math.abs(Math.round(A)-b)||1,x=(o+l)*p+m,_=Math.abs(Math.round(x)-y)||1;return t.setTransform(Math.sign(c),0,0,Math.sign(p),b,y),t.drawImage(e,s,i,n,a,0,0,w,_),t.setTransform(c,d,u,p,g,m),[w,_]}if(0===c&&0===p){const f=o*u+g,b=Math.round(f),v=r*d+m,y=Math.round(v),A=(o+l)*u+g,w=Math.abs(Math.round(A)-b)||1,x=(r+h)*d+m,_=Math.abs(Math.round(x)-y)||1;return t.setTransform(0,Math.sign(d),Math.sign(u),0,b,y),t.drawImage(e,s,i,n,a,0,0,_,w),t.setTransform(c,d,u,p,g,m),[_,w]}return t.drawImage(e,s,i,n,a,r,o,h,l),[Math.hypot(c,d)*h,Math.hypot(u,p)*l]}class le{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=c,this.textMatrixScale=1,this.fontMatrix=d,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=0,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]=V.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=V.applyTransform(e,t),i=V.applyTransform(e.slice(2),t),n=V.applyTransform([e[0],e[3]],t),a=V.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){V.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,h,l){const c=V.bezierBoundingBox(e,s,i,n,a,r,o,h,l);l||this.updateRectMinMax(t,c)}getPathBoundingBox(t=Kt,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Xt){e||T("Stroke bounding box must include transform.");const t=V.singularValueDecompose2dScale(e),i=t[0]*this.lineWidth/2,n=t[1]*this.lineWidth/2;s[0]-=i,s[1]-=n,s[2]+=i,s[3]+=n}return s}updateClipFromPath(){const t=V.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=Kt,e=null){return V.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function ce(t,e){if("undefined"!=typeof ImageData&&e instanceof ImageData)return void t.putImageData(e,0,0);const s=e.height,i=e.width,n=s%re,a=(s-n)/re,r=0===n?a:a+1,o=t.createImageData(i,re);let h,l=0;const c=e.data,d=o.data;let u,p,g,m;if(e.kind===b.GRAYSCALE_1BPP){const e=c.byteLength,s=new Uint32Array(d.buffer,0,d.byteLength>>2),m=s.length,f=i+7>>3,b=4294967295,v=$.isLittleEndian?4278190080:255;for(u=0;u<r;u++){for(g=u<a?re:n,h=0,p=0;p<g;p++){const t=e-l;let n=0;const a=t>f?i:8*t-7,r=-8&a;let o=0,d=0;for(;n<r;n+=8)d=c[l++],s[h++]=128&d?b:v,s[h++]=64&d?b:v,s[h++]=32&d?b:v,s[h++]=16&d?b:v,s[h++]=8&d?b:v,s[h++]=4&d?b:v,s[h++]=2&d?b:v,s[h++]=1&d?b:v;for(;n<a;n++)0===o&&(d=c[l++],o=128),s[h++]=d&o?b:v,o>>=1}for(;h<m;)s[h++]=0;t.putImageData(o,0,u*re)}}else if(e.kind===b.RGBA_32BPP){for(p=0,m=i*re*4,u=0;u<a;u++)d.set(c.subarray(l,l+m)),l+=m,t.putImageData(o,0,p),p+=re;u<r&&(m=i*n*4,d.set(c.subarray(l,l+m)),t.putImageData(o,0,p))}else{if(e.kind!==b.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=re,m=i*g,u=0;u<r;u++){for(u>=a&&(g=n,m=i*g),h=0,p=m;p--;)d[h++]=c[l++],d[h++]=c[l++],d[h++]=c[l++],d[h++]=255;t.putImageData(o,0,u*re)}}}function de(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const s=e.height,i=e.width,n=s%re,a=(s-n)/re,r=0===n?a:a+1,o=t.createImageData(i,re);let h=0;const l=e.data,c=o.data;for(let e=0;e<r;e++){const s=e<a?re:n;({srcPos:h}=ae({src:l,srcPos:h,dest:c,width:i,height:s,nonBlackColor:0})),t.putImageData(o,0,e*re)}}function ue(t,e){const s=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const i of s)void 0!==t[i]&&(e[i]=t[i]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function pe(t){if(t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0),!l){const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}}function ge(t,e){if(e)return!0;const s=V.singularValueDecompose2dScale(t);s[0]=Math.fround(s[0]),s[1]=Math.fround(s[1]);const i=Math.fround((globalThis.devicePixelRatio||1)*et.PDF_TO_CSS_UNITS);return s[0]<=i&&s[1]<=i}const me=["butt","round","square"],fe=["miter","round","bevel"],be={},ve={};class ye{constructor(t,e,s,i,n,{optionalContentConfig:a,markedContentStack:r=null},o,h){this.ctx=t,this.current=new le(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 oe(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=h,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return"string"==typeof t?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 t=this.cachedCanvases.getCanvas("transparent",n,a);this.compositeCtx=this.ctx,this.transparentCanvas=t.canvas,this.ctx=t.context,this.ctx.save(),this.ctx.transform(...At(this.compositeCtx))}this.ctx.save(),pe(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=At(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 h=o-r>10&&"function"==typeof s,l=h?Date.now()+15:0;let c=0;const d=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==i&&r===i.nextBreakPoint)return i.breakIt(r,s),r;if(p=a[r],p!==A.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?d:u;if(!e.has(t))return e.get(t,s),r}if(r++,r===o)return r;if(h&&++c>10){if(Date.now()>l)return s(),r;c=0}}}#ke(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();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.#ke(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#Pe()}#Pe(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width,i=t.height;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),h=s,l=i,c="prescale1";for(;r>2&&h>1||o>2&&l>1;){let e=h,s=l;r>2&&h>1&&(e=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h/2),r/=h/e),o>2&&l>1&&(s=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l)/2,o/=l/s),n=this.cachedCanvases.getCanvas(c,e,s),a=n.context,a.clearRect(0,0,e,s),a.drawImage(t,0,0,h,l,0,0,e,s),t=n.canvas,h=e,l=s,c="prescale1"===c?"prescale2":"prescale1"}return{img:t,paintWidth:h,paintHeight:l}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,a=this.current.patternFill,r=At(e);let o,h,l,c;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;h=JSON.stringify(a?r:[r.slice(0,4),n]),o=this._cachedBitmapsMap.get(e),o||(o=new Map,this._cachedBitmapsMap.set(e,o));const s=o.get(h);if(s&&!a)return{canvas:s,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])};l=s}l||(c=this.cachedCanvases.getCanvas("maskCanvas",s,i),de(c.context,t));let d=V.transform(r,[1/s,0,0,-1/i,0,0]);d=V.transform(d,[1,0,0,1,0,-i]);const[u,p,g,m]=V.getAxialAlignedBoundingBox([0,0,s,i],d),f=Math.round(g-u)||1,b=Math.round(m-p)||1,v=this.cachedCanvases.getCanvas("fillCanvas",f,b),y=v.context,A=u,w=p;y.translate(-A,-w),y.transform(...d),l||(l=this._scaleImage(c.canvas,wt(y)),l=l.img,o&&a&&o.set(h,l)),y.imageSmoothingEnabled=ge(At(y),t.interpolate),he(y,l,0,0,l.width,l.height,0,0,s,i),y.globalCompositeOperation="source-in";const x=V.transform(wt(y),[1,0,0,1,-A,-w]);return y.fillStyle=a?n.getPattern(e,this,x,Kt):n,y.fillRect(0,0,s,i),o&&!a&&(this.cachedCanvases.delete("fillCanvas"),o.set(h,v.canvas)),{canvas:v.canvas,offsetX:Math.round(A),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=me[t]}setLineJoin(t){this.ctx.lineJoin=fe[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;void 0!==s.setLineDash&&(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)}}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(...At(this.suspendedCtx)),ue(this.suspendedCtx,n),function(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,s){e.translate(t,s),this.__originalTranslate(t,s)},t.scale=function(t,s){e.scale(t,s),this.__originalScale(t,s)},t.transform=function(t,s,i,n,a,r){e.transform(t,s,i,n,a,r),this.__originalTransform(t,s,i,n,a,r)},t.setTransform=function(t,s,i,n,a,r){e.setTransform(t,s,i,n,a,r),this.__originalSetTransform(t,s,i,n,a,r)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,s){e.moveTo(t,s),this.__originalMoveTo(t,s)},t.lineTo=function(t,s){e.lineTo(t,s),this.__originalLineTo(t,s)},t.bezierCurveTo=function(t,s,i,n,a,r){e.bezierCurveTo(t,s,i,n,a,r),this.__originalBezierCurveTo(t,s,i,n,a,r)},t.rect=function(t,s,i,n){e.rect(t,s,i,n),this.__originalRect(t,s,i,n)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(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(),ue(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;0!==r&&0!==o&&(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,h,l,c){let d=t.canvas,u=o-l,p=h-c;if(a)if(u<0||p<0||u+s>d.width||p+i>d.height){const t=this.cachedCanvases.getCanvas("maskExtension",s,i),e=t.context;e.drawImage(d,-u,-p),a.some((t=>0!==t))&&(e.globalCompositeOperation="destination-atop",e.fillStyle=V.makeHexColor(...a),e.fillRect(0,0,s,i),e.globalCompositeOperation="source-over"),d=t.canvas,u=p=0}else if(a.some((t=>0!==t))){t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,s,i),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=V.makeHexColor(...a),t.fillRect(u,p,s,i),t.restore()}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,h,s,i),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(d,u,p,s,i,o,h,s,i),e.restore()}save(){this.inSMaskMode?(ue(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),ue(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,r,o=n.x,h=n.y;const l=At(i),c=0===l[0]&&0===l[3]||0===l[1]&&0===l[2],d=c?s.slice(0):null;for(let s=0,u=0,p=t.length;s<p;s++)switch(0|t[s]){case A.rectangle:o=e[u++],h=e[u++];const t=e[u++],s=e[u++],p=o+t,g=h+s;i.moveTo(o,h),0===t||0===s?i.lineTo(p,g):(i.lineTo(p,h),i.lineTo(p,g),i.lineTo(o,g)),c||n.updateRectMinMax(l,[o,h,p,g]),i.closePath();break;case A.moveTo:o=e[u++],h=e[u++],i.moveTo(o,h),c||n.updatePathMinMax(l,o,h);break;case A.lineTo:o=e[u++],h=e[u++],i.lineTo(o,h),c||n.updatePathMinMax(l,o,h);break;case A.curveTo:a=o,r=h,o=e[u+4],h=e[u+5],i.bezierCurveTo(e[u],e[u+1],e[u+2],e[u+3],o,h),n.updateCurvePathMinMax(l,a,r,e[u],e[u+1],e[u+2],e[u+3],o,h,d),u+=6;break;case A.curveTo2:a=o,r=h,i.bezierCurveTo(o,h,e[u],e[u+1],e[u+2],e[u+3]),n.updateCurvePathMinMax(l,a,r,o,h,e[u],e[u+1],e[u+2],e[u+3],d),o=e[u+2],h=e[u+3],u+=4;break;case A.curveTo3:a=o,r=h,o=e[u+2],h=e[u+3],i.bezierCurveTo(e[u],e[u+1],o,h,o,h),n.updateCurvePathMinMax(l,a,r,e[u],e[u+1],o,h,o,h,d),u+=4;break;case A.closePath:i.closePath()}c&&n.updateScalingPathMinMax(l,d),n.setCurrentPoint(o,h)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&("object"==typeof s&&s?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,wt(e),Xt),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;let i=!1;this.current.patternFill&&(e.save(),e.fillStyle=s.getPattern(e,this,wt(e),Kt),i=!0);const n=this.current.getClippedPathBoundingBox();this.contentVisible&&null!==n&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),i&&e.restore(),t&&this.consumePath(n)}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=be}eoClip(){this.pendingClip=ve}beginText(){this.current.textMatrix=c,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(void 0!==t){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}else e.beginPath()}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||d,0!==i.fontMatrix[0]&&0!==i.fontMatrix[3]||S("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 h=e;e<16?h=16:e>100&&(h=100),this.current.fontSizeScale=e/h,this.ctx.font=`${o} ${r} ${h}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,h=a.fontSize/a.fontSizeScale,l=3&o,c=!!(4&o),d=a.patternFill&&!r.missingFile;let u;(r.disableFontFace||c||d)&&(u=r.getPathGenerator(this.commonObjs,t)),r.disableFontFace||d?(n.save(),n.translate(e,s),n.beginPath(),u(n,h),i&&n.setTransform(...i),0!==l&&2!==l||n.fill(),1!==l&&2!==l||n.stroke(),n.restore()):(0!==l&&2!==l||n.fillText(t,e,s),1!==l&&2!==l||n.strokeText(t,e,s)),c&&(this.pendingTextPaths||=[]).push({transform:At(n),x:e,y:s,fontSize:h,addToPath:u})}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 t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){s=!0;break}return P(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(0===i)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,h=e.fontDirection,l=e.textHScale*h,c=t.length,d=s.vertical,u=d?1:-1,p=s.defaultVMetrics,g=i*e.fontMatrix[0],m=0===e.textRenderingMode&&!s.disableFontFace&&!e.patternFill;let f;if(n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),h>0?n.scale(l,-1):n.scale(l,1),e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,wt(n),Kt);f=At(n),n.restore(),n.fillStyle=t}let b=e.lineWidth;const v=e.textMatrixScale;if(0===v||0===b){const t=3&e.textRenderingMode;1!==t&&2!==t||(b=this.getSinglePixelWidth())}else b/=v;if(1!==a&&(n.scale(a,a),b/=a),n.lineWidth=b,s.isInvalidPDFjsFont){const s=[];let i=0;for(const e of t)s.push(e.unicode),i+=e.width;return n.fillText(s.join(""),0,0),e.x+=i*g*l,n.restore(),void this.compose()}let y,A=0;for(y=0;y<c;++y){const e=t[y];if("number"==typeof e){A+=u*e*i/1e3;continue}let l=!1;const c=(e.isSpace?o:0)+r,b=e.fontChar,v=e.accent;let w,x,_=e.width;if(d){const t=e.vmetric||p,s=-(e.vmetric?t[1]:.5*_)*g,i=t[2]*g;_=t?-t[0]:_,w=s/a,x=(A+i)/a}else w=A/a,x=0;if(s.remeasure&&_>0){const t=1e3*n.measureText(b).width/i*a;if(_<t&&this.isFontSubpixelAAEnabled){const e=_/t;l=!0,n.save(),n.scale(e,1),w/=e}else _!==t&&(w+=(_-t)/2e3*i/a)}if(this.contentVisible&&(e.isInFont||s.missingFile))if(m&&!v)n.fillText(b,w,x);else if(this.paintChar(b,w,x,f),v){const t=w+i*v.offset.x/a,e=x-i*v.offset.y/a;this.paintChar(v.fontChar,t,e,f)}A+=d?_*g-c*h:_*g+c*h,l&&n.restore()}d?e.y-=A:e.x+=A*l,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,h=s.wordSpacing,l=s.textHScale*a,c=s.fontMatrix||d,u=t.length;let p,g,m,f;if(3!==s.textRenderingMode&&0!==n){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(l,a),p=0;p<u;++p){if(g=t[p],"number"==typeof g){f=r*g*n/1e3,this.ctx.translate(f,0),s.x+=f*l;continue}const a=(g.isSpace?h:0)+o,d=i.charProcOperatorList[g.operatorListId];d?(this.contentVisible&&(this.processingType3=g,this.save(),e.scale(n,n),e.transform(...c),this.executeOperatorList(d),this.restore()),m=V.applyTransform([g.width,0],c)[0]*n+a,e.translate(m,0),s.x+=m*l):S(`Type3 character "${g.operatorListId}" is not available.`)}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("TilingPattern"===t[0]){const s=t[1],i=this.baseTransform||At(this.ctx),n={createCanvasGraphics:t=>new ye(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new ne(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){const i=V.makeHexColor(t,e,s);this.ctx.strokeStyle=i,this.current.strokeColor=i}setFillRGBColor(t,e,s){const i=V.makeHexColor(t,e,s);this.ctx.fillStyle=i,this.current.fillColor=i,this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=function(t){switch(t[0]){case"RadialAxial":return new Zt(t);case"Mesh":return new se(t);case"Dummy":return new ie}throw new Error(`Unknown IR type: ${t[0]}`)}(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),Yt);const i=wt(e);if(i){const{width:t,height:s}=e.canvas,[n,a,r,o]=V.getAxialAlignedBoundingBox([0,0,t,s],i);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){T("Should not call beginInlineImage")}beginImageData(){T("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=At(this.ctx),e)){const t=e[2]-e[0],s=e[3]-e[1];this.ctx.rect(e[0],e[1],t,s),this.current.updateRectMinMax(At(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||C("TODO: Support non-isolated groups."),t.knockout&&S("Knockout groups not supported.");const s=At(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=V.getAxialAlignedBoundingBox(t.bbox,At(e));const n=[0,0,e.canvas.width,e.canvas.height];i=V.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),h=Math.max(Math.ceil(i[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,h]);let l="groupAt"+this.groupLevel;t.smask&&(l+="_smask_"+this.smaskCounter++%2);const c=this.cachedCanvases.getCanvas(l,o,h),d=c.context;d.translate(-a,-r),d.transform(...s),t.smask?this.smaskStack.push({canvas:c.canvas,context:d,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()),ue(e,d),this.ctx=d,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 t=At(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...t);const s=V.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(s)}}beginAnnotation(t,e,s,i,n){if(this.#ke(),pe(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const i=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(s=s.slice())[4]-=e[0],s[5]-=e[1],(e=e.slice())[0]=e[1]=0,e[2]=i,e[3]=a;const[n,r]=V.singularValueDecompose2dScale(At(this.ctx)),{viewportScale:o}=this,h=Math.ceil(i*this.outputScaleX*o),l=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(h,l);const{canvas:c,context:d}=this.annotationCanvas;this.annotationCanvasMap.set(t,c),this.annotationCanvas.savedCtx=this.ctx,this.ctx=d,this.ctx.save(),this.ctx.setTransform(n,0,0,-r,0,a*r),pe(this.ctx)}else pe(this.ctx),this.ctx.rect(e[0],e[1],i,a),this.ctx.clip(),this.endPath()}this.current=new le(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#Pe(),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)).count=e;const s=this.ctx,i=this.processingType3;if(i&&(void 0===i.compiled&&(i.compiled=function(t){const{width:e,height:s}=t;if(e>1e3||s>1e3)return null;const i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,h=new Uint8Array(n*(s+1));const l=e+7&-8;let c=new Uint8Array(l*s),d=0;for(const e of t.data){let t=128;for(;t>0;)c[d++]=e&t?0:255,t>>=1}let u=0;for(d=0,0!==c[d]&&(h[0]=1,++u),r=1;r<e;r++)c[d]!==c[d+1]&&(h[r]=c[d]?2:1,++u),d++;for(0!==c[d]&&(h[r]=2,++u),a=1;a<s;a++){d=a*l,o=a*n,c[d-l]!==c[d]&&(h[o]=c[d]?1:8,++u);let t=(c[d]?4:0)+(c[d-l]?8:0);for(r=1;r<e;r++)t=(t>>2)+(c[d+1]?4:0)+(c[d-l+1]?8:0),i[t]&&(h[o+r]=i[t],++u),d++;if(c[d-l]!==c[d]&&(h[o+r]=c[d]?2:4,++u),u>1e3)return null}for(d=l*(s-1),o=a*n,0!==c[d]&&(h[o]=8,++u),r=1;r<e;r++)c[d]!==c[d+1]&&(h[o+r]=c[d]?4:8,++u),d++;if(0!==c[d]&&(h[o+r]=4,++u),u>1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=s;a++){let t=a*n;const s=t+e;for(;t<s&&!h[t];)t++;if(t===s)continue;g.moveTo(t%n,a);const i=t;let r=h[t];do{const e=p[r];do{t+=e}while(!h[t]);const s=h[t];5!==s&&10!==s?(r=s,h[t]=0):(r=s&51*r>>4,h[t]&=r>>2|r<<2),g.lineTo(t%n,t/n|0),h[t]||--u}while(i!==t);--a}return c=null,h=null,function(t){t.save(),t.scale(1/e,-1/s),t.translate(0,-s),t.fill(g),t.beginPath(),t.restore()}}(t)),i.compiled))return void i.compiled(s);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=At(r);r.transform(e,s,i,n,0,0);const h=this._createMaskCanvas(t);r.setTransform(1,0,0,1,h.offsetX-o[4],h.offsetY-o[5]);for(let t=0,l=a.length;t<l;t+=2){const l=V.transform(o,[e,s,i,n,a[t],a[t+1]]),[c,d]=V.applyTransform([0,0],l);r.drawImage(h.canvas,c,d)}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:t,width:a,height:r,transform:o}=n,h=this.cachedCanvases.getCanvas("maskCanvas",a,r),l=h.context;l.save(),de(l,this.getObject(t,n)),l.globalCompositeOperation="source-in",l.fillStyle=i?s.getPattern(l,this,wt(e),Kt):s,l.fillRect(0,0,a,r),l.restore(),e.save(),e.transform(...o),e.scale(1,-1),he(e,h.canvas,0,0,a,r,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);e?this.paintInlineImageXObject(e):S("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n)return void S("Dependent image isn't ready yet");const a=n.width,r=n.height,o=[];for(let t=0,n=i.length;t<n;t+=2)o.push({transform:[e,0,0,s,i[t],i[t+1]],x:0,y:0,w:a,h:r});this.paintInlineImageXObjectGroup(n,o)}applyTransferMapsToCanvas(t){return"none"!==this.current.transferMaps&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return t.bitmap;const{bitmap:e,width: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(),!l){const{filter:t}=i;"none"!==t&&""!==t&&(i.filter="none")}let n;if(i.scale(1/e,-1/s),t.bitmap)n=this.applyTransferMapsToBitmap(t);else if("function"==typeof HTMLElement&&t instanceof HTMLElement||!t.data)n=t;else{const i=this.cachedCanvases.getCanvas("inlineImage",e,s).context;ce(i,t),n=this.applyTransferMapsToCanvas(i)}const a=this._scaleImage(n,wt(i));i.imageSmoothingEnabled=ge(At(i),t.interpolate),he(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 e=t.width,s=t.height,n=this.cachedCanvases.getCanvas("inlineImage",e,s).context;ce(n,t),i=this.applyTransferMapsToCanvas(n)}for(const t of e)s.save(),s.transform(...t.transform),s.scale(1,-1),he(s,i,t.x,t.y,t.w,t.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){"OC"===t?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===ve?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=At(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),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(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let a,r;if(0===s&&0===i){const s=Math.abs(e),i=Math.abs(n);if(s===i)if(0===t)a=r=1/s;else{const e=s*t;a=r=e<1?1/e:1}else if(0===t)a=1/s,r=1/i;else{const e=s*t,n=i*t;a=e<1?1/e:1,r=n<1?1/n:1}}else{const o=Math.abs(e*n-s*i),h=Math.hypot(e,s),l=Math.hypot(i,n);if(0===t)a=l/o,r=h/o;else{const e=t*o;a=l>e?l/e:1,r=h>e?h/e: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,1===i&&1===n)return void e.stroke();const a=e.getLineDash();if(t&&e.save(),e.scale(i,n),a.length>0){const t=Math.max(i,n);e.setLineDash(a.map((e=>e/t))),e.lineDashOffset/=t}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 t in A)void 0!==ye.prototype[t]&&(ye.prototype[A[t]]=ye.prototype[t]);class Ae{static#Re=null;static#Le="";static get workerPort(){return this.#Re}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Re=t}static get workerSrc(){return this.#Le}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Le=t}}function we(t){switch(t instanceof Error||"object"==typeof t&&null!==t||T('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new B(t.message);case"MissingPDFException":return new F(t.message);case"PasswordException":return new L(t.message,t.code);case"UnexpectedResponseException":return new O(t.message,t.status);case"UnknownErrorException":return new I(t.message,t.details);default:return new I(t.message,t.toString())}}class xe{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),this._onComObjOnMessage=t=>{const e=t.data;if(e.targetName!==this.sourceName)return;if(e.stream)return void this.#Ie(e);if(e.callback){const t=e.callbackId,s=this.callbackCapabilities[t];if(!s)throw new Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],1===e.callback)s.resolve(e.data);else{if(2!==e.callback)throw new Error("Unexpected callback case");s.reject(we(e.reason))}return}const i=this.actionHandler[e.action];if(!i)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const t=this.sourceName,n=e.sourceName;new Promise((function(t){t(i(e.data))})).then((function(i){s.postMessage({sourceName:t,targetName:n,callback:1,callbackId:e.callbackId,data:i})}),(function(i){s.postMessage({sourceName:t,targetName:n,callback:2,callbackId:e.callbackId,reason:we(i)})}))}else e.streamId?this.#De(e):i(e.data)},s.addEventListener("message",this._onComObjOnMessage)}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(t){n.reject(t)}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:s=>{const h=Promise.withResolvers();return this.streamControllers[n]={controller:s,startCall:h,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:s.desiredSize},i),h.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:6,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{M(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[n].cancelCall=e,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:a,targetName:r,stream:1,streamId:n,reason:we(t)}),e.promise}},s)}#De(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:4,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:3,streamId:e}),delete a.streamSinks[e])},error(t){M(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:5,streamId:e,reason:we(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,new Promise((function(e){e(r(t.data,o))})).then((function(){n.postMessage({sourceName:s,targetName:i,stream:8,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:s,targetName:i,stream:8,streamId:e,reason:we(t)})}))}#Ie(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 8:t.success?a.startCall.resolve():a.startCall.reject(we(t.reason));break;case 7:t.success?a.pullCall.resolve():a.pullCall.reject(we(t.reason));break;case 6:if(!r){n.postMessage({sourceName:s,targetName:i,stream:7,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,new Promise((function(t){t(r.onPull?.())})).then((function(){n.postMessage({sourceName:s,targetName:i,stream:7,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:s,targetName:i,stream:7,streamId:e,reason:we(t)})}));break;case 4:if(M(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case 3:if(M(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#Fe(a,e);break;case 5:M(a,"error should have stream controller"),a.controller.error(we(t.reason)),this.#Fe(a,e);break;case 2:t.success?a.cancelCall.resolve():a.cancelCall.reject(we(t.reason)),this.#Fe(a,e);break;case 1:if(!r)break;new Promise((function(e){e(r.onCancel?.(we(t.reason)))})).then((function(){n.postMessage({sourceName:s,targetName:i,stream:2,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:s,targetName:i,stream:2,streamId:e,reason:we(t)})})),r.sinkCapability.reject(we(t.reason)),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#Fe(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class _e{#Oe;#Ne;constructor({parsedData:t,rawData:e}){this.#Oe=t,this.#Ne=e}getRaw(){return this.#Ne}get(t){return this.#Oe.get(t)??null}getAll(){return j(this.#Oe)}has(t){return this.#Oe.has(t)}}const Ee=Symbol("INTERNAL");class Ce{#Be=!1;#He=!1;#ze=!1;#je=!0;constructor(t,{name:e,intent:s,usage:i}){this.#Be=!!(2&t),this.#He=!!(4&t),this.name=e,this.intent=s,this.usage=i}get visible(){if(this.#ze)return this.#je;if(!this.#je)return!1;const{print:t,view:e}=this.usage;return this.#Be?"OFF"!==e?.viewState:!this.#He||"OFF"!==t?.printState}_setVisible(t,e,s=!1){t!==Ee&&T("Internal method `_setVisible` called."),this.#ze=s,this.#je=e}}class Se{#$e=null;#Ue=new Map;#Ve=null;#Ge=null;constructor(t,e=2){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Ge=t.order;for(const s of t.groups)this.#Ue.set(s.id,new Ce(e,s));if("OFF"===t.baseState)for(const t of this.#Ue.values())t._setVisible(Ee,!1);for(const e of t.on)this.#Ue.get(e)._setVisible(Ee,!0);for(const e of t.off)this.#Ue.get(e)._setVisible(Ee,!1);this.#Ve=this.getHash()}}#We(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const e=t[i];let n;if(Array.isArray(e))n=this.#We(e);else{if(!this.#Ue.has(e))return S(`Optional content group not found: ${e}`),!0;n=this.#Ue.get(e).visible}switch(s){case"And":if(!n)return!1;break;case"Or":if(n)return!0;break;case"Not":return!n;default:return!0}}return"And"===s}isVisible(t){if(0===this.#Ue.size)return!0;if(!t)return C("Optional content group not defined."),!0;if("OCG"===t.type)return this.#Ue.has(t.id)?this.#Ue.get(t.id).visible:(S(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#We(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#Ue.has(e))return S(`Optional content group not found: ${e}`),!0;if(this.#Ue.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#Ue.has(e))return S(`Optional content group not found: ${e}`),!0;if(!this.#Ue.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#Ue.has(e))return S(`Optional content group not found: ${e}`),!0;if(!this.#Ue.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#Ue.has(e))return S(`Optional content group not found: ${e}`),!0;if(this.#Ue.get(e).visible)return!1}return!0}return S(`Unknown optional content policy ${t.policy}.`),!0}return S(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0){const s=this.#Ue.get(t);s?(s._setVisible(Ee,!!e,!0),this.#$e=null):S(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let s;for(const e of t){switch(e){case"ON":case"OFF":case"Toggle":s=e;continue}const t=this.#Ue.get(e);if(t)switch(s){case"ON":t._setVisible(Ee,!0);break;case"OFF":t._setVisible(Ee,!1);break;case"Toggle":t._setVisible(Ee,!t.visible)}}this.#$e=null}get hasInitialVisibility(){return null===this.#Ve||this.getHash()===this.#Ve}getOrder(){return this.#Ue.size?this.#Ge?this.#Ge.slice():[...this.#Ue.keys()]:null}getGroups(){return this.#Ue.size>0?j(this.#Ue):null}getGroup(t){return this.#Ue.get(t)||null}getHash(){if(null!==this.#$e)return this.#$e;const t=new Bt;for(const[e,s]of this.#Ue)t.update(`${e}:${s.visible}`);return this.#$e=t.hexdigest()}}class Te{constructor(t,{disableRange:e=!1,disableStream:s=!1}){M(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 t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})})),t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})})),t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})})),t.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;void 0===t?this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s):M(this._rangeReaders.some((function(e){return e._begin===t&&(e._enqueue(s),!0)})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){M(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Me(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new ke(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 Me{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=lt(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){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 t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class ke{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(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function Pe({getResponseHeader:t,isHttp:e,rangeChunkSize:s,disableRange:i}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t("Content-Length"),10);return Number.isInteger(a)?(n.suggestedLength=a,a<=2*s||i||!e||"bytes"!==t("Accept-Ranges")||"identity"!==(t("Content-Encoding")||"identity")||(n.allowRangeRequests=!0),n):n}function Re(t){const e=t("Content-Disposition");if(e){let t=function(t){let e=!0,s=i("filename\\*","i").exec(t);if(s){s=s[1];let t=r(s);return t=unescape(t),t=o(t),t=h(t),a(t)}if(s=function(t){const e=[];let s;const n=i("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(s=n.exec(t));){let[,t,i,n]=s;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[i,n]}const a=[];for(let t=0;t<e.length&&t in e;++t){let[s,i]=e[t];i=r(i),s&&(i=unescape(i),0===t&&(i=o(i))),a.push(i)}return a.join("")}(t),s)return a(h(s));if(s=i("filename","i").exec(t),s){s=s[1];let t=r(s);return t=h(t),a(t)}function i(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function n(t,s){if(t){if(!/^[\x00-\xFF]+$/.test(s))return s;try{const i=new TextDecoder(t,{fatal:!0}),n=z(s);s=i.decode(n),e=!1}catch{}}return s}function a(t){return e&&/[\x80-\xff]/.test(t)&&(t=n("utf-8",t),e&&(t=n("iso-8859-1",t))),t}function r(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const s=e[t].indexOf('"');-1!==s&&(e[t]=e[t].slice(0,s),e.length=t+1),e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function o(t){const e=t.indexOf("'");return-1===e?t:n(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function h(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(t,e,s,i){if("q"===s||"Q"===s)return n(e,i=(i=i.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(t,e){return String.fromCharCode(parseInt(e,16))})));try{i=atob(i)}catch{}return n(e,i)}))}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(lt(t))return t}return null}function Le(t,e){return 404===t||0===t&&e.startsWith("file:")?new F('Missing PDF "'+e+'".'):new O(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t)}function Ie(t){return 200===t||206===t}function De(t,e,s){return{method:"GET",headers:t,signal:s.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function Fe(t){const e=new Headers;for(const s in t){const i=t[s];void 0!==i&&e.append(s,i)}return e}function Oe(t){return t instanceof Uint8Array?t.buffer:t instanceof ArrayBuffer?t:(S(`getArrayBuffer - unexpected data format: ${t}`),new Uint8Array(t).buffer)}class Ne{constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.httpHeaders=this.isHttp&&t.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return M(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new Be(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new He(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 Be{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,this._headers=Fe(this._stream.httpHeaders);const s=e.url;fetch(s,De(this._headers,this._withCredentials,this._abortController)).then((t=>{if(!Ie(t.status))throw Le(t.status,s);this._reader=t.body.getReader(),this._headersCapability.resolve();const e=e=>t.headers.get(e),{allowRangeRequests:i,suggestedLength:n}=Pe({getResponseHeader:e,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=i,this._contentLength=n||this._contentLength,this._filename=Re(e),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new B("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:Oe(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class He{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,this._headers=Fe(this._stream.httpHeaders),this._headers.append("Range",`bytes=${e}-${s-1}`);const n=i.url;fetch(n,De(this._headers,this._withCredentials,this._abortController)).then((t=>{if(!Ie(t.status))throw Le(t.status,n);this._readCapability.resolve(),this._reader=t.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:Oe(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class ze{constructor(t,e={}){this.url=t,this.isHttp=/^https?:/i.test(t),this.httpHeaders=this.isHttp&&e.httpHeaders||Object.create(null),this.withCredentials=e.withCredentials||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,s){const i={begin:t,end:e};for(const t in s)i[t]=s[t];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 t in this.httpHeaders){const s=this.httpHeaders[t];void 0!==s&&e.setRequestHeader(t,s)}return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=206):i.expectedStatus=200,e.responseType="arraybuffer",t.onError&&(e.onerror=function(s){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),4!==i.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===i.status&&this.isHttp)return void s.onError?.(i.status);const n=i.status||200;if((200!==n||206!==s.expectedStatus)&&n!==s.expectedStatus)return void s.onError?.(i.status);const a=function(t){const e=t.response;return"string"!=typeof e?e:z(e).buffer}(i);if(206===n){const t=i.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);s.onDone({begin:parseInt(e[1],10),chunk:a})}else a?s.onDone({begin:0,chunk:a}):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 je{constructor(t){this._source=t,this._manager=new ze(t.url,{httpHeaders:t.httpHeaders,withCredentials:t.withCredentials}),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 M(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new $e(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Ue(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 $e{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._headersReceivedCapability=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=t=>e.getResponseHeader(t),{allowRangeRequests:i,suggestedLength:n}=Pe({getResponseHeader:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=Re(s),this._isRangeSupported&&this._manager.abortRequest(t),this._headersReceivedCapability.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 t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=Le(t,this._url),this._headersReceivedCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.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._headersReceivedCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class Ue{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 t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=Le(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const Ve=/^file:\/\/\/[a-zA-Z]:\//;class Ge{constructor(t){this.source=t,this.url=function(t){const e=Wt.get("url"),s=e.parse(t);return"file:"===s.protocol||s.host?s:/^[a-z]:[/\\]/i.test(t)?e.parse(`file:///${t}`):(s.host||(s.protocol="file:"),s)}(t.url),this.isHttp="http:"===this.url.protocol||"https:"===this.url.protocol,this.isFsUrl="file:"===this.url.protocol,this.httpHeaders=this.isHttp&&t.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return M(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new Qe(this):new Xe(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=this.isFsUrl?new Je(this,t,e):new Ye(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 We{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 null===t?(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){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new B("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class qe{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 null===t?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),this._storedError&&this._readableStream.destroy(this._storedError)}}function Ke(t,e){return{protocol:t.protocol,auth:t.auth,host:t.hostname,port:t.port,path:t.path,method:"GET",headers:e}}class Xe extends We{constructor(t){super(t);const e=e=>{if(404===e.statusCode){const t=new F(`Missing PDF "${this._url}".`);return this._storedError=t,void this._headersCapability.reject(t)}this._headersCapability.resolve(),this._setReadableStream(e);const s=t=>this._readableStream.headers[t.toLowerCase()],{allowRangeRequests:i,suggestedLength:n}=Pe({getResponseHeader:s,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=i,this._contentLength=n||this._contentLength,this._filename=Re(s)};if(this._request=null,"http:"===this._url.protocol){const s=Wt.get("http");this._request=s.request(Ke(this._url,t.httpHeaders),e)}else{const s=Wt.get("https");this._request=s.request(Ke(this._url,t.httpHeaders),e)}this._request.on("error",(t=>{this._storedError=t,this._headersCapability.reject(t)})),this._request.end()}}class Ye extends qe{constructor(t,e,s){super(t),this._httpHeaders={};for(const e in t.httpHeaders){const s=t.httpHeaders[e];void 0!==s&&(this._httpHeaders[e]=s)}this._httpHeaders.Range=`bytes=${e}-${s-1}`;const i=t=>{if(404!==t.statusCode)this._setReadableStream(t);else{const t=new F(`Missing PDF "${this._url}".`);this._storedError=t}};if(this._request=null,"http:"===this._url.protocol){const t=Wt.get("http");this._request=t.request(Ke(this._url,this._httpHeaders),i)}else{const t=Wt.get("https");this._request=t.request(Ke(this._url,this._httpHeaders),i)}this._request.on("error",(t=>{this._storedError=t})),this._request.end()}}class Qe extends We{constructor(t){super(t);let e=decodeURIComponent(this._url.path);Ve.test(this._url.href)&&(e=e.replace(/^\//,""));const s=Wt.get("fs");s.promises.lstat(e).then((t=>{this._contentLength=t.size,this._setReadableStream(s.createReadStream(e)),this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new F(`Missing PDF "${e}".`)),this._storedError=t,this._headersCapability.reject(t)}))}}class Je extends qe{constructor(t,e,s){super(t);let i=decodeURIComponent(this._url.path);Ve.test(this._url.href)&&(i=i.replace(/^\//,""));const n=Wt.get("fs");this._setReadableStream(n.createReadStream(i,{start:e,end:s-1}))}}const Ze=30;class ts{#qe=Promise.withResolvers();#ft=null;#Ke=!1;#Xe=!!globalThis.FontInspector?.enabled;#Ye=null;#Qe=null;#Je=0;#Ze=0;#ts=null;#es=null;#ss=0;#is=0;#ns=Object.create(null);#as=[];#rs=null;#os=[];#hs=new WeakMap;#ls=null;static#cs=new Map;static#ds=new Map;static#us=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#rs=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#rs=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#ft=this.#es=e,this.#is=s.scale*(globalThis.devicePixelRatio||1),this.#ss=s.rotation,this.#Qe={prevFontSize:null,prevFontFamily:null,div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:a,pageY:r}=s.rawDims;this.#ls=[1,0,0,-1,-a,r+n],this.#Ze=i,this.#Je=n,xt(e,s),this.#qe.promise.catch((()=>{})).then((()=>{ts.#us.delete(this),this.#Qe=null,this.#ns=null}))}render(){const t=()=>{this.#ts.read().then((({value:e,done:s})=>{s?this.#qe.resolve():(this.#Ye??=e.lang,Object.assign(this.#ns,e.styles),this.#ps(e.items),t())}),this.#qe.reject)};return this.#ts=this.#rs.getReader(),ts.#us.add(this),t(),this.#qe.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#ss&&(e?.(),this.#ss=i,xt(this.#es,{rotation:i})),s!==this.#is){e?.(),this.#is=s;const t={prevFontSize:null,prevFontFamily:null,div:null,properties:null,ctx:ts.#gs(this.#Ye)};for(const e of this.#os)t.properties=this.#hs.get(e),t.div=e,this.#ms(t)}}cancel(){const t=new B("TextLayer task cancelled.");this.#ts?.cancel(t).catch((()=>{})),this.#ts=null,this.#qe.reject(t)}get textDivs(){return this.#os}get textContentItemsStr(){return this.#as}#ps(t){if(this.#Ke)return;this.#Qe.ctx||=ts.#gs(this.#Ye);const e=this.#os,s=this.#as;for(const i of t){if(e.length>1e5)return S("Ignoring additional textDivs for performance reasons."),void(this.#Ke=!0);if(void 0!==i.str)s.push(i.str),this.#fs(i);else if("beginMarkedContentProps"===i.type||"beginMarkedContent"===i.type){const t=this.#ft;this.#ft=document.createElement("span"),this.#ft.classList.add("markedContent"),null!==i.id&&this.#ft.setAttribute("id",`${i.id}`),t.append(this.#ft)}else"endMarkedContent"===i.type&&(this.#ft=this.#ft.parentNode)}}#fs(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#os.push(e);const i=V.transform(this.#ls,t.transform);let n=Math.atan2(i[1],i[0]);const a=this.#ns[t.fontName];a.vertical&&(n+=Math.PI/2);const r=this.#Xe&&a.fontSubstitution||a.fontFamily,o=Math.hypot(i[2],i[3]),h=o*ts.#bs(r,this.#Ye);let l,c;0===n?(l=i[4],c=i[5]-h):(l=i[4]+h*Math.sin(n),c=i[5]-h*Math.cos(n));const d="calc(var(--scale-factor)*",u=e.style;this.#ft===this.#es?(u.left=`${(100*l/this.#Ze).toFixed(2)}%`,u.top=`${(100*c/this.#Je).toFixed(2)}%`):(u.left=`${d}${l.toFixed(2)}px)`,u.top=`${d}${c.toFixed(2)}px)`),u.fontSize=`${d}${o.toFixed(2)}px)`,u.fontFamily=r,s.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#Xe&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==n&&(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 e=Math.abs(t.transform[0]),s=Math.abs(t.transform[3]);e!==s&&Math.max(e,s)/Math.min(e,s)>1.5&&(p=!0)}if(p&&(s.canvasWidth=a.vertical?t.height:t.width),this.#hs.set(e,s),this.#Qe.div=e,this.#Qe.properties=s,this.#ms(this.#Qe),s.hasText&&this.#ft.append(e),s.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#ft.append(t)}}#ms(t){const{div:e,properties:s,ctx:i,prevFontSize:n,prevFontFamily:a}=t,{style:r}=e;let o="";if(0!==s.canvasWidth&&s.hasText){const{fontFamily:h}=r,{canvasWidth:l,fontSize:c}=s;n===c&&a===h||(i.font=`${c*this.#is}px ${h}`,t.prevFontSize=c,t.prevFontFamily=h);const{width:d}=i.measureText(e.textContent);d>0&&(o=`scaleX(${l*this.#is/d})`)}0!==s.angle&&(o=`rotate(${s.angle}deg) ${o}`),o.length>0&&(r.transform=o)}static cleanup(){if(!(this.#us.size>0)){this.#cs.clear();for(const{canvas:t}of this.#ds.values())t.remove();this.#ds.clear()}}static#gs(t=null){let e=this.#ds.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}),this.#ds.set(t,e)}return e}static#bs(t,e){const s=this.#cs.get(t);if(s)return s;const i=this.#gs(e),n=i.font;i.canvas.width=i.canvas.height=Ze,i.font=`30px ${t}`;const a=i.measureText("");let r=a.fontBoundingBoxAscent,o=Math.abs(a.fontBoundingBoxDescent);if(r){const e=r/(r+o);return this.#cs.set(t,e),i.canvas.width=i.canvas.height=0,i.font=n,e}i.strokeStyle="red",i.clearRect(0,0,Ze,Ze),i.strokeText("g",0,0);let h=i.getImageData(0,0,Ze,Ze).data;o=0;for(let t=h.length-1-3;t>=0;t-=4)if(h[t]>0){o=Math.ceil(t/4/Ze);break}i.clearRect(0,0,Ze,Ze),i.strokeText("A",0,Ze),h=i.getImageData(0,0,Ze,Ze).data,r=0;for(let t=0,e=h.length;t<e;t+=4)if(h[t]>0){r=Ze-Math.floor(t/4/Ze);break}i.canvas.width=i.canvas.height=0,i.font=n;const l=r?r/(r+o):.8;return this.#cs.set(t,l),l}}function es(){mt("`renderTextLayer`, please use `TextLayer` instead.");const{textContentSource:t,container:e,viewport:s,...i}=arguments[0],n=Object.keys(i);n.length>0&&S("Ignoring `renderTextLayer` parameters: "+n.join(", "));const a=new ts({textContentSource:t,container:e,viewport:s}),{textDivs:r,textContentItemsStr:o}=a;return{promise:a.render(),textDivs:r,textContentItemsStr:o}}function ss(){mt("`updateTextLayer`, please use `TextLayer` instead.")}class is{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};return function t(s){if(!s)return;let i=null;const n=s.name;if("#text"===n)i=s.value;else{if(!is.shouldBuildText(n))return;s?.attributes?.textContent?i=s.attributes.textContent:s.value&&(i=s.value)}if(null!==i&&e.push({str:i}),s.children)for(const e of s.children)t(e)}(t),s}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const ns=65536,as=l?class extends Y{_createCanvas(t,e){return Wt.get("canvas").createCanvas(t,e)}}:class extends Y{constructor({ownerDocument:t=globalThis.document}={}){super(),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}},rs=l?class extends Q{_fetchData(t,e){return qt(t).then((t=>({cMapData:t,compressionType:e})))}}:it,os=l?class extends X{}:class extends X{#vs;#ys;#As;#ws;#xs;#f=0;constructor({docId:t,ownerDocument:e=globalThis.document}={}){super(),this.#As=t,this.#ws=e}get#v(){return this.#vs||=new Map}get#_s(){return this.#xs||=new Map}get#Es(){if(!this.#ys){const t=this.#ws.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.#ws.createElementNS(tt,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#ys=this.#ws.createElementNS(tt,"defs"),t.append(s),s.append(this.#ys),this.#ws.body.append(t)}return this.#ys}#Cs(t){if(1===t.length){const e=t[0],s=new Array(256);for(let t=0;t<256;t++)s[t]=e[t]/255;const i=s.join(",");return[i,i,i]}const[e,s,i]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++)n[t]=e[t]/255,a[t]=s[t]/255,r[t]=i[t]/255;return[n.join(","),a.join(","),r.join(",")]}addFilter(t){if(!t)return"none";let e=this.#v.get(t);if(e)return e;const[s,i,n]=this.#Cs(t),a=1===t.length?s:`${s}${i}${n}`;if(e=this.#v.get(a),e)return this.#v.set(t,e),e;const r=`g_${this.#As}_transfer_map_${this.#f++}`,o=`url(#${r})`;this.#v.set(t,o),this.#v.set(a,o);const h=this.#Ss(r);return this.#Ts(s,i,n,h),o}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#_s.get(i);if(n?.key===s)return n.url;if(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#_s.set(i,n)),!t||!e)return n.url;const a=this.#Ms(t);t=V.makeHexColor(...a);const r=this.#Ms(e);if(e=V.makeHexColor(...r),this.#Es.style.color="","#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const h=o.join(","),l=`g_${this.#As}_hcm_filter`,c=n.filter=this.#Ss(l);this.#Ts(h,h,h,c),this.#ks(c);const d=(t,e)=>{const s=a[t]/255,i=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=s+t/e*(i-s);return n.join(",")};return this.#Ts(d(0,5),d(1,5),d(2,5),c),n.url=`url(#${l})`,n.url}addAlphaFilter(t){let e=this.#v.get(t);if(e)return e;const[s]=this.#Cs([t]),i=`alpha_${s}`;if(e=this.#v.get(i),e)return this.#v.set(t,e),e;const n=`g_${this.#As}_alpha_map_${this.#f++}`,a=`url(#${n})`;this.#v.set(t,a),this.#v.set(i,a);const r=this.#Ss(n);return this.#Ps(s,r),a}addLuminosityFilter(t){let e,s,i=this.#v.get(t||"luminosity");if(i)return i;if(t?([e]=this.#Cs([t]),s=`luminosity_${e}`):s="luminosity",i=this.#v.get(s),i)return this.#v.set(t,i),i;const n=`g_${this.#As}_luminosity_map_${this.#f++}`,a=`url(#${n})`;this.#v.set(t,a),this.#v.set(s,a);const r=this.#Ss(n);return this.#Rs(r),t&&this.#Ps(e,r),a}addHighlightHCMFilter(t,e,s,i,n){const a=`${e}-${s}-${i}-${n}`;let r=this.#_s.get(t);if(r?.key===a)return r.url;if(r?(r.filter?.remove(),r.key=a,r.url="none",r.filter=null):(r={key:a,url:"none",filter:null},this.#_s.set(t,r)),!e||!s)return r.url;const[o,h]=[e,s].map(this.#Ms.bind(this));let l=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),[d,u]=[i,n].map(this.#Ms.bind(this));c<l&&([l,c,d,u]=[c,l,u,d]),this.#Es.style.color="";const p=(t,e,s)=>{const i=new Array(256),n=(c-l)/s,a=t/255,r=(e-t)/(255*s);let o=0;for(let t=0;t<=s;t++){const e=Math.round(l+t*n),s=a+t*r;for(let t=o;t<=e;t++)i[t]=s;o=e+1}for(let t=o;t<256;t++)i[t]=i[o-1];return i.join(",")},g=`g_${this.#As}_hcm_${t}_filter`,m=r.filter=this.#Ss(g);return this.#ks(m),this.#Ts(p(d[0],u[0],5),p(d[1],u[1],5),p(d[2],u[2],5),m),r.url=`url(#${g})`,r.url}destroy(t=!1){t&&0!==this.#_s.size||(this.#ys&&(this.#ys.parentNode.parentNode.remove(),this.#ys=null),this.#vs&&(this.#vs.clear(),this.#vs=null),this.#f=0)}#Rs(t){const e=this.#ws.createElementNS(tt,"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)}#ks(t){const e=this.#ws.createElementNS(tt,"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)}#Ss(t){const e=this.#ws.createElementNS(tt,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#Es.append(e),e}#Ls(t,e,s){const i=this.#ws.createElementNS(tt,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#Ts(t,e,s,i){const n=this.#ws.createElementNS(tt,"feComponentTransfer");i.append(n),this.#Ls(n,"feFuncR",t),this.#Ls(n,"feFuncG",e),this.#Ls(n,"feFuncB",s)}#Ps(t,e){const s=this.#ws.createElementNS(tt,"feComponentTransfer");e.append(s),this.#Ls(s,"feFuncA",t)}#Ms(t){return this.#Es.style.color=t,yt(getComputedStyle(this.#Es).getPropertyValue("color"))}},hs=l?class extends J{_fetchData(t){return qt(t)}}:nt;function ls(t){if("string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t}),"object"!=typeof t)throw new Error("Invalid parameter in getDocument, need parameter object.");if(!t.url&&!t.data&&!t.range)throw new Error("Invalid parameter object: need either .data, .range or .url");const e=new ds,{docId:s}=e,i=t.url?function(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(l&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,n=t.data?function(t){if(l&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return z(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,a=t.httpHeaders||null,r=!0===t.withCredentials,o=t.password??null,h=t.range instanceof us?t.range:null,c=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:ns;let d=t.worker instanceof bs?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||ht(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||rs,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,v=t.StandardFontDataFactory||hs,y=!0!==t.stopAtErrors,A=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,w=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!l,E=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,C="boolean"==typeof t.disableFontFace?t.disableFontFace:l,S=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,k=!0===t.disableRange,P=!0===t.disableStream,R=!0===t.disableAutoFetch,L=!0===t.pdfBug,I=h?h.length:t.length??NaN,D="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!l&&!C,F="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===it&&v===nt&&g&&b&&pt(g,document.baseURI)&&pt(b,document.baseURI),O=t.canvasFactory||new as({ownerDocument:M}),N=t.filterFactory||new os({docId:s,ownerDocument:M});_(u);const B={canvasFactory:O,filterFactory:N};if(F||(B.cMapReaderFactory=new f({baseUrl:g,isCompressed:m}),B.standardFontDataFactory=new v({baseUrl:b})),!d){const t={verbosity:u,port:Ae.workerPort};d=t.port?bs.fromPort(t):new bs(t),e._worker=d}const H={docId:s,apiVersion:"4.3.136",data:n,password:o,disableAutoFetch:R,rangeChunkSize:c,length:I,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:A,disableFontFace:C,ignoreErrors:y,isEvalSupported:w,isOffscreenCanvasSupported:x,canvasMaxAreaInBytes:E,fontExtraProperties:S,useSystemFonts:D,cMapUrl:F?g:null,standardFontDataUrl:F?b:null}},j={disableFontFace:C,fontExtraProperties:S,ownerDocument:M,pdfBug:L,styleElement:null,loadingParams:{disableAutoFetch:R,enableXfa:T}};return d.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const t=d.messageHandler.sendWithPromise("GetDocRequest",H,n?[n.buffer]:null);let o;var u;return h?o=new Te(h,{disableRange:k,disableStream:P}):n||(u={url:i,length:I,httpHeaders:a,withCredentials:r,rangeChunkSize:c,disableRange:k,disableStream:P},o=l?"undefined"!=typeof fetch&&"undefined"!=typeof Response&&"body"in Response.prototype&&pt(u.url)?new Ne(u):new Ge(u):pt(u.url)?new Ne(u):new je(u)),t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const i=new xe(s,t,d.port),n=new vs(i,e,o,j,B);e._transport=n,i.send("Ready",null)}))})).catch(e._capability.reject),e}function cs(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class ds{static#As=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+ds.#As++,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 us{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){T("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class ps{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return P(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 gs{#Is=null;#Ds=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new ut:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new As,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 rt({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 P(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=p.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:h=null,printAnnotationStorage:l=null}){this._stats?.time("Overall");const c=this._transport.getRenderingIntent(s,i,l),{renderingIntent:d,cacheKey:u}=c;this.#Ds=!1,this.#Fs(),r||=this._transport.getOptionalContentConfig(d);let g=this._intentStates.get(u);g||(g=Object.create(null),this._intentStates.set(u,g)),g.streamReaderCancelTimeout&&(clearTimeout(g.streamReaderCancelTimeout),g.streamReaderCancelTimeout=null);const m=!!(4&d);g.displayReadyCapability||(g.displayReadyCapability=Promise.withResolvers(),g.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(c));const f=t=>{g.renderTasks.delete(b),(this._maybeCleanupAfterRender||m)&&(this.#Ds=!0),this.#Os(!m),t?(b.capability.reject(t),this._abortOperatorList({intentState:g,reason:t instanceof Error?t:new Error(t)})):b.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},b=new xs({callback:f,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:!m,pdfBug:this._pdfBug,pageColors:h});(g.renderTasks||=new Set).add(b);const v=b.task;return Promise.all([g.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)f();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&d))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:t,optionalContentConfig:e}),b.operatorListChanged()}})).catch(f),v}getOperatorList({intent:t="display",annotationMode:e=p.ENABLE,printAnnotationStorage:s=null}={}){const i=this._transport.getRenderingIntent(t,e,s,!0);let n,a=this._intentStates.get(i.cacheKey);return a||(a=Object.create(null),this._intentStates.set(i.cacheKey,a)),a.opListReadCapability||(n=Object.create(null),n.operatorListChanged=function(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(n))},a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||=new Set).add(n),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(i)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size(t){return t.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>is.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,s){const i=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function e(){i.read().then((function({value:s,done:i}){i?t(n):(n.lang??=s.lang,Object.assign(n.styles,s.styles),n.items.push(...s.items),e())}),s)}()}))}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.#Ds=!1,this.#Fs(),Promise.all(t)}cleanup(t=!1){this.#Ds=!0;const e=this.#Os(!1);return t&&e&&(this._stats&&=new ut),e}#Os(t=!1){if(this.#Fs(),!this.#Ds||this.destroyed)return!1;if(t)return this.#Is=setTimeout((()=>{this.#Is=null,this.#Os(!1)}),5e3),!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#Ds=!1,!0}#Fs(){this.#Is&&(clearTimeout(this.#Is),this.#Is=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 t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#Os(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s}){const{map:i,transfer:n}=s,a=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:i},n).getReader(),r=this._intentStates.get(e);r.streamReader=a;const o=()=>{a.read().then((({value:t,done:e})=>{e?r.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,r),o())}),(t=>{if(r.streamReader=null,!this._transport.destroyed){if(r.operatorList){r.operatorList.lastChunk=!0;for(const t of r.renderTasks)t.operatorListChanged();this.#Os(!0)}if(r.displayReadyCapability)r.displayReadyCapability.reject(t);else{if(!r.opListReadCapability)throw t;r.opListReadCapability.reject(t)}}}))};o()}_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 ot){let s=100;return e.extraDelay>0&&e.extraDelay<1e3&&(s+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})}),s))}}if(t.streamReader.cancel(new B(e.message)).catch((()=>{})),t.streamReader=null,!this._transport.destroyed){for(const[e,s]of this._intentStates)if(s===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class ms{#Ns=new Set;#Bs=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#Bs.then((()=>{for(const t of this.#Ns)t.call(this,s)}))}addEventListener(t,e){this.#Ns.add(e)}removeEventListener(t,e){this.#Ns.delete(e)}terminate(){this.#Ns.clear()}}const fs={isWorkerDisabled:!1,fakeWorkerId:0};l&&(fs.isWorkerDisabled=!0,Ae.workerSrc||="./pdf.worker.mjs"),fs.isSameOrigin=function(t,e){let s;try{if(s=new URL(t),!s.origin||"null"===s.origin)return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},fs.createCDNWrapper=function(t){const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};class bs{static#Hs;constructor({name:t=null,port:e=null,verbosity:s=E()}={}){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(bs.#Hs?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");return(bs.#Hs||=new WeakMap).set(e,this),void this._initializeFromPort(e)}this._initialize()}get promise(){return l?Promise.all([Wt.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 xe("main","worker",t),this._messageHandler.on("ready",(function(){})),this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!fs.isWorkerDisabled&&!bs.#zs){let{workerSrc:t}=bs;try{fs.isSameOrigin(window.location.href,t)||(t=fs.createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new xe("main","worker",e),i=()=>{e.removeEventListener("error",n),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=()=>{this._webWorker||i()};e.addEventListener("error",n),s.on("test",(t=>{e.removeEventListener("error",n),this.destroyed?i():t?(this._messageHandler=s,this._port=e,this._webWorker=e,this._readyCapability.resolve(),s.send("configure",{verbosity:this.verbosity})):(this._setupFakeWorker(),s.destroy(),e.terminate())})),s.on("ready",(t=>{if(e.removeEventListener("error",n),this.destroyed)i();else try{a()}catch{this._setupFakeWorker()}}));const a=()=>{const t=new Uint8Array;s.send("test",t,[t.buffer])};return void a()}catch{C("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){fs.isWorkerDisabled||(S("Setting up fake worker."),fs.isWorkerDisabled=!0),bs._setupFakeWorkerGlobal.then((t=>{if(this.destroyed)return void this._readyCapability.reject(new Error("Worker was destroyed"));const e=new ms;this._port=e;const s="fake"+fs.fakeWorkerId++,i=new xe(s+"_worker",s,e);t.setup(i,e);const n=new xe(s,s+"_worker",e);this._messageHandler=n,this._readyCapability.resolve(),n.send("configure",{verbosity:this.verbosity})})).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),bs.#Hs?.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=this.#Hs?.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 bs(t)}static get workerSrc(){if(Ae.workerSrc)return Ae.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#zs(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return P(this,"_setupFakeWorkerGlobal",(async()=>this.#zs?this.#zs:(await import(this.workerSrc)).WorkerMessageHandler)())}}class vs{#js=new Map;#$s=new Map;#Us=new Map;#Vs=new Map;#Gs=null;constructor(t,e,s,i,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new As,this.fontLoader=new $t({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()}#Ws(t,e=null){const s=this.#js.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return this.#js.set(t,i),i}get annotationStorage(){return P(this,"annotationStorage",new zt)}getRenderingIntent(t,e=p.ENABLE,s=null,i=!1){let n=2,a=Ht;switch(t){case"any":n=1;break;case"display":break;case"print":n=4;break;default:S(`getRenderingIntent - invalid intent: ${t}`)}switch(e){case p.DISABLE:n+=64;break;case p.ENABLE:break;case p.ENABLE_FORMS:n+=16;break;case p.ENABLE_STORAGE:n+=32,a=(4&n&&s instanceof jt?s:this.annotationStorage).serializable;break;default:S(`getRenderingIntent - invalid annotationMode: ${e}`)}return i&&(n+=256),{renderingIntent:n,cacheKey:`${n}_${a.hash}`,annotationStorageSerializable:a}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#Gs?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#$s.values())t.push(e._destroy());this.#$s.clear(),this.#Us.clear(),this.#Vs.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.#js.clear(),this.filterFactory.destroy(),ts.cleanup(),this._networkStream?.cancelAllRequests(new B("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",((t,e)=>{M(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}},e.onPull=()=>{this._fullReader.read().then((function({value:t,done:s}){s?e.close():(M(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{this._fullReader.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}})),t.on("ReaderHeadersReady",(t=>{const s=Promise.withResolvers(),i=this._fullReader;return i.headersReady.then((()=>{i.isStreamingSupported&&i.isRangeSupported||(this._lastProgress&&e.onProgress?.(this._lastProgress),i.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),s.resolve({isStreamingSupported:i.isStreamingSupported,isRangeSupported:i.isRangeSupported,contentLength:i.contentLength})}),s.reject),s.promise})),t.on("GetRangeReader",((t,e)=>{M(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const s=this._networkStream.getRangeReader(t.begin,t.end);s?(e.onPull=()=>{s.read().then((function({value:t,done:s}){s?e.close():(M(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{s.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}):e.close()})),t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new ps(t,this))})),t.on("DocException",(function(t){let s;switch(t.name){case"PasswordException":s=new L(t.message,t.code);break;case"InvalidPDFException":s=new D(t.message);break;case"MissingPDFException":s=new F(t.message);break;case"UnexpectedResponseException":s=new O(t.message,t.status);break;case"UnknownErrorException":s=new I(t.message,t.details);break;default:T("DocException - expected a valid Error.")}e._capability.reject(s)})),t.on("PasswordRequest",(t=>{if(this.#Gs=Promise.withResolvers(),e.onPassword){const s=t=>{t instanceof Error?this.#Gs.reject(t):this.#Gs.resolve({password:t})};try{e.onPassword(s,t.code)}catch(t){this.#Gs.reject(t)}}else this.#Gs.reject(new L(t.message,t.code));return this.#Gs.promise})),t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)})),t.on("StartRenderPage",(t=>{this.destroyed||this.#$s.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)})),t.on("commonobj",(([e,s,i])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(s){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in i){const t=i.error;S(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,h=new Ut(i,{disableFontFace:n,inspectFont:o});this.fontLoader.bind(h).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&h.data&&(h.data=null),this.commonObjs.resolve(e,h)}));break;case"CopyLocalImage":const{imageRef:l}=i;M(l,"The imageRef must be defined.");for(const t of this.#$s.values())for(const[,s]of t.objs)if(s?.ref===l)return s.dataLen?(this.commonObjs.resolve(e,structuredClone(s)),s.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,i);break;default:throw new Error(`Got unknown common object type ${s}`)}return null})),t.on("obj",(([t,e,s,i])=>{if(this.destroyed)return;const n=this.#$s.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(s){case"Image":n.objs.resolve(t,i),i?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,i);break;default:throw new Error(`Got unknown object type ${s}`)}else i?.bitmap?.close()})),t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})})),t.on("FetchBuiltInCMap",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(t):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")))),t.on("FetchStandardFontData",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(t):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&S("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.#Us.get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((s=>{if(this.destroyed)throw new Error("Transport destroyed");s.refStr&&this.#Vs.set(s.refStr,t);const i=new gs(e,s,this,this._params.pdfBug);return this.#$s.set(e,i),i}));return this.#Us.set(e,i),i}getPageIndex(t){return cs(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Ws("GetFieldObjects")}hasJSActions(){return this.#Ws("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#Ws("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Ws("GetOptionalContentConfig").then((e=>new Se(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#js.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new _e(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#js.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 t of this.#$s.values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#js.clear(),this.filterFactory.destroy(!0),ts.cleanup()}}cachedPageNumber(t){if(!cs(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#Vs.get(e)??null}}const ys=Symbol("INITIAL_DATA");class As{#qs=Object.create(null);#Ks(t){return this.#qs[t]||={...Promise.withResolvers(),data:ys}}get(t,e=null){if(e){const s=this.#Ks(t);return s.promise.then((()=>e(s.data))),null}const s=this.#qs[t];if(!s||s.data===ys)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#qs[t];return!!e&&e.data!==ys}resolve(t,e=null){const s=this.#Ks(t);s.data=e,s.resolve()}clear(){for(const t in this.#qs){const{data:e}=this.#qs[t];e?.bitmap?.close()}this.#qs=Object.create(null)}*[Symbol.iterator](){for(const t in this.#qs){const{data:e}=this.#qs[t];e!==ys&&(yield[t,e])}}}class ws{#Xs=null;constructor(t){this.#Xs=t,this.onContinue=null}get promise(){return this.#Xs.capability.promise}cancel(t=0){this.#Xs.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Xs.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Xs;return t.form||t.canvas&&e?.size>0}}class xs{static#Ys=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:h,useRequestAnimationFrame:l=!1,pdfBug:c=!1,pageColors:d=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=h,this._pdfBug=c,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===l&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new ws(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(xs.#Ys.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.");xs.#Ys.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 ye(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(),xs.#Ys.delete(this._canvas),this.callback(t||new ot(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?window.requestAnimationFrame((()=>{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(),xs.#Ys.delete(this._canvas),this.callback())))}}const _s="4.3.136",Es="0cec64437";function Cs(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function Ss(t){return Math.max(0,Math.min(255,255*t))}class Ts{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=Ss(t),t,t]}static G_HTML([t]){const e=Cs(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(Ss)}static RGB_HTML(t){return`#${t.map(Cs).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[Ss(1-Math.min(1,t+i)),Ss(1-Math.min(1,s+i)),Ss(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;return["CMYK",i,n,a,Math.min(i,n,a)]}}class Ms{static setupStorage(t,e,s,i,n){const a=i.getValue(e,{value:null});switch(s.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===n)break;t.addEventListener("input",(t=>{i.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===s.attributes.type||"checkbox"===s.attributes.type){if(a.value===s.attributes.xfaOn?t.setAttribute("checked",!0):a.value===s.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",(t=>{i.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{if(null!==a.value&&t.setAttribute("value",a.value),"print"===n)break;t.addEventListener("input",(t=>{i.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of s.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const s=t.target.options,n=-1===s.selectedIndex?"":s[s.selectedIndex].value;i.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${i}`);for(const[e,s]of Object.entries(a))if(null!=s)switch(e){case"class":s.length&&t.setAttribute(e,s.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",s);break;case"style":Object.assign(t.style,s);break;case"textContent":t.textContent=s;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,s)}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="richText"!==n,o=t.div;if(o.append(a),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const h=[];if(0===i.children.length){if(i.value){const t=document.createTextNode(i.value);a.append(t),r&&is.shouldBuildText(i.name)&&h.push(t)}return{textDivs:h}}const l=[[i,-1,a]];for(;l.length>0;){const[t,i,a]=l.at(-1);if(i+1===t.children.length){l.pop();continue}const o=t.children[++l.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);h.push(t),a.append(t);continue}const d=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);if(a.append(d),o.attributes&&this.setAttributes({html:d,element:o,storage:e,intent:n,linkService:s}),o.children?.length>0)l.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);r&&is.shouldBuildText(c)&&h.push(t),d.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:h}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const ks=1e3,Ps=new WeakSet;function Rs(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class Ls{static create(t){switch(t.data.annotationType){case 2:return new Ds(t);case 1:return new Fs(t);case 20:switch(t.data.fieldType){case"Tx":return new Ns(t);case"Btn":return t.data.radioButton?new zs(t):t.data.checkBox?new Hs(t):new js(t);case"Ch":return new $s(t);case"Sig":return new Bs(t)}return new Os(t);case 16:return new Us(t);case 3:return new Gs(t);case 4:return new Ws(t);case 5:return new qs(t);case 6:return new Ks(t);case 8:return new Xs(t);case 14:return new Qs(t);case 15:return new Js(t);case 7:return new Ys(t);case 9:return new Zs(t);case 10:return new ti(t);case 11:return new ei(t);case 12:return new si(t);case 13:return new ii(t);case 17:return new ni(t);default:return new Is(t)}}}class Is{#Qs=null;#Js=!1;#Zs=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 hasPopupData(){return Is._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Qs||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#ti(e),this.#Zs?.popup.updateEdited(t)}resetEdited(){this.#Qs&&(this.#ti(this.#Qs.rect),this.#Zs?.popup.resetEdited(),this.#Qs=null)}#ti(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:h,height:l}=Rs(t);e.left=100*(t[0]-r)/n+"%",e.top=100*(a-t[3]+o)/a+"%",0===i?(e.width=100*h/n+"%",e.height=100*l/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 Os||(n.tabIndex=ks);const{style:a}=n;if(a.zIndex=this.parent.zIndex++,e.popupRef&&n.setAttribute("aria-haspopup","dialog"),e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Us){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:r,height:o}=Rs(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,s=e.borderStyle.verticalCornerRadius;if(t>0||s>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${s}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof zs){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case 1:a.borderStyle="solid";break;case 2:a.borderStyle="dashed";break;case 3:S("Unimplemented border style: beveled");break;case 4:S("Unimplemented border style: inset");break;case 5:a.borderBottomStyle="solid"}const i=e.borderColor||null;i?(this.#Js=!0,a.borderColor=V.makeHexColor(0|i[0],0|i[1],0|i[2])):a.borderWidth=0}const h=V.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:l,pageHeight:c,pageX:d,pageY:u}=i.rawDims;a.left=100*(h[0]-d)/l+"%",a.top=100*(h[1]-u)/c+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/l+"%",a.height=100*o/c+"%"):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}=Rs(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=(t,e,s)=>{const i=s.detail[t],n=i[0],a=i.slice(1);s.target.style[e]=Ts[`${n}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:Ts[`${n}_rgb`](a)})};return P(this,"_commonActions",{display:t=>{const{display:e}=t.detail,s=e%2==1;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:s,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail)){const n=t[i]||s[i];n?.(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];a&&(a({detail:{[i]:n},target:t}),delete e[i])}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect;if(1===t.length){const[,{x:a,y:r},{x:o,y:h}]=t[0];if(i===a&&n===r&&e===o&&s===h)return}const{style:a}=this.container;let r;if(this.#Js){const{borderColor:t,borderWidth:e}=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="${t}" stroke-width="${e}">`],this.container.classList.add("hasBorder")}const o=i-e,h=n-s,{svgFactory:l}=this,c=l.createElement("svg");c.classList.add("quadrilateralsContainer"),c.setAttribute("width",0),c.setAttribute("height",0);const d=l.createElement("defs");c.append(d);const u=l.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),d.append(u);for(const[,{x:s,y:i},{x:a,y:c}]of t){const t=l.createElement("rect"),d=(a-e)/o,p=(n-i)/h,g=(s-a)/o,m=(i-c)/h;t.setAttribute("x",d),t.setAttribute("y",p),t.setAttribute("width",g),t.setAttribute("height",m),u.append(t),r?.push(`<rect vector-effect="non-scaling-stroke" x="${d}" y="${p}" width="${g}" height="${m}"/>`)}this.#Js&&(r.push("</g></svg>')"),a.backgroundImage=r.join("")),this.container.append(c),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{container:t,data:e}=this;t.setAttribute("aria-haspopup","dialog");const s=this.#Zs=new Us({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]});this.parent.div.append(s.render())}render(){T("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:t,id:n,exportValues:a}of i){if(-1===t)continue;if(n===e)continue;const i="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Ps.has(r)?s.push({id:n,exportValue:i,domElement:r}):S(`_getElementsByName - element not allowed: ${n}`)}return s}for(const i of document.getElementsByName(t)){const{exportValue:t}=i,n=i.getAttribute("data-element-id");n!==e&&Ps.has(i)&&s.push({id:n,exportValue:t,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")}get _isEditable(){return!1}_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 Ds extends Is{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.#ei(s,t.attachment,t.attachmentDest),i=!0):t.setOCGState?(this.#si(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}#ii(){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.#ii()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#ii()}#ei(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.#ii()}#si(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#ii()}_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.#ii()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#ii(),!this._fieldObjects)return S('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(s||(t.onclick=()=>!1));t.onclick=()=>{s?.();const{fields:t,refs:i,include:n}=e,a=[];if(0!==t.length||0!==i.length){const e=new Set(i);for(const s of t){const t=this._fieldObjects[s]||[];for(const{id:s}of t)e.add(s)}for(const t of Object.values(this._fieldObjects))for(const s of t)e.has(s.id)===n&&a.push(s)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;switch(o.push(e),t.type){case"text":{const s=t.defaultValue||"";r.setValue(e,{value:s});break}case"checkbox":case"radiobutton":{const s=t.defaultValue===t.exportValues;r.setValue(e,{value:s});break}case"combobox":case"listbox":{const s=t.defaultValue||"";r.setValue(e,{value:s});break}default:continue}const s=document.querySelector(`[data-element-id="${e}"]`);s&&(Ps.has(s)?s.dispatchEvent(new Event("resetform")):S(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class Fs extends Is{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 Os extends Is{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return $.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(s,(t=>{if("blur"===s){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===s){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t)}})}))}_setEventListeners(t,e,s,i){for(const[n,a]of s)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,n,a,i),"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":V.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const{fontColor:e}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,i=t.style;let n;const a=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(u*s))||1);n=Math.min(s,a(e/u))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);n=Math.min(s,a(t/u))}i.fontSize=`calc(${n}px * var(--scale-factor))`,i.color=V.makeHexColor(e[0],e[1],e[2]),null!==this.data.textAlignment&&(i.textAlign=["left","center","right"][this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class Ns extends Os{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}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("\n")||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),Ps.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=ks,this._setRequired(s,this.data.required),a&&(s.maxLength=a),s.addEventListener("input",(i=>{t.setValue(e,{value:i.target.value}),this.setPropertyOnSiblings(s,"value",i.target.value,"value"),o.formattedValue=null})),s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";s.value=o.userValue=e,o.formattedValue=null}));let h=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue),o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)})),s.addEventListener("updatefromsandbox",(s=>{this.showElementAndHideCanvas(s.target);const i={value(s){o.userValue=s.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),s.target.value=o.userValue},formattedValue(s){const{formattedValue:i}=s.detail;o.formattedValue=i,null!=i&&s.target!==document.activeElement&&(s.target.value=i),t.setValue(e,{formattedValue:i})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:s=>{const{charLimit:i}=s.detail,{target:n}=s;if(0===i)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",i);let a=o.userValue;!a||a.length<=i||(a=a.slice(0,i),n.value=o.userValue=a,t.setValue(e,{value:a}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}}))}};this._dispatchEventFromSandbox(i,s)})),s.addEventListener("keydown",(t=>{o.commitKey=1;let s=-1;if("Escape"===t.key?s=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):s=2,-1===s)return;const{value:i}=t.target;o.lastCommittedValue!==i&&(o.lastCommittedValue=i,o.userValue=i,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:s,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))}));const i=h;h=null,s.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:s}=t.target;o.userValue=s,o.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),i(t)})),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:s,target:i}=t,{value:n,selectionStart:a,selectionEnd:r}=i;let h=a,l=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(h-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(l+=t[0].length);break}case"deleteContentBackward":a===r&&(h-=1);break;case"deleteContentForward":a===r&&(l+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:s||"",willCommit:!1,selStart:h,selEnd:l}})})),this._setEventListeners(s,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}if(h&&s.addEventListener("blur",h),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;s.classList.add("comb"),s.style.letterSpacing=`calc(${t}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 Bs extends Os{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Hs extends Os{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;"string"==typeof i&&(i="Off"!==i,t.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return Ps.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=ks,n.addEventListener("change",(i=>{const{name:n,checked:a}=i.target;for(const i of this._getElementsByName(n,s)){const s=a&&i.exportValue===e.exportValue;i.domElement&&(i.domElement.checked=s),t.setValue(i.id,{value:s})}t.setValue(s,{value:a})})),n.addEventListener("resetform",(t=>{const s=e.defaultFieldValue||"Off";t.target.checked=s===e.exportValue})),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",(e=>{const i={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(s,{value:e.target.checked})}};this._dispatchEventFromSandbox(i,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class zs extends Os{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("string"==typeof i&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const i of this._getElementsByName(e.fieldName,s))t.setValue(i.id,{value:!1});const n=document.createElement("input");if(Ps.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=ks,n.addEventListener("change",(e=>{const{name:i,checked:n}=e.target;for(const e of this._getElementsByName(i,s))t.setValue(e.id,{value:!1});t.setValue(s,{value:n})})),n.addEventListener("resetform",(t=>{const s=e.defaultFieldValue;t.target.checked=null!=s&&s===e.buttonValue})),this.enableScripting&&this.hasJSActions){const i=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=i===e.detail.value;for(const i of this._getElementsByName(e.target.name)){const e=n&&i.id===s;i.domElement&&(i.domElement.checked=e),t.setValue(i.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class js extends Ds{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))),t}}class $s extends Os{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");Ps.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=ks;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",(t=>{const e=this.data.defaultFieldValue;for(const t of i.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,s.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),n=!1),i.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),i.prepend(t),a=()=>{t.remove(),i.removeEventListener("input",a),a=null},i.addEventListener("input",a)}const r=t=>{const e=t?"value":"textContent",{options:s,multiple:n}=i;return n?Array.prototype.filter.call(s,(t=>t.selected)).map((t=>t[e])):-1===s.selectedIndex?null:s[s.selectedIndex][e]};let o=r(!1);const h=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",(s=>{const n={value(s){a?.();const n=s.detail.value,h=new Set(Array.isArray(n)?n:[n]);for(const t of i.options)t.selected=h.has(t.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(t){i.multiple=!0},remove(s){const n=i.options,a=s.detail.remove;n[a].selected=!1,i.remove(a),n.length>0&&-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0),t.setValue(e,{value:r(!0),items:h(s)}),o=r(!1)},clear(s){for(;0!==i.length;)i.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(s){const{index:n,displayValue:a,exportValue:l}=s.detail.insert,c=i.children[n],d=document.createElement("option");d.textContent=a,d.value=l,c?c.before(d):i.append(d),t.setValue(e,{value:r(!0),items:h(s)}),o=r(!1)},items(s){const{items:n}=s.detail;for(;0!==i.length;)i.remove(0);for(const t of n){const{displayValue:e,exportValue:s}=t,n=document.createElement("option");n.textContent=e,n.value=s,i.append(n)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:r(!0),items:h(s)}),o=r(!1)},indices(s){const i=new Set(s.detail.indices);for(const t of s.target.options)t.selected=i.has(t.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,s)})),i.addEventListener("input",(s=>{const i=r(!0),n=r(!1);t.setValue(e,{value:i}),s.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:n,changeEx:i,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))):i.addEventListener("input",(function(s){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 Us extends Is{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:Is._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Vs({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,e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map((t=>`${K}${t}`)).join(",")),this.container}}class Vs{#ni=this.#ai.bind(this);#ri=this.#oi.bind(this);#hi=this.#li.bind(this);#ci=this.#di.bind(this);#ui=null;#ft=null;#pi=null;#gi=null;#mi=null;#fi=null;#bi=null;#vi=!1;#yi=null;#_=null;#Ai=null;#wi=null;#xi=null;#Qs=null;#_i=!1;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:h,parentRect:l,open:c}){this.#ft=t,this.#xi=i,this.#pi=a,this.#wi=r,this.#fi=o,this.#ui=e,this.#Ai=h,this.#bi=l,this.#mi=s,this.#gi=bt.toDateObject(n),this.trigger=s.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger)t.addEventListener("click",this.#ci),t.addEventListener("mouseenter",this.#hi),t.addEventListener("mouseleave",this.#ri),t.classList.add("popupTriggerArea");for(const t of s)t.container?.addEventListener("keydown",this.#ni);this.#ft.hidden=!0,c&&this.#di()}render(){if(this.#yi)return;const t=this.#yi=document.createElement("div");if(t.className="popup",this.#ui){const e=t.style.outlineColor=V.makeHexColor(...this.#ui);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=V.makeHexColor(...this.#ui.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");if(e.append(s),({dir:s.dir,str:s.textContent}=this.#xi),t.append(e),this.#gi){const t=document.createElement("span");t.classList.add("popupDate"),t.setAttribute("data-l10n-id","pdfjs-annotation-date-string"),t.setAttribute("data-l10n-args",JSON.stringify({date:this.#gi.toLocaleDateString(),time:this.#gi.toLocaleTimeString()})),e.append(t)}const i=this.#Ei;if(i)Ms.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const e=this._formatContents(this.#pi);t.append(e)}this.#ft.append(t)}get#Ei(){const t=this.#wi,e=this.#pi;return!t?.str||e?.str&&e.str!==t.str?null:this.#wi.html||null}get#Ci(){return this.#Ei?.attributes?.style?.fontSize||0}get#Si(){return this.#Ei?.attributes?.style?.color||null}#Ti(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#Si,fontSize:this.#Ci?`calc(${this.#Ci}px * var(--scale-factor))`:""}};for(const s of t.split("\n"))e.push({name:"span",value:s,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 t=0,e=i.length;t<e;++t){const n=i[t];s.append(document.createTextNode(n)),t<e-1&&s.append(document.createElement("br"))}return s}#ai(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#vi)&&this.#di()}updateEdited({rect:t,popupContent:e}){this.#Qs||={contentsObj:this.#pi,richText:this.#wi},t&&(this.#_=null),e&&(this.#wi=this.#Ti(e),this.#pi=null),this.#yi?.remove(),this.#yi=null}resetEdited(){this.#Qs&&(({contentsObj:this.#pi,richText:this.#wi}=this.#Qs),this.#Qs=null,this.#yi?.remove(),this.#yi=null,this.#_=null)}#Mi(){if(null!==this.#_)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#fi;let a=!!this.#bi,r=a?this.#bi:this.#Ai;for(const t of this.#mi)if(!r||null!==V.intersect(t.data.rect,r)){r=t.data.rect,a=!0;break}const o=V.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,l=o[0]+h,c=o[1];this.#_=[100*(l-i)/e,100*(c-n)/s];const{style:d}=this.#ft;d.left=`${this.#_[0]}%`,d.top=`${this.#_[1]}%`}#di(){this.#vi=!this.#vi,this.#vi?(this.#li(),this.#ft.addEventListener("click",this.#ci),this.#ft.addEventListener("keydown",this.#ni)):(this.#oi(),this.#ft.removeEventListener("click",this.#ci),this.#ft.removeEventListener("keydown",this.#ni))}#li(){this.#yi||this.render(),this.isVisible?this.#vi&&this.#ft.classList.add("focused"):(this.#Mi(),this.#ft.hidden=!1,this.#ft.style.zIndex=parseInt(this.#ft.style.zIndex)+1e3)}#oi(){this.#ft.classList.remove("focused"),!this.#vi&&this.isVisible&&(this.#ft.hidden=!0,this.#ft.style.zIndex=parseInt(this.#ft.style.zIndex)-1e3)}forceHide(){this.#_i=this.isVisible,this.#_i&&(this.#ft.hidden=!0)}maybeShow(){this.#_i&&(this.#yi||this.#li(),this.#_i=!1,this.#ft.hidden=!1)}get isVisible(){return!1===this.#ft.hidden}}class Gs extends Is{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=g.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}get _isEditable(){return this.data.hasOwnCanvas}}class Ws extends Is{#ki=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=Rs(t.rect),i=this.svgFactory.create(e,s,!0),n=this.#ki=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.#ki}addHighlightArea(){this.container.classList.add("highlightArea")}}class qs extends Is{#Pi=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=Rs(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,a=this.#Pi=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.#Pi}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ks extends Is{#Ri=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=Rs(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,a=this.#Ri=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.#Ri}addHighlightArea(){this.container.classList.add("highlightArea")}}class Xs extends Is{#Li=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const t=this.data,{width:e,height:s}=Rs(t.rect),i=this.svgFactory.create(e,s,!0);let n=[];for(const e of t.vertices){const s=e.x-t.rect[0],i=t.rect[3]-e.y;n.push(s+","+i)}n=n.join(" ");const a=this.#Li=this.svgFactory.createElement(this.svgElementName);return a.setAttribute("points",n),a.setAttribute("stroke-width",t.borderStyle.width||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.#Li}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ys extends Xs{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Qs extends Is{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 Js extends Is{#Ii=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=g.INK}render(){this.container.classList.add(this.containerClassName);const t=this.data,{width:e,height:s}=Rs(t.rect),i=this.svgFactory.create(e,s,!0);for(const e of t.inkLists){let s=[];for(const i of e){const e=i.x-t.rect[0],n=t.rect[3]-i.y;s.push(`${e},${n}`)}s=s.join(" ");const n=this.svgFactory.createElement(this.svgElementName);this.#Ii.push(n),n.setAttribute("points",s),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),!t.popupRef&&this.hasPopupData&&this._createPopup(),i.append(n)}return this.container.append(i),this.container}getElementsToTriggerPopup(){return this.#Ii}addHighlightArea(){this.container.classList.add("highlightArea")}}class Zs extends Is{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this.container}}class ti extends Is{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 ei extends Is{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 si extends Is{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 ii extends Is{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class ni extends Is{#Di=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||0===e.fillAlpha?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(100*e.fillAlpha)}%);`)),s.addEventListener("dblclick",this.#Fi.bind(this)),this.#Di=s;const{isMac:i}=$.platform;return t.addEventListener("keydown",(t=>{"Enter"===t.key&&(i?t.metaKey:t.ctrlKey)&&this.#Fi()})),!e.popupRef&&this.hasPopupData?this._createPopup():s.classList.add("popupTriggerArea"),t.append(s),t}getElementsToTriggerPopup(){return this.#Di}addHighlightArea(){this.container.classList.add("highlightArea")}#Fi(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class ai{#Oi=null;#Ni=null;#Bi=new Map;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:a}){this.div=t,this.#Oi=e,this.#Ni=s,this.page=n,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=i}#Hi(t,e){const s=t.firstChild||t;s.id=`${K}${e}`,this.div.append(t),this.#Oi?.moveElementInDOM(this.div,t,s,!1)}async render(t){const{annotations:e}=t,s=this.div;xt(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new at,annotationStorage:t.annotationStorage||new zt,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=16===t.annotationType;if(e){const e=i.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:s}=Rs(t.rect);if(e<=0||s<=0)continue}n.data=t;const s=Ls.create(n);if(!s.isRenderable)continue;if(!e&&t.popupRef){const e=i.get(t.popupRef);e?e.push(s):i.set(t.popupRef,[s])}const a=s.render();t.hidden&&(a.style.visibility="hidden"),this.#Hi(a,t.id),s.annotationEditorType>0&&(this.#Bi.set(s.data.id,s),this._annotationEditorUIManager?.renderAnnotationElement(s))}this.#zi()}update({viewport:t}){const e=this.div;this.viewport=t,xt(e,{rotation:t.rotation}),this.#zi(),e.hidden=!1}#zi(){if(!this.#Ni)return;const t=this.div;for(const[e,s]of this.#Ni){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?"CANVAS"===n.nodeName?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s)}this.#Ni.clear()}getEditableAnnotations(){return Array.from(this.#Bi.values())}getEditableAnnotation(t){return this.#Bi.get(t)}}const ri=/\r\n?|\n/g;class oi extends It{#ji=this.editorDivBlur.bind(this);#$i=this.editorDivFocus.bind(this);#Ui=this.editorDivInput.bind(this);#Vi=this.editorDivKeydown.bind(this);#Gi=this.editorDivPaste.bind(this);#ui;#Wi="";#qi=`${this.id}-editor`;#Ci;#Ki=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=oi.prototype,e=t=>t.isEmpty(),s=Rt.TRANSLATE_SMALL,i=Rt.TRANSLATE_BIG;return P(this,"_keyboardManager",new kt([[["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=g.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#ui=t.color||oi._defaultColor||It._defaultLineColor,this.#Ci=t.fontSize||oi._defaultFontSize}static initialize(t,e){It.initialize(t,e,{strings:["pdfjs-free-text-default-content"]});const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case m.FREETEXT_SIZE:oi._defaultFontSize=e;break;case m.FREETEXT_COLOR:oi._defaultColor=e}}updateParams(t,e){switch(t){case m.FREETEXT_SIZE:this.#Xi(e);break;case m.FREETEXT_COLOR:this.#Yi(e)}}static get defaultPropertiesToUpdate(){return[[m.FREETEXT_SIZE,oi._defaultFontSize],[m.FREETEXT_COLOR,oi._defaultColor||It._defaultLineColor]]}get propertiesToUpdate(){return[[m.FREETEXT_SIZE,this.#Ci],[m.FREETEXT_COLOR,this.#ui]]}#Xi(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`,this.translate(0,-(t-this.#Ci)*this.parentScale),this.#Ci=t,this.#Qi()},s=this.#Ci;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#Yi(t){const e=t=>{this.#ui=this.editorDiv.style.color=t},s=this.#ui;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-oi._internalPadding*t,-(oi._internalPadding+this.#Ci)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){this.isInEditMode()||(this.parent.setEditingState(!1),this.parent.updateToolbar(g.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.editorDiv.addEventListener("keydown",this.#Vi),this.editorDiv.addEventListener("focus",this.#$i),this.editorDiv.addEventListener("blur",this.#ji),this.editorDiv.addEventListener("input",this.#Ui),this.editorDiv.addEventListener("paste",this.#Gi))}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#qi),this._isDraggable=!0,this.editorDiv.removeEventListener("keydown",this.#Vi),this.editorDiv.removeEventListener("focus",this.#$i),this.editorDiv.removeEventListener("blur",this.#ji),this.editorDiv.removeEventListener("input",this.#Ui),this.editorDiv.removeEventListener("paste",this.#Gi),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()}#Ji(){const t=[];this.editorDiv.normalize();for(const e of this.editorDiv.childNodes)t.push(oi.#Zi(e));return t.join("\n")}#Qi(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,i=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),s=e.getBoundingClientRect(),e.remove(),e.style.display=i,e.classList.toggle("hidden",n)}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.#Wi,e=this.#Wi=this.#Ji().trimEnd();if(t===e)return;const s=t=>{this.#Wi=t,t?(this.#tn(),this._uiManager.rebuild(this),this.#Qi()):this.remove()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#Qi()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){oi._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.#qi),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),It._l10nPromise.get("pdfjs-free-text-default-content").then((t=>this.editorDiv?.setAttribute("default-content",t))),this.editorDiv.contentEditable=!0;const{style:s}=this.editorDiv;if(s.fontSize=`calc(${this.#Ci}px * var(--scale-factor))`,s.color=this.#ui,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),Ct(this,this.div,["dblclick","keydown"]),this.width){const[s,i]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this.#Ki;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,h]=this.pageDimensions,[l,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(n[0]-l)/o,u=e+this.height-(n[1]-c)/h;break;case 90:d=t+(n[0]-l)/o,u=e-(n[1]-c)/h,[a,r]=[r,-a];break;case 180:d=t-this.width+(n[0]-l)/o,u=e-(n[1]-c)/h,[a,r]=[-a,-r];break;case 270:d=t+(n[0]-l-this.height*h)/o,u=e+(n[1]-c-this.width*o)/h,[a,r]=[-r,a]}this.setAt(d*s,u*i,a,r)}else this.setAt(t*s,e*i,this.width*s,this.height*i);this.#tn(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#Zi(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(ri,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(1===s.length&&"text/plain"===s[0])return;t.preventDefault();const i=oi.#en(e.getData("text")||"").replaceAll(ri,"\n");if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!i.includes("\n"))return a.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:r,startOffset:o}=a,h=[],l=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(l.push(r.nodeValue.slice(o).replaceAll(ri,"")),t!==this.editorDiv){let e=h;for(const s of this.editorDiv.childNodes)s!==t?e.push(oi.#Zi(s)):e=l}h.push(r.nodeValue.slice(0,o).replaceAll(ri,""))}else if(r===this.editorDiv){let t=h,e=0;for(const s of this.editorDiv.childNodes)e++===o&&(t=l),t.push(oi.#Zi(s))}this.#Wi=`${h.join("\n")}${i}${l.join("\n")}`,this.#tn();const c=new Range;let d=h.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(d<=e){c.setStart(t,d),c.setEnd(t,d);break}d-=e}n.removeAllRanges(),n.addRange(c)}#tn(){if(this.editorDiv.replaceChildren(),this.#Wi)for(const t of this.#Wi.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#sn(){return this.#Wi.replaceAll(" "," ")}static#en(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static deserialize(t,e,s){let i=null;if(t instanceof Gs){const{data:{defaultAppearanceData:{fontSize:e,fontColor:s},rect:n,rotation:a,id:r},textContent:o,textPosition:h,parent:{page:{pageNumber:l}}}=t;if(!o||0===o.length)return null;i=t={annotationType:g.FREETEXT,color:Array.from(s),fontSize:e,value:o.join("\n"),position:h,pageIndex:l-1,rect:n.slice(0),rotation:a,id:r,deleted:!1}}const n=super.deserialize(t,e,s);return n.#Ci=t.fontSize,n.#ui=V.makeHexColor(...t.color),n.#Wi=oi.#en(t.value),n.annotationElementId=t.id||null,n.#Ki=i,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};const e=oi._internalPadding*this.parentScale,s=this.getRect(e,e),i=It._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#ui),n={annotationType:g.FREETEXT,color:i,fontSize:this.#Ci,value:this.#sn(),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#in(n)?null:(n.id=this.annotationElementId,n)}#in(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this.#Ki;return this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some(((t,e)=>t!==i[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:s}=e;s.fontSize=`calc(${this.#Ci}px * var(--scale-factor))`,s.color=this.#ui,e.replaceChildren();for(const t of this.#Wi.split("\n")){const s=document.createElement("div");s.append(t?document.createTextNode(t):document.createElement("br")),e.append(s)}const i=oi._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#Wi}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class hi{#nn;#an=[];#rn=[];constructor(t,e=0,s=0,i=!0){let n=1/0,a=-1/0,r=1/0,o=-1/0;const h=10**-4;for(const{x:s,y:i,width:l,height:c}of t){const t=Math.floor((s-e)/h)*h,d=Math.ceil((s+l+e)/h)*h,u=Math.floor((i-e)/h)*h,p=Math.ceil((i+c+e)/h)*h,g=[t,u,p,!0],m=[d,u,p,!1];this.#an.push(g,m),n=Math.min(n,t),a=Math.max(a,d),r=Math.min(r,u),o=Math.max(o,p)}const l=a-n+2*s,c=o-r+2*s,d=n-s,u=r-s,p=this.#an.at(i?-1:-2),g=[p[0],p[2]];for(const t of this.#an){const[e,s,i]=t;t[0]=(e-d)/l,t[1]=(s-u)/c,t[2]=(i-u)/c}this.#nn={x:d,y:u,width:l,height:c,lastPoint:g}}getOutlines(){this.#an.sort(((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#an)e[3]?(t.push(...this.#on(e)),this.#hn(e)):(this.#ln(e),t.push(...this.#on(e)));return this.#cn(t)}#cn(t){const e=[],s=new Set;for(const s of t){const[t,i,n]=s;e.push([t,i,s],[t,n,s])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,i=e.length;t<i;t+=2){const i=e[t][2],n=e[t+1][2];i.push(n),n.push(i),s.add(i),s.add(n)}const i=[];let n;for(;s.size>0;){const t=s.values().next().value;let[e,a,r,o,h]=t;s.delete(t);let l=e,c=a;for(n=[e,r],i.push(n);;){let t;if(s.has(o))t=o;else{if(!s.has(h))break;t=h}s.delete(t),[e,a,r,o,h]=t,l!==e&&(n.push(l,c,e,c===a?a:r),l=e),c=c===a?r:a}n.push(l,c)}return new ci(i,this.#nn)}#dn(t){const e=this.#rn;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}#hn([,t,e]){const s=this.#dn(t);this.#rn.splice(s,0,[t,e])}#ln([,t,e]){const s=this.#dn(t);for(let i=s;i<this.#rn.length;i++){const[s,n]=this.#rn[i];if(s!==t)break;if(s===t&&n===e)return void this.#rn.splice(i,1)}for(let i=s-1;i>=0;i--){const[s,n]=this.#rn[i];if(s!==t)break;if(s===t&&n===e)return void this.#rn.splice(i,1)}}#on(t){const[e,s,i]=t,n=[[e,s,i]],a=this.#dn(i);for(let t=0;t<a;t++){const[s,i]=this.#rn[t];for(let t=0,a=n.length;t<a;t++){const[,r,o]=n[t];if(!(i<=r||o<=s))if(r>=s)if(o>i)n[t][1]=i;else{if(1===a)return[];n.splice(t,1),t--,a--}else n[t][2]=s,o>i&&n.push([e,i,o])}}return n}}class li{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(t,e){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof ui}}class ci extends li{#nn;#un;constructor(t,e){super(),this.#un=t,this.#nn=e}toSVGPath(){const t=[];for(const e of this.#un){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 e of this.#un){const s=new Array(e.length);for(let n=0;n<e.length;n+=2)s[n]=t+e[n]*r,s[n+1]=i-e[n+1]*o;a.push(s)}return a}get box(){return this.#nn}}class di{#nn;#pn=[];#gn;#mn;#fn=[];#bn=new Float64Array(18);#vn;#yn;#An;#wn;#xn;#_n;#En=[];static#Cn=8;static#Sn=2;static#Tn=di.#Cn+di.#Sn;constructor({x:t,y:e},s,i,n,a,r=0){this.#nn=s,this.#_n=n*i,this.#mn=a,this.#bn.set([NaN,NaN,NaN,NaN,t,e],6),this.#gn=r,this.#wn=di.#Cn*i,this.#An=di.#Tn*i,this.#xn=i,this.#En.push(t,e)}get free(){return!0}isEmpty(){return isNaN(this.#bn[8])}#Mn(){const t=this.#bn.subarray(4,6),e=this.#bn.subarray(16,18),[s,i,n,a]=this.#nn;return[(this.#vn+(t[0]-e[0])/2-s)/n,(this.#yn+(t[1]-e[1])/2-i)/a,(this.#vn+(e[0]-t[0])/2-s)/n,(this.#yn+(e[1]-t[1])/2-i)/a]}add({x:t,y:e}){this.#vn=t,this.#yn=e;const[s,i,n,a]=this.#nn;let[r,o,h,l]=this.#bn.subarray(8,12);const c=t-h,d=e-l,u=Math.hypot(c,d);if(u<this.#An)return!1;const p=u-this.#wn,g=p/u,m=g*c,f=g*d;let b=r,v=o;r=h,o=l,h+=m,l+=f,this.#En?.push(t,e);const y=m/p,A=-f/p*this.#_n,w=y*this.#_n;return this.#bn.set(this.#bn.subarray(2,8),0),this.#bn.set([h+A,l+w],4),this.#bn.set(this.#bn.subarray(14,18),12),this.#bn.set([h-A,l-w],16),isNaN(this.#bn[6])?(0===this.#fn.length&&(this.#bn.set([r+A,o+w],2),this.#fn.push(NaN,NaN,NaN,NaN,(r+A-s)/n,(o+w-i)/a),this.#bn.set([r-A,o-w],14),this.#pn.push(NaN,NaN,NaN,NaN,(r-A-s)/n,(o-w-i)/a)),this.#bn.set([b,v,r,o,h,l],6),!this.isEmpty()):(this.#bn.set([b,v,r,o,h,l],6),Math.abs(Math.atan2(v-o,b-r)-Math.atan2(f,m))<Math.PI/2?([r,o,h,l]=this.#bn.subarray(2,6),this.#fn.push(NaN,NaN,NaN,NaN,((r+h)/2-s)/n,((o+l)/2-i)/a),[r,o,b,v]=this.#bn.subarray(14,18),this.#pn.push(NaN,NaN,NaN,NaN,((b+r)/2-s)/n,((v+o)/2-i)/a),!0):([b,v,r,o,h,l]=this.#bn.subarray(0,6),this.#fn.push(((b+5*r)/6-s)/n,((v+5*o)/6-i)/a,((5*r+h)/6-s)/n,((5*o+l)/6-i)/a,((r+h)/2-s)/n,((o+l)/2-i)/a),[h,l,r,o,b,v]=this.#bn.subarray(12,18),this.#pn.push(((b+5*r)/6-s)/n,((v+5*o)/6-i)/a,((5*r+h)/6-s)/n,((5*o+l)/6-i)/a,((r+h)/2-s)/n,((o+l)/2-i)/a),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#fn,e=this.#pn,s=this.#bn.subarray(4,6),i=this.#bn.subarray(16,18),[n,a,r,o]=this.#nn,[h,l,c,d]=this.#Mn();if(isNaN(this.#bn[6])&&!this.isEmpty())return`M${(this.#bn[2]-n)/r} ${(this.#bn[3]-a)/o} L${(this.#bn[4]-n)/r} ${(this.#bn[5]-a)/o} L${h} ${l} L${c} ${d} L${(this.#bn[16]-n)/r} ${(this.#bn[17]-a)/o} L${(this.#bn[14]-n)/r} ${(this.#bn[15]-a)/o} Z`;const u=[];u.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?u.push(`L${t[e+4]} ${t[e+5]}`):u.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);u.push(`L${(s[0]-n)/r} ${(s[1]-a)/o} L${h} ${l} L${c} ${d} L${(i[0]-n)/r} ${(i[1]-a)/o}`);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?u.push(`L${e[t+4]} ${e[t+5]}`):u.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return u.push(`L${e[4]} ${e[5]} Z`),u.join(" ")}getOutlines(){const t=this.#fn,e=this.#pn,s=this.#bn,i=s.subarray(4,6),n=s.subarray(16,18),[a,r,o,h]=this.#nn,l=new Float64Array((this.#En?.length??0)+2);for(let t=0,e=l.length-2;t<e;t+=2)l[t]=(this.#En[t]-a)/o,l[t+1]=(this.#En[t+1]-r)/h;l[l.length-2]=(this.#vn-a)/o,l[l.length-1]=(this.#yn-r)/h;const[c,d,u,p]=this.#Mn();if(isNaN(s[6])&&!this.isEmpty()){const t=new Float64Array(36);return t.set([NaN,NaN,NaN,NaN,(s[2]-a)/o,(s[3]-r)/h,NaN,NaN,NaN,NaN,(s[4]-a)/o,(s[5]-r)/h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,u,p,NaN,NaN,NaN,NaN,(s[16]-a)/o,(s[17]-r)/h,NaN,NaN,NaN,NaN,(s[14]-a)/o,(s[15]-r)/h],0),new ui(t,l,this.#nn,this.#xn,this.#gn,this.#mn)}const g=new Float64Array(this.#fn.length+24+this.#pn.length);let m=t.length;for(let e=0;e<m;e+=2)isNaN(t[e])?g[e]=g[e+1]=NaN:(g[e]=t[e],g[e+1]=t[e+1]);g.set([NaN,NaN,NaN,NaN,(i[0]-a)/o,(i[1]-r)/h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,u,p,NaN,NaN,NaN,NaN,(n[0]-a)/o,(n[1]-r)/h],m),m+=24;for(let t=e.length-6;t>=6;t-=6)for(let s=0;s<6;s+=2)isNaN(e[t+s])?(g[m]=g[m+1]=NaN,m+=2):(g[m]=e[t+s],g[m+1]=e[t+s+1],m+=2);return g.set([NaN,NaN,NaN,NaN,e[4],e[5]],m),new ui(g,l,this.#nn,this.#xn,this.#gn,this.#mn)}}class ui extends li{#nn;#kn=null;#gn;#mn;#En;#xn;#Pn;constructor(t,e,s,i,n,a){super(),this.#Pn=t,this.#En=e,this.#nn=s,this.#xn=i,this.#gn=n,this.#mn=a,this.#Rn(a);const{x:r,y:o,width:h,height:l}=this.#kn;for(let e=0,s=t.length;e<s;e+=2)t[e]=(t[e]-r)/h,t[e+1]=(t[e+1]-o)/l;for(let t=0,s=e.length;t<s;t+=2)e[t]=(e[t]-r)/h,e[t+1]=(e[t+1]-o)/l}toSVGPath(){const t=[`M${this.#Pn[4]} ${this.#Pn[5]}`];for(let e=6,s=this.#Pn.length;e<s;e+=6)isNaN(this.#Pn[e])?t.push(`L${this.#Pn[e+4]} ${this.#Pn[e+5]}`):t.push(`C${this.#Pn[e]} ${this.#Pn[e+1]} ${this.#Pn[e+2]} ${this.#Pn[e+3]} ${this.#Pn[e+4]} ${this.#Pn[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const a=s-t,r=i-e;let o,h;switch(n){case 0:o=this.#Ln(this.#Pn,t,i,a,-r),h=this.#Ln(this.#En,t,i,a,-r);break;case 90:o=this.#In(this.#Pn,t,e,a,r),h=this.#In(this.#En,t,e,a,r);break;case 180:o=this.#Ln(this.#Pn,s,e,-a,r),h=this.#Ln(this.#En,s,e,-a,r);break;case 270:o=this.#In(this.#Pn,s,i,-a,-r),h=this.#In(this.#En,s,i,-a,-r)}return{outline:Array.from(o),points:[Array.from(h)]}}#Ln(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}#In(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}#Rn(t){const e=this.#Pn;let s=e[4],i=e[5],n=s,a=i,r=s,o=i,h=s,l=i;const c=t?Math.max:Math.min;for(let t=6,d=e.length;t<d;t+=6){if(isNaN(e[t]))n=Math.min(n,e[t+4]),a=Math.min(a,e[t+5]),r=Math.max(r,e[t+4]),o=Math.max(o,e[t+5]),l<e[t+5]?(h=e[t+4],l=e[t+5]):l===e[t+5]&&(h=c(h,e[t+4]));else{const d=V.bezierBoundingBox(s,i,...e.slice(t,t+6));n=Math.min(n,d[0]),a=Math.min(a,d[1]),r=Math.max(r,d[2]),o=Math.max(o,d[3]),l<d[3]?(h=d[2],l=d[3]):l===d[3]&&(h=c(h,d[2]))}s=e[t+4],i=e[t+5]}const d=n-this.#gn,u=a-this.#gn,p=r-n+2*this.#gn,g=o-a+2*this.#gn;this.#kn={x:d,y:u,width:p,height:g,lastPoint:[h,l]}}get box(){return this.#kn}getNewOutline(t,e){const{x:s,y:i,width:n,height:a}=this.#kn,[r,o,h,l]=this.#nn,c=n*h,d=a*l,u=s*h+r,p=i*l+o,g=new di({x:this.#En[0]*c+u,y:this.#En[1]*d+p},this.#nn,this.#xn,t,this.#mn,e??this.#gn);for(let t=2;t<this.#En.length;t+=2)g.add({x:this.#En[t]*c+u,y:this.#En[t+1]*d+p});return g.getOutlines()}}class pi{#ni=this.#ai.bind(this);#Dn=this.#r.bind(this);#Fn=null;#On=null;#Nn;#Bn=null;#Hn=!1;#zn=!1;#n=null;#jn;#u=null;#$n;static get _keyboardManager(){return P(this,"_keyboardManager",new kt([[["Escape","mac+Escape"],pi.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],pi.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],pi.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],pi.prototype._moveToPrevious],[["Home","mac+Home"],pi.prototype._moveToBeginning],[["End","mac+End"],pi.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#zn=!1,this.#$n=m.HIGHLIGHT_COLOR,this.#n=t):(this.#zn=!0,this.#$n=m.HIGHLIGHT_DEFAULT_COLOR),this.#u=t?._uiManager||e,this.#jn=this.#u._eventBus,this.#Nn=t?.color||this.#u?.highlightColors.values().next().value||"#FFFF98"}renderButton(){const t=this.#Fn=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0),t.addEventListener("click",this.#Un.bind(this)),t.addEventListener("keydown",this.#ni);const e=this.#On=document.createElement("span");return e.className="swatch",e.setAttribute("aria-hidden",!0),e.style.backgroundColor=this.#Nn,t.append(e),t}renderMainDropdown(){const t=this.#Bn=this.#Vn();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#Vn(){const t=document.createElement("div");t.addEventListener("contextmenu",gt),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[e,s]of this.#u.highlightColors){const i=document.createElement("button");i.tabIndex="0",i.role="option",i.setAttribute("data-color",s),i.title=e,i.setAttribute("data-l10n-id",`pdfjs-editor-colorpicker-${e}`);const n=document.createElement("span");i.append(n),n.className="swatch",n.style.backgroundColor=s,i.setAttribute("aria-selected",s===this.#Nn),i.addEventListener("click",this.#Gn.bind(this,s)),t.append(i)}return t.addEventListener("keydown",this.#ni),t}#Gn(t,e){e.stopPropagation(),this.#jn.dispatch("switchannotationeditorparams",{source:this,type:this.#$n,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#Fn)return void this.#Un(t);const e=t.target.getAttribute("data-color");e&&this.#Gn(e,t)}_moveToNext(t){this.#Wn?t.target!==this.#Fn?t.target.nextSibling?.focus():this.#Bn.firstChild?.focus():this.#Un(t)}_moveToPrevious(t){t.target!==this.#Bn?.firstChild&&t.target!==this.#Fn?(this.#Wn||this.#Un(t),t.target.previousSibling?.focus()):this.#Wn&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Wn?this.#Bn.firstChild?.focus():this.#Un(t)}_moveToEnd(t){this.#Wn?this.#Bn.lastChild?.focus():this.#Un(t)}#ai(t){pi._keyboardManager.exec(this,t)}#Un(t){if(this.#Wn)return void this.hideDropdown();if(this.#Hn=0===t.detail,window.addEventListener("pointerdown",this.#Dn),this.#Bn)return void this.#Bn.classList.remove("hidden");const e=this.#Bn=this.#Vn();this.#Fn.append(e)}#r(t){this.#Bn?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#Bn?.classList.add("hidden"),window.removeEventListener("pointerdown",this.#Dn)}get#Wn(){return this.#Bn&&!this.#Bn.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#zn||(this.#Wn?(this.hideDropdown(),this.#Fn.focus({preventScroll:!0,focusVisible:this.#Hn})):this.#n?.unselect())}updateColor(t){if(this.#On&&(this.#On.style.backgroundColor=t),!this.#Bn)return;const e=this.#u.highlightColors.values();for(const s of this.#Bn.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#Fn?.remove(),this.#Fn=null,this.#On=null,this.#Bn?.remove(),this.#Bn=null}}class gi extends It{#qn=null;#Kn=0;#Xn;#Yn=null;#i=null;#Qn=null;#Jn=null;#Zn=0;#ta=null;#ea=null;#f=null;#sa=!1;#at=this.#ia.bind(this);#na=null;#aa;#ra=null;#oa="";#_n;#ha="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _l10nPromise;static _type="highlight";static _editorType=g.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=gi.prototype;return P(this,"_keyboardManager",new kt([[["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||gi._defaultColor,this.#_n=t.thickness||gi._defaultThickness,this.#aa=t.opacity||gi._defaultOpacity,this.#Xn=t.boxes||null,this.#ha=t.methodOfCreation||"",this.#oa=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#sa=!0,this.#la(t),this.#ca()):(this.#qn=t.anchorNode,this.#Kn=t.anchorOffset,this.#Jn=t.focusNode,this.#Zn=t.focusOffset,this.#da(),this.#ca(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#sa?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#_n,methodOfCreation:this.#ha}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#da(){const t=new hi(this.#Xn,.001);this.#ea=t.getOutlines(),({x:this.x,y:this.y,width:this.width,height:this.height}=this.#ea.box);const e=new hi(this.#Xn,.0025,.001,"ltr"===this._uiManager.direction);this.#Qn=e.getOutlines();const{lastPoint:s}=this.#Qn.box;this.#na=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#la({highlightOutlines:t,highlightId:e,clipPathId:s}){if(this.#ea=t,this.#Qn=t.getNewOutline(this.#_n/2+1.5,.0025),e>=0)this.#f=e,this.#Yn=s,this.parent.drawLayer.finalizeLine(e,t),this.#ra=this.parent.drawLayer.highlightOutline(this.#Qn);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#f,t),this.parent.drawLayer.updateBox(this.#f,gi.#ua(this.#ea.box,(e-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#ra,this.#Qn),this.parent.drawLayer.updateBox(this.#ra,gi.#ua(this.#Qn.box,e))}const{x:i,y:n,width:a,height:r}=t.box;switch(this.rotation){case 0:this.x=i,this.y=n,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-i,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-i,this.y=1-n,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=i,this.width=a*e/t,this.height=r*t/e;break}}const{lastPoint:o}=this.#Qn.box;this.#na=[(o[0]-i)/a,(o[1]-n)/r]}static initialize(t,e){It.initialize(t,e),gi._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case m.HIGHLIGHT_DEFAULT_COLOR:gi._defaultColor=e;break;case m.HIGHLIGHT_THICKNESS:gi._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#na}updateParams(t,e){switch(t){case m.HIGHLIGHT_COLOR:this.#Yi(e);break;case m.HIGHLIGHT_THICKNESS:this.#pa(e)}}static get defaultPropertiesToUpdate(){return[[m.HIGHLIGHT_DEFAULT_COLOR,gi._defaultColor],[m.HIGHLIGHT_THICKNESS,gi._defaultThickness]]}get propertiesToUpdate(){return[[m.HIGHLIGHT_COLOR,this.color||gi._defaultColor],[m.HIGHLIGHT_THICKNESS,this.#_n||gi._defaultThickness],[m.HIGHLIGHT_FREE,this.#sa]]}#Yi(t){const e=t=>{this.color=t,this.parent?.drawLayer.changeColor(this.#f,t),this.#i?.updateColor(t)},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:m.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#pa(t){const e=this.#_n,s=t=>{this.#_n=t,this.#ga(t)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.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.#i=new pi({editor:this}),t.addColorPicker(this.#i)),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.#ma())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#ma())}onceAdded(){this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#fa(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#ca(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#fa():t&&(this.#ca(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#ga(t){if(!this.#sa)return;this.#la({highlightOutlines:this.#ea.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#fa(){null!==this.#f&&this.parent&&(this.parent.drawLayer.remove(this.#f),this.#f=null,this.parent.drawLayer.remove(this.#ra),this.#ra=null)}#ca(t=this.parent){null===this.#f&&(({id:this.#f,clipPathId:this.#Yn}=t.drawLayer.highlight(this.#ea,this.color,this.#aa)),this.#ra=t.drawLayer.highlightOutline(this.#Qn),this.#ta&&(this.#ta.style.clipPath=this.#Yn))}static#ua({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.#sa?(t=(t-this.rotation+360)%360,s=gi.#ua(this.#ea.box,t)):s=gi.#ua(this,t),e.rotate(this.#f,t),e.rotate(this.#ra,t),e.updateBox(this.#f,s),e.updateBox(this.#ra,gi.#ua(this.#Qn.box,t))}render(){if(this.div)return this.div;const t=super.render();this.#oa&&(t.setAttribute("aria-label",this.#oa),t.setAttribute("role","mark")),this.#sa?t.classList.add("free"):this.div.addEventListener("keydown",this.#at);const e=this.#ta=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#Yn;const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),Ct(this,this.#ta,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.parent.drawLayer.addClass(this.#ra,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#ra,"hovered")}#ia(t){gi._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#ba(!0);break;case 1:case 3:this.#ba(!1)}}#ba(t){if(!this.#qn)return;const e=window.getSelection();t?e.setPosition(this.#qn,this.#Kn):e.setPosition(this.#Jn,this.#Zn)}select(){super.select(),this.#ra&&(this.parent?.drawLayer.removeClass(this.#ra,"hovered"),this.parent?.drawLayer.addClass(this.#ra,"selected"))}unselect(){super.unselect(),this.#ra&&(this.parent?.drawLayer.removeClass(this.#ra,"selected"),this.#sa||this.#ba(!1))}get _mustFixPosition(){return!this.#sa}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(this.#f,t),this.parent.drawLayer.show(this.#ra,t))}#ma(){return this.#sa?this.rotation:0}#va(){if(this.#sa)return null;const[t,e]=this.pageDimensions,s=this.#Xn,i=new Array(8*s.length);let n=0;for(const{x:a,y:r,width:o,height:h}of s){const s=a*t,l=(1-r-h)*e;i[n]=i[n+4]=s,i[n+1]=i[n+3]=l,i[n+2]=i[n+6]=s+o*t,i[n+5]=i[n+7]=l+h*e,n+=8}return i}#ya(t){return this.#ea.serialize(t,this.#ma())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:a,y:r,width:o,height:h}=s.getBoundingClientRect(),l=e=>{this.#Aa(t,e)},c={capture:!0,passive:!1},d=t=>{t.preventDefault(),t.stopPropagation()},u=e=>{s.removeEventListener("pointermove",l),window.removeEventListener("blur",u),window.removeEventListener("pointerup",u),window.removeEventListener("pointerdown",d,c),window.removeEventListener("contextmenu",gt),this.#wa(t,e)};window.addEventListener("blur",u),window.addEventListener("pointerup",u),window.addEventListener("pointerdown",d,c),window.addEventListener("contextmenu",gt),s.addEventListener("pointermove",l),this._freeHighlight=new di({x:i,y:n},[a,r,o,h],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0))}static#Aa(t,e){this._freeHighlight.add(e)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#wa(t,e){this._freeHighlight.isEmpty()?t.drawLayer.removeFreeHighlight(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 deserialize(t,e,s){const i=super.deserialize(t,e,s),{rect:[n,a,r,o],color:h,quadPoints:l}=t;i.color=V.makeHexColor(...h),i.#aa=t.opacity;const[c,d]=i.pageDimensions;i.width=(r-n)/c,i.height=(o-a)/d;const u=i.#Xn=[];for(let t=0;t<l.length;t+=8)u.push({x:(l[4]-r)/c,y:(o-(1-l[t+5]))/d,width:(l[t+2]-l[t])/c,height:(l[t+5]-l[t+1])/d});return i.#da(),i}serialize(t=!1){if(this.isEmpty()||t)return null;const e=this.getRect(0,0),s=It._colorManager.convert(this.color);return{annotationType:g.HIGHLIGHT,color:s,opacity:this.#aa,thickness:this.#_n,quadPoints:this.#va(),outlines:this.#ya(e),pageIndex:this.pageIndex,rect:e,rotation:this.#ma(),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}}class mi extends It{#xa=0;#_a=0;#Ea=this.canvasPointermove.bind(this);#Ca=this.canvasPointerleave.bind(this);#Sa=this.canvasPointerup.bind(this);#Ta=this.canvasPointerdown.bind(this);#Ma=null;#ka=new Path2D;#Pa=!1;#Ra=!1;#La=!1;#Ia=null;#Da=0;#Fa=0;#Oa=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=g.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){It.initialize(t,e)}static updateDefaultParams(t,e){switch(t){case m.INK_THICKNESS:mi._defaultThickness=e;break;case m.INK_COLOR:mi._defaultColor=e;break;case m.INK_OPACITY:mi._defaultOpacity=e/100}}updateParams(t,e){switch(t){case m.INK_THICKNESS:this.#pa(e);break;case m.INK_COLOR:this.#Yi(e);break;case m.INK_OPACITY:this.#Na(e)}}static get defaultPropertiesToUpdate(){return[[m.INK_THICKNESS,mi._defaultThickness],[m.INK_COLOR,mi._defaultColor||It._defaultLineColor],[m.INK_OPACITY,Math.round(100*mi._defaultOpacity)]]}get propertiesToUpdate(){return[[m.INK_THICKNESS,this.thickness||mi._defaultThickness],[m.INK_COLOR,this.color||mi._defaultColor||It._defaultLineColor],[m.INK_OPACITY,Math.round(100*(this.opacity??mi._defaultOpacity))]]}#pa(t){const e=t=>{this.thickness=t,this.#Ba()},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:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#Yi(t){const e=t=>{this.color=t,this.#Ha()},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:m.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#Na(t){const e=t=>{this.opacity=t,this.#Ha()};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:m.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.canvas||(this.#za(),this.#ja()),this.isAttachedToDOM||(this.parent.add(this),this.#$a()),this.#Ba()))}remove(){null!==this.canvas&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#Ma&&(clearTimeout(this.#Ma),this.#Ma=null),this.#Ia.disconnect(),this.#Ia=null,super.remove())}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&null===t&&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.#Pa||null===this.canvas||(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",this.#Ta))}disableEditMode(){this.isInEditMode()&&null!==this.canvas&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",this.#Ta))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return 0===this.paths.length||1===this.paths.length&&0===this.paths[0].length}#Ua(){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]}}#Va(){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}${function(t){return Math.round(Math.min(255,Math.max(1,255*t))).toString(16).padStart(2,"0")}(s)}`}#Ga(t,e){this.canvas.addEventListener("contextmenu",gt),this.canvas.addEventListener("pointerleave",this.#Ca),this.canvas.addEventListener("pointermove",this.#Ea),this.canvas.addEventListener("pointerup",this.#Sa),this.canvas.removeEventListener("pointerdown",this.#Ta),this.isEditing=!0,this.#La||(this.#La=!0,this.#$a(),this.thickness||=mi._defaultThickness,this.color||=mi._defaultColor||It._defaultLineColor,this.opacity??=mi._defaultOpacity),this.currentPath.push([t,e]),this.#Ra=!1,this.#Va(),this.#Oa=()=>{this.#Wa(),this.#Oa&&window.requestAnimationFrame(this.#Oa)},window.requestAnimationFrame(this.#Oa)}#qa(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.#ka;if(n.push([t,e]),this.#Ra=!0,n.length<=2)return a.moveTo(...n[0]),void a.lineTo(t,e);3===n.length&&(this.#ka=a=new Path2D,a.moveTo(...n[0])),this.#Ka(a,...n.at(-3),...n.at(-2),t,e)}#Xa(){if(0===this.currentPath.length)return;const t=this.currentPath.at(-1);this.#ka.lineTo(...t)}#Ya(t,e){let s;if(this.#Oa=null,t=Math.min(Math.max(t,0),this.canvas.width),e=Math.min(Math.max(e,0),this.canvas.height),this.#qa(t,e),this.#Xa(),1!==this.currentPath.length)s=this.#Qa();else{const i=[t,e];s=[[i,i.slice(),i.slice(),i]]}const i=this.#ka,n=this.currentPath;this.currentPath=[],this.#ka=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(n),this.paths.push(s),this.bezierPath2D.push(i),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),0===this.paths.length?this.remove():(this.canvas||(this.#za(),this.#ja()),this.#Ba())},mustExec:!0})}#Wa(){if(!this.#Ra)return;this.#Ra=!1;Math.ceil(this.thickness*this.parentScale);const t=this.currentPath.slice(-3),e=t.map((t=>t[0])),s=t.map((t=>t[1])),{ctx:i}=(Math.min(...e),Math.max(...e),Math.min(...s),Math.max(...s),this);i.save(),i.clearRect(0,0,this.canvas.width,this.canvas.height);for(const t of this.bezierPath2D)i.stroke(t);i.stroke(this.#ka),i.restore()}#Ka(t,e,s,i,n,a,r){const o=(e+i)/2,h=(s+n)/2,l=(i+a)/2,c=(n+r)/2;t.bezierCurveTo(o+2*(i-o)/3,h+2*(n-h)/3,l+2*(i-l)/3,c+2*(n-c)/3,l,c)}#Qa(){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[a,r]=t[s],[o,h]=t[s+1],l=(a+o)/2,c=(r+h)/2,d=[i+2*(a-i)/3,n+2*(r-n)/3],u=[l+2*(a-l)/3,c+2*(r-c)/3];e.push([[i,n],d,u,[l,c]]),[i,n]=[l,c]}const[a,r]=t[s],[o,h]=t[s+1],l=[i+2*(a-i)/3,n+2*(r-n)/3],c=[o+2*(a-o)/3,h+2*(r-h)/3];return e.push([[i,n],l,c,[o,h]]),e}#Ha(){if(this.isEmpty())return void this.#Ja();this.#Va();const{canvas:t,ctx:e}=this;e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height),this.#Ja();for(const t of this.bezierPath2D)e.stroke(t)}commit(){this.#Pa||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),this.#Pa=!0,this.div.classList.add("disabled"),this.#Ba(!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),this.enableEditMode())}canvasPointerdown(t){0===t.button&&this.isInEditMode()&&!this.#Pa&&(this.setInForeground(),t.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),this.#Ga(t.offsetX,t.offsetY))}canvasPointermove(t){t.preventDefault(),this.#qa(t.offsetX,t.offsetY)}canvasPointerup(t){t.preventDefault(),this.#Za(t)}canvasPointerleave(t){this.#Za(t)}#Za(t){this.canvas.removeEventListener("pointerleave",this.#Ca),this.canvas.removeEventListener("pointermove",this.#Ea),this.canvas.removeEventListener("pointerup",this.#Sa),this.canvas.addEventListener("pointerdown",this.#Ta),this.#Ma&&clearTimeout(this.#Ma),this.#Ma=setTimeout((()=>{this.#Ma=null,this.canvas.removeEventListener("contextmenu",gt)}),10),this.#Ya(t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#za(){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")}#ja(){this.#Ia=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.setDimensions(e.width,e.height)})),this.#Ia.observe(this.div)}get isResizable(){return!this.isEmpty()&&this.#Pa}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.#Ua();if(this.setAt(s,i,0,0),this.setDims(n,a),this.#za(),this.width){const[s,i]=this.parentDimensions;this.setAspectRatio(this.width*s,this.height*i),this.setAt(t*s,e*i,this.width*s,this.height*i),this.#La=!0,this.#$a(),this.setDims(this.width*s,this.height*i),this.#Ha(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#ja(),this.div}#$a(){if(!this.#La)return;const[t,e]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*e),this.#Ja()}setDimensions(t,e){const s=Math.round(t),i=Math.round(e);if(this.#Da===s&&this.#Fa===i)return;this.#Da=s,this.#Fa=i,this.canvas.style.visibility="hidden";const[n,a]=this.parentDimensions;this.width=t/n,this.height=e/a,this.fixAndSetPosition(),this.#Pa&&this.#tr(t,e),this.#$a(),this.#Ha(),this.canvas.style.visibility="visible",this.fixDims()}#tr(t,e){const s=this.#er(),i=(t-s)/this.#_a,n=(e-s)/this.#xa;this.scaleFactor=Math.min(i,n)}#Ja(){const t=this.#er()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static#sr(t){const e=new Path2D;for(let s=0,i=t.length;s<i;s++){const[i,n,a,r]=t[s];0===s&&e.moveTo(...i),e.bezierCurveTo(n[0],n[1],a[0],a[1],r[0],r[1])}return e}static#ir(t,e,s){const[i,n,a,r]=e;switch(s){case 0:for(let e=0,s=t.length;e<s;e+=2)t[e]+=i,t[e+1]=r-t[e+1];break;case 90:for(let e=0,s=t.length;e<s;e+=2){const s=t[e];t[e]=t[e+1]+i,t[e+1]=s+n}break;case 180:for(let e=0,s=t.length;e<s;e+=2)t[e]=a-t[e],t[e+1]+=n;break;case 270:for(let e=0,s=t.length;e<s;e+=2){const s=t[e];t[e]=a-t[e+1],t[e+1]=r-s}break;default:throw new Error("Invalid rotation")}return t}static#nr(t,e,s){const[i,n,a,r]=e;switch(s){case 0:for(let e=0,s=t.length;e<s;e+=2)t[e]-=i,t[e+1]=r-t[e+1];break;case 90:for(let e=0,s=t.length;e<s;e+=2){const s=t[e];t[e]=t[e+1]-n,t[e+1]=s-i}break;case 180:for(let e=0,s=t.length;e<s;e+=2)t[e]=a-t[e],t[e+1]-=n;break;case 270:for(let e=0,s=t.length;e<s;e+=2){const s=t[e];t[e]=r-t[e+1],t[e+1]=a-s}break;default:throw new Error("Invalid rotation")}return t}#ar(t,e,s,i){const n=[],a=this.thickness/2,r=t*e+a,o=t*s+a;for(const e of this.paths){const s=[],a=[];for(let i=0,n=e.length;i<n;i++){const[h,l,c,d]=e[i];if(h[0]===d[0]&&h[1]===d[1]&&1===n){const e=t*h[0]+r,i=t*h[1]+o;s.push(e,i),a.push(e,i);break}const u=t*h[0]+r,p=t*h[1]+o,g=t*l[0]+r,m=t*l[1]+o,f=t*c[0]+r,b=t*c[1]+o,v=t*d[0]+r,y=t*d[1]+o;0===i&&(s.push(u,p),a.push(u,p)),s.push(g,m,f,b,v,y),a.push(g,m),i===n-1&&a.push(v,y)}n.push({bezier:mi.#ir(s,i,this.rotation),points:mi.#ir(a,i,this.rotation)})}return n}#rr(){let t=1/0,e=-1/0,s=1/0,i=-1/0;for(const n of this.paths)for(const[a,r,o,h]of n){const n=V.bezierBoundingBox(...a,...r,...o,...h);t=Math.min(t,n[0]),s=Math.min(s,n[1]),e=Math.max(e,n[2]),i=Math.max(i,n[3])}return[t,s,e,i]}#er(){return this.#Pa?Math.ceil(this.thickness*this.parentScale):0}#Ba(t=!1){if(this.isEmpty())return;if(!this.#Pa)return void this.#Ha();const e=this.#rr(),s=this.#er();this.#_a=Math.max(It.MIN_SIZE,e[2]-e[0]),this.#xa=Math.max(It.MIN_SIZE,e[3]-e[1]);const i=Math.ceil(s+this.#_a*this.scaleFactor),n=Math.ceil(s+this.#xa*this.scaleFactor),[a,r]=this.parentDimensions;this.width=i/a,this.height=n/r,this.setAspectRatio(i,n);const o=this.translationX,h=this.translationY;this.translationX=-e[0],this.translationY=-e[1],this.#$a(),this.#Ha(),this.#Da=i,this.#Fa=n,this.setDims(i,n);const l=t?s/this.scaleFactor/2:0;this.translate(o-this.translationX-l,h-this.translationY-l)}static deserialize(t,e,s){if(t instanceof Js)return null;const i=super.deserialize(t,e,s);i.thickness=t.thickness,i.color=V.makeHexColor(...t.color),i.opacity=t.opacity;const[n,a]=i.pageDimensions,r=i.width*n,o=i.height*a,h=i.parentScale,l=t.thickness/2;i.#Pa=!0,i.#Da=Math.round(r),i.#Fa=Math.round(o);const{paths:c,rect:d,rotation:u}=t;for(let{bezier:t}of c){t=mi.#nr(t,d,u);const e=[];i.paths.push(e);let s=h*(t[0]-l),n=h*(t[1]-l);for(let i=2,a=t.length;i<a;i+=6){const a=h*(t[i]-l),r=h*(t[i+1]-l),o=h*(t[i+2]-l),c=h*(t[i+3]-l),d=h*(t[i+4]-l),u=h*(t[i+5]-l);e.push([[s,n],[a,r],[o,c],[d,u]]),s=d,n=u}const a=this.#sr(e);i.bezierPath2D.push(a)}const p=i.#rr();return i.#_a=Math.max(It.MIN_SIZE,p[2]-p[0]),i.#xa=Math.max(It.MIN_SIZE,p[3]-p[1]),i.#tr(r,o),i}serialize(){if(this.isEmpty())return null;const t=this.getRect(0,0),e=It._colorManager.convert(this.ctx.strokeStyle);return{annotationType:g.INK,color:e,thickness:this.thickness,opacity:this.opacity,paths:this.#ar(this.scaleFactor/this.parentScale,this.translationX,this.translationY,t),pageIndex:this.pageIndex,rect:t,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}}class fi extends It{#or=null;#hr=null;#lr=null;#cr=null;#dr=null;#ur="";#pr=null;#Ia=null;#gr=null;#mr=!1;#fr=!1;static _type="stamp";static _editorType=g.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#cr=t.bitmapUrl,this.#dr=t.bitmapFile}static initialize(t,e){It.initialize(t,e)}static get supportedTypes(){return P(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return P(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(g.STAMP,{bitmapFile:t.getAsFile()})}#br(t,e=!1){t?(this.#or=t.bitmap,e||(this.#hr=t.id,this.#mr=t.isSvg),t.file&&(this.#ur=t.file.name),this.#za()):this.remove()}#vr(){this.#lr=null,this._uiManager.enableWaiting(!1),this.#pr&&this.div.focus()}#yr(){if(this.#hr)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#hr).then((t=>this.#br(t,!0))).finally((()=>this.#vr()));if(this.#cr){const t=this.#cr;return this.#cr=null,this._uiManager.enableWaiting(!0),void(this.#lr=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#br(t))).finally((()=>this.#vr())))}if(this.#dr){const t=this.#dr;return this.#dr=null,this._uiManager.enableWaiting(!0),void(this.#lr=this._uiManager.imageManager.getFromFile(t).then((t=>this.#br(t))).finally((()=>this.#vr())))}const t=document.createElement("input");t.type="file",t.accept=fi.supportedTypesStr,this.#lr=new Promise((e=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this.#br(e)}else this.remove();e()})),t.addEventListener("cancel",(()=>{this.remove(),e()}))})).finally((()=>this.#vr())),t.click()}remove(){this.#hr&&(this.#or=null,this._uiManager.imageManager.deleteId(this.#hr),this.#pr?.remove(),this.#pr=null,this.#Ia?.disconnect(),this.#Ia=null,this.#gr&&(clearTimeout(this.#gr),this.#gr=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#hr&&null===this.#pr&&this.#yr(),this.isAttachedToDOM||this.parent.add(this))):this.#hr&&this.#yr()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#lr||this.#or||this.#cr||this.#dr||this.#hr)}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.addAltTextButton(),this.#or?this.#za():this.#yr(),this.width){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i)}return this.div}#za(){const{div:t}=this;let{width:e,height:s}=this.#or;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 t=Math.min(a*i/e,a*n/s);e*=t,s*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/i,s*o/n),this._uiManager.enableWaiting(!1);const h=this.#pr=document.createElement("canvas");t.append(h),t.hidden=!1,this.#Ar(e,s),this.#ja(),this.#fr||(this.parent.addUndoableEditor(this),this.#fr=!0),this._reportTelemetry({action:"inserted_image"}),this.#ur&&h.setAttribute("aria-label",this.#ur)}#wr(t,e){const[s,i]=this.parentDimensions;this.width=t/s,this.height=e/i,this.setDims(t,e),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,null!==this.#gr&&clearTimeout(this.#gr),this.#gr=setTimeout((()=>{this.#gr=null,this.#Ar(t,e)}),200)}#xr(t,e){const{width:s,height:i}=this.#or;let n=s,a=i,r=this.#or;for(;n>2*t||a>2*e;){const s=n,i=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 o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,s,i,0,0,n,a),r=o.transferToImageBitmap()}return r}#Ar(t,e){t=Math.ceil(t),e=Math.ceil(e);const s=this.#pr;if(!s||s.width===t&&s.height===e)return;s.width=t,s.height=e;const i=this.#mr?this.#or:this.#xr(t,e);if(this._uiManager.hasMLManager&&!this.hasAltText()){const s=new OffscreenCanvas(t,e).getContext("2d");s.drawImage(i,0,0,i.width,i.height,0,0,t,e),this._uiManager.mlGuess({service:"image-to-text",request:{data:s.getImageData(0,0,t,e).data,width:t,height:e,channels:4}}).then((t=>{const e=t?.output||"";this.parent&&e&&!this.hasAltText()&&(this.altTextData={altText:e,decorative:!1})}))}const n=s.getContext("2d");n.filter=this._uiManager.hcmFilter,n.drawImage(i,0,0,i.width,i.height,0,0,t,e)}getImageForAltText(){return this.#pr}#_r(t){if(t){if(this.#mr){const t=this._uiManager.imageManager.getSvgUrl(this.#hr);if(t)return t}const t=document.createElement("canvas");return({width:t.width,height:t.height}=this.#or),t.getContext("2d").drawImage(this.#or,0,0),t.toDataURL()}if(this.#mr){const[t,e]=this.pageDimensions,s=Math.round(this.width*t*et.PDF_TO_CSS_UNITS),i=Math.round(this.height*e*et.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(s,i);return n.getContext("2d").drawImage(this.#or,0,0,this.#or.width,this.#or.height,0,0,s,i),n.transferToImageBitmap()}return structuredClone(this.#or)}#ja(){this.#Ia=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.#wr(e.width,e.height)})),this.#Ia.observe(this.div)}static deserialize(t,e,s){if(t instanceof ii)return null;const i=super.deserialize(t,e,s),{rect:n,bitmapUrl:a,bitmapId:r,isSvg:o,accessibilityData:h}=t;r&&s.imageManager.isValidId(r)?i.#hr=r:i.#cr=a,i.#mr=o;const[l,c]=i.pageDimensions;return i.width=(n[2]-n[0])/l,i.height=(n[3]-n[1])/c,h&&(i.altTextData=h),i}serialize(t=!1,e=null){if(this.isEmpty())return null;const s={annotationType:g.STAMP,bitmapId:this.#hr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#mr,structTreeParentId:this._structTreeParentId};if(t)return s.bitmapUrl=this.#_r(!0),s.accessibilityData=this.altTextData,s;const{decorative:i,altText:n}=this.altTextData;if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),null===e)return s;e.stamps||=new Map;const a=this.#mr?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(e.stamps.has(this.#hr)){if(this.#mr){const t=e.stamps.get(this.#hr);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#_r(!1))}}else e.stamps.set(this.#hr,{area:a,serialized:s}),s.bitmap=this.#_r(!1);return s}}class bi{#Oi;#Er=!1;#Cr=null;#Sr=null;#Tr=null;#Mr=null;#kr=null;#Pr=new Map;#Rr=!1;#Lr=!1;#Ir=!1;#Dr=null;#u;static _initialized=!1;static#F=new Map([oi,mi,fi,gi].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:s,accessibilityManager:i,annotationLayer:n,drawLayer:a,textLayer:r,viewport:o,l10n:h}){const l=[...bi.#F.values()];if(!bi._initialized){bi._initialized=!0;for(const e of l)e.initialize(h,t)}t.registerEditorTypes(l),this.#u=t,this.pageIndex=e,this.div=s,this.#Oi=i,this.#Cr=n,this.viewport=o,this.#Dr=r,this.drawLayer=a,this.#u.addLayer(this)}get isEmpty(){return 0===this.#Pr.size}get isInvisible(){return this.isEmpty&&this.#u.getMode()===g.NONE}updateToolbar(t){this.#u.updateToolbar(t)}updateMode(t=this.#u.getMode()){switch(this.#Fr(),t){case g.NONE:return this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case g.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case g.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 bi.#F.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#Dr?.div}addInkEditorIfNeeded(t){if(this.#u.getMode()===g.INK){if(!t)for(const t of this.#Pr.values())if(t.isEmpty())return void t.setInBackground();this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(t){this.#u.setEditingState(t)}addCommands(t){this.#u.addCommands(t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Cr?.div.classList.toggle("disabled",!t)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const e of this.#Pr.values())e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#u.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));if(!this.#Cr)return;const e=this.#Cr.getEditableAnnotations();for(const s of e){if(s.hide(),this.#u.isDeletedAnnotationElement(s.data.id))continue;if(t.has(s.data.id))continue;const e=this.deserialize(s);e&&(this.addOrRebuild(e),e.enableEditing())}}disable(){this.#Ir=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const s of this.#Pr.values())s.disableEditing(),s.annotationElementId&&(null===s.serialize()?(e.set(s.annotationElementId,s),this.getEditableAnnotation(s.annotationElementId)?.show(),s.remove()):t.set(s.annotationElementId,s));if(this.#Cr){const s=this.#Cr.getEditableAnnotations();for(const i of s){const{id:s}=i.data;if(this.#u.isDeletedAnnotationElement(s))continue;let n=e.get(s);n?(n.resetAnnotationElement(i),n.show(!1),i.show()):(n=t.get(s),n&&(this.#u.addChangedExistingAnnotation(n),n.renderAnnotationElement(i),n.show(!1)),i.show())}}this.#Fr(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const t of bi.#F.values())s.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#Ir=!1}getEditableAnnotation(t){return this.#Cr?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#u.getActive()!==t&&this.#u.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1,this.#Dr?.div&&!this.#Mr&&(this.#Mr=this.#Or.bind(this),this.#Dr.div.addEventListener("pointerdown",this.#Mr),this.#Dr.div.classList.add("highlighting"))}disableTextSelection(){this.div.tabIndex=0,this.#Dr?.div&&this.#Mr&&(this.#Dr.div.removeEventListener("pointerdown",this.#Mr),this.#Mr=null,this.#Dr.div.classList.remove("highlighting"))}#Or(t){if(this.#u.unselectAll(),t.target===this.#Dr.div){const{isMac:e}=$.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#u.showAllEditors("highlight",!0,!0),this.#Dr.div.classList.add("free"),gi.startHighlighting(this,"ltr"===this.#u.direction,t),this.#Dr.div.addEventListener("pointerup",(()=>{this.#Dr.div.classList.remove("free")}),{once:!0}),t.preventDefault()}}enableClick(){this.#Tr||(this.#Tr=this.pointerdown.bind(this),this.#Sr=this.pointerup.bind(this),this.div.addEventListener("pointerdown",this.#Tr),this.div.addEventListener("pointerup",this.#Sr))}disableClick(){this.#Tr&&(this.div.removeEventListener("pointerdown",this.#Tr),this.div.removeEventListener("pointerup",this.#Sr),this.#Tr=null,this.#Sr=null)}attach(t){this.#Pr.set(t.id,t);const{annotationElementId:e}=t;e&&this.#u.isDeletedAnnotationElement(e)&&this.#u.removeDeletedAnnotationElement(t)}detach(t){this.#Pr.delete(t.id),this.#Oi?.removePointerInTextLayer(t.contentDiv),!this.#Ir&&t.annotationElementId&&this.#u.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#u.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,this.#Lr||this.addInkEditorIfNeeded(!1)}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#u.addDeletedAnnotationElement(t.annotationElementId),It.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.#u.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),this.#u.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#kr&&(t._focusEventsAllowed=!1,this.#kr=setTimeout((()=>{this.#kr=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0}),e.focus())}),0)),t._structTreeParentId=this.#Oi?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#u.getId()}get#Nr(){return bi.#F.get(this.#u.getMode())}#Br(t){const e=this.#Nr;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Nr?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#u.updateToolbar(t),this.#u.updateMode(t);const{offsetX:s,offsetY:i}=this.#Hr(),n=this.getNextId(),a=this.#Br({parent:this,id:n,x:s,y:i,uiManager:this.#u,isCentered:!0,...e});a&&this.add(a)}deserialize(t){return bi.#F.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#u)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#Br({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#u,isCentered:e,...s});return n&&this.add(n),n}#Hr(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+s))/2-t,o=(a+Math.min(window.innerHeight,e+i))/2-e,[h,l]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:h,offsetY:l}}addNewEditor(){this.createAndAddNewEditor(this.#Hr(),!0)}setSelected(t){this.#u.setSelected(t)}toggleSelected(t){this.#u.toggleSelected(t)}isSelected(t){return this.#u.isSelected(t)}unselect(t){this.#u.unselect(t)}pointerup(t){const{isMac:e}=$.platform;0!==t.button||t.ctrlKey&&e||t.target===this.div&&this.#Rr&&(this.#Rr=!1,this.#Er?this.#u.getMode()!==g.STAMP?this.createAndAddNewEditor(t,!1):this.#u.unselectAll():this.#Er=!0)}pointerdown(t){if(this.#u.getMode()===g.HIGHLIGHT&&this.enableTextSelection(),this.#Rr)return void(this.#Rr=!1);const{isMac:e}=$.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#Rr=!0;const s=this.#u.getActive();this.#Er=!s||s.isEmpty()}findNewParent(t,e,s){const i=this.#u.findParent(e,s);return null!==i&&i!==this&&(i.changeParent(t),!0)}destroy(){this.#u.getActive()?.parent===this&&(this.#u.commitOrRemove(),this.#u.setActiveEditor(null)),this.#kr&&(clearTimeout(this.#kr),this.#kr=null);for(const t of this.#Pr.values())this.#Oi?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Pr.clear(),this.#u.removeLayer(this)}#Fr(){this.#Lr=!0;for(const t of this.#Pr.values())t.isEmpty()&&t.remove();this.#Lr=!1}render({viewport:t}){this.viewport=t,xt(this.div,t);for(const t of this.#u.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#u.commitOrRemove(),this.#Fr();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,xt(this.div,{rotation:s}),e!==s)for(const t of this.#Pr.values())t.rotate(s);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#u.viewParameters.realScale}}class vi{#fi=null;#f=0;#zr=new Map;#jr=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#fi){if(this.#fi!==t){if(this.#zr.size>0)for(const e of this.#zr.values())e.remove(),t.append(e);this.#fi=t}}else this.#fi=t}static get _svgFactory(){return P(this,"_svgFactory",new at)}static#$r(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+"%"}#Ur(t){const e=vi._svgFactory.create(1,1,!0);return this.#fi.append(e),e.setAttribute("aria-hidden",!0),vi.#$r(e,t),e}#Vr(t,e){const s=vi._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=vi._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}highlight(t,e,s,i=!1){const n=this.#f++,a=this.#Ur(t.box);a.classList.add("highlight"),t.free&&a.classList.add("free");const r=vi._svgFactory.createElement("defs");a.append(r);const o=vi._svgFactory.createElement("path");r.append(o);const h=`path_p${this.pageIndex}_${n}`;o.setAttribute("id",h),o.setAttribute("d",t.toSVGPath()),i&&this.#jr.set(n,o);const l=this.#Vr(r,h),c=vi._svgFactory.createElement("use");return a.append(c),a.setAttribute("fill",e),a.setAttribute("fill-opacity",s),c.setAttribute("href",`#${h}`),this.#zr.set(n,a),{id:n,clipPathId:`url(#${l})`}}highlightOutline(t){const e=this.#f++,s=this.#Ur(t.box);s.classList.add("highlightOutline");const i=vi._svgFactory.createElement("defs");s.append(i);const n=vi._svgFactory.createElement("path");i.append(n);const a=`path_p${this.pageIndex}_${e}`;let r;if(n.setAttribute("id",a),n.setAttribute("d",t.toSVGPath()),n.setAttribute("vector-effect","non-scaling-stroke"),t.free){s.classList.add("free");const t=vi._svgFactory.createElement("mask");i.append(t),r=`mask_p${this.pageIndex}_${e}`,t.setAttribute("id",r),t.setAttribute("maskUnits","objectBoundingBox");const n=vi._svgFactory.createElement("rect");t.append(n),n.setAttribute("width","1"),n.setAttribute("height","1"),n.setAttribute("fill","white");const o=vi._svgFactory.createElement("use");t.append(o),o.setAttribute("href",`#${a}`),o.setAttribute("stroke","none"),o.setAttribute("fill","black"),o.setAttribute("fill-rule","nonzero"),o.classList.add("mask")}const o=vi._svgFactory.createElement("use");s.append(o),o.setAttribute("href",`#${a}`),r&&o.setAttribute("mask",`url(#${r})`);const h=o.cloneNode();return s.append(h),o.classList.add("mainOutline"),h.classList.add("secondaryOutline"),this.#zr.set(e,s),e}finalizeLine(t,e){const s=this.#jr.get(t);this.#jr.delete(t),this.updateBox(t,e.box),s.setAttribute("d",e.toSVGPath())}updateLine(t,e){this.#zr.get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}removeFreeHighlight(t){this.remove(t),this.#jr.delete(t)}updatePath(t,e){this.#jr.get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){vi.#$r(this.#zr.get(t),e)}show(t,e){this.#zr.get(t).classList.toggle("hidden",!e)}rotate(t,e){this.#zr.get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){this.#zr.get(t).setAttribute("fill",e)}changeOpacity(t,e){this.#zr.get(t).setAttribute("fill-opacity",e)}addClass(t,e){this.#zr.get(t).classList.add(e)}removeClass(t,e){this.#zr.get(t).classList.remove(e)}remove(t){null!==this.#fi&&(this.#zr.get(t).remove(),this.#zr.delete(t))}destroy(){this.#fi=null;for(const t of this.#zr.values())t.remove();this.#zr.clear()}}var yi=h.AnnotationLayer,Ai=h.AnnotationMode,wi=h.GlobalWorkerOptions,xi=h.PDFDataRangeTransport,_i=h.TextLayer,Ei=h.getDocument,Ci=s(48045),Si=function(t,e,s){if(s||2===arguments.length)for(var i,n=0,a=e.length;n<a;n++)!i&&n in e||(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},Ti=Si(Si(Si(Si(Si(Si(Si(Si(Si(Si(Si(Si(Si(Si(Si(Si(Si(Si([],["onCopy","onCut","onPaste"],!0),["onCompositionEnd","onCompositionStart","onCompositionUpdate"],!0),["onFocus","onBlur"],!0),["onInput","onInvalid","onReset","onSubmit"],!0),["onLoad","onError"],!0),["onKeyDown","onKeyPress","onKeyUp"],!0),["onAbort","onCanPlay","onCanPlayThrough","onDurationChange","onEmptied","onEncrypted","onEnded","onError","onLoadedData","onLoadedMetadata","onLoadStart","onPause","onPlay","onPlaying","onProgress","onRateChange","onSeeked","onSeeking","onStalled","onSuspend","onTimeUpdate","onVolumeChange","onWaiting"],!0),["onClick","onContextMenu","onDoubleClick","onMouseDown","onMouseEnter","onMouseLeave","onMouseMove","onMouseOut","onMouseOver","onMouseUp"],!0),["onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop"],!0),["onSelect"],!0),["onTouchCancel","onTouchEnd","onTouchMove","onTouchStart"],!0),["onPointerDown","onPointerMove","onPointerUp","onPointerCancel","onGotPointerCapture","onLostPointerCapture","onPointerEnter","onPointerLeave","onPointerOver","onPointerOut"],!0),["onScroll"],!0),["onWheel"],!0),["onAnimationStart","onAnimationEnd","onAnimationIteration"],!0),["onTransitionEnd"],!0),["onChange"],!0),["onToggle"],!0);function Mi(t,e){var s={};return Ti.forEach((function(i){var n=t[i];n&&(s[i]=e?function(t){return n(t,e(i))}:n)})),s}function ki(t){var e=!1;return{promise:new Promise((function(s,i){t.then((function(t){return!e&&s(t)})).catch((function(t){return!e&&i(t)}))})),cancel:function(){e=!0}}}function Pi(t){var e,s,i="";if("string"==typeof t||"number"==typeof t)i+=t;else if("object"==typeof t)if(Array.isArray(t)){var n=t.length;for(e=0;e<n;e++)t[e]&&(s=Pi(t[e]))&&(i&&(i+=" "),i+=s)}else for(s in t)t[s]&&(i&&(i+=" "),i+=s);return i}var Ri=function(){for(var t,e,s=0,i="",n=arguments.length;s<n;s++)(t=arguments[s])&&(e=Pi(t))&&(i&&(i+=" "),i+=e);return i},Li=s(25385),Ii=s(63730),Di=Object.prototype.hasOwnProperty;function Fi(t,e,s){for(s of t.keys())if(Oi(s,e))return s}function Oi(t,e){var s,i,n;if(t===e)return!0;if(t&&e&&(s=t.constructor)===e.constructor){if(s===Date)return t.getTime()===e.getTime();if(s===RegExp)return t.toString()===e.toString();if(s===Array){if((i=t.length)===e.length)for(;i--&&Oi(t[i],e[i]););return-1===i}if(s===Set){if(t.size!==e.size)return!1;for(i of t){if((n=i)&&"object"==typeof n&&!(n=Fi(e,n)))return!1;if(!e.has(n))return!1}return!0}if(s===Map){if(t.size!==e.size)return!1;for(i of t){if((n=i[0])&&"object"==typeof n&&!(n=Fi(e,n)))return!1;if(!Oi(i[1],e.get(n)))return!1}return!0}if(s===ArrayBuffer)t=new Uint8Array(t),e=new Uint8Array(e);else if(s===DataView){if((i=t.byteLength)===e.byteLength)for(;i--&&t.getInt8(i)===e.getInt8(i););return-1===i}if(ArrayBuffer.isView(t)){if((i=t.byteLength)===e.byteLength)for(;i--&&t[i]===e[i];);return-1===i}if(!s||"object"==typeof t){for(s in i=0,t){if(Di.call(t,s)&&++i&&!Di.call(e,s))return!1;if(!(s in e)||!Oi(t[s],e[s]))return!1}return Object.keys(e).length===i}}return t!=t&&e!=e}var Ni=(0,a.createContext)(null);function Bi({children:t,type:e}){return(0,Ci.jsx)("div",{className:`react-pdf__message react-pdf__message--${e}`,children:t})}class Hi{constructor(){this.externalLinkEnabled=!0,this.externalLinkRel=void 0,this.externalLinkTarget=void 0,this.isInPresentationMode=!1,this.pdfDocument=void 0,this.pdfViewer=void 0}setDocument(t){this.pdfDocument=t}setViewer(t){this.pdfViewer=t}setExternalLinkRel(t){this.externalLinkRel=t}setExternalLinkTarget(t){this.externalLinkTarget=t}setHistory(){}get pagesCount(){return this.pdfDocument?this.pdfDocument.numPages:0}get page(){return(0,Li.A)(this.pdfViewer,"PDF viewer is not initialized."),this.pdfViewer.currentPageNumber||0}set page(t){(0,Li.A)(this.pdfViewer,"PDF viewer is not initialized."),this.pdfViewer.currentPageNumber=t}get rotation(){return 0}set rotation(t){}goToDestination(t){return new Promise((e=>{(0,Li.A)(this.pdfDocument,"PDF document not loaded."),(0,Li.A)(t,"Destination is not specified."),"string"==typeof t?this.pdfDocument.getDestination(t).then(e):Array.isArray(t)?e(t):t.then(e)})).then((t=>{(0,Li.A)(Array.isArray(t),`"${t}" is not a valid destination array.`);const e=t[0];new Promise((t=>{(0,Li.A)(this.pdfDocument,"PDF document not loaded."),e instanceof Object?this.pdfDocument.getPageIndex(e).then((e=>{t(e)})).catch((()=>{(0,Li.A)(!1,`"${e}" is not a valid page reference.`)})):"number"==typeof e?t(e):(0,Li.A)(!1,`"${e}" is not a valid destination reference.`)})).then((e=>{const s=e+1;(0,Li.A)(this.pdfViewer,"PDF viewer is not initialized."),(0,Li.A)(s>=1&&s<=this.pagesCount,`"${s}" is not a valid page number.`),this.pdfViewer.scrollPageIntoView({dest:t,pageIndex:e,pageNumber:s})}))}))}navigateTo(t){this.goToDestination(t)}goToPage(t){const e=t-1;(0,Li.A)(this.pdfViewer,"PDF viewer is not initialized."),(0,Li.A)(t>=1&&t<=this.pagesCount,`"${t}" is not a valid page number.`),this.pdfViewer.scrollPageIntoView({pageIndex:e,pageNumber:t})}addLinkAttributes(t,e,s){t.href=e,t.rel=this.externalLinkRel||"noopener noreferrer nofollow",t.target=s?"_blank":this.externalLinkTarget||""}getDestinationHash(){return"#"}getAnchorUrl(){return"#"}setHash(){}executeNamedAction(){}cachePageRef(){}isPageVisible(){return!0}isPageCached(){return!0}executeSetOCGState(){}}var zi=1,ji=2;const $i="undefined"!=typeof document,Ui=$i&&"file:"===window.location.protocol;function Vi(t){return function(t){return void 0!==t}(t)&&null!==t}function Gi(t){return function(t){return"string"==typeof t}(t)&&/^data:/.test(t)}function Wi(t){(0,Li.A)(Gi(t),"Invalid data URI.");const[e="",s=""]=t.split(",");return-1!==e.split(";").indexOf("base64")?atob(s):unescape(s)}function qi(){return $i&&window.devicePixelRatio||1}function Ki(){Ii(!Ui,"Loading PDF as base64 strings/URLs may not work on protocols other than HTTP/HTTPS. On Chromium based browsers, you can use --allow-file-access-from-files flag for debugging purposes.")}function Xi(t){t&&t.cancel&&t.cancel()}function Yi(t,e){return Object.defineProperty(t,"width",{get(){return this.view[2]*e},configurable:!0}),Object.defineProperty(t,"height",{get(){return this.view[3]*e},configurable:!0}),Object.defineProperty(t,"originalWidth",{get(){return this.view[2]},configurable:!0}),Object.defineProperty(t,"originalHeight",{get(){return this.view[3]},configurable:!0}),t}function Qi(t,e){switch(e.type){case"RESOLVE":return{value:e.value,error:void 0};case"REJECT":return{value:!1,error:e.error};case"RESET":return{value:void 0,error:void 0};default:return t}}function Ji(){return(0,a.useReducer)(Qi,{value:void 0,error:void 0})}var Zi=function(t,e){var s={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(s[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(s[i[n]]=t[i[n]])}return s};const{Tm:tn}=i,en=(t,e)=>{switch(e){case zi:t(prompt("Enter the password to open this PDF file."));break;case ji:t(prompt("Invalid password. Please try again."))}};function sn(t){return"object"==typeof t&&null!==t&&("data"in t||"range"in t||"url"in t)}var nn=(0,a.forwardRef)((function(t,e){var{children:s,className:i,error:n="Failed to load PDF file.",externalLinkRel:r,externalLinkTarget:o,file:h,inputRef:l,imageResourcesPath:c,loading:d="Loading PDF…",noData:u="No PDF file specified.",onItemClick:p,onLoadError:g,onLoadProgress:m,onLoadSuccess:f,onPassword:b=en,onSourceError:v,onSourceSuccess:y,options:A,renderMode:w,rotate:x}=t,_=Zi(t,["children","className","error","externalLinkRel","externalLinkTarget","file","inputRef","imageResourcesPath","loading","noData","onItemClick","onLoadError","onLoadProgress","onLoadSuccess","onPassword","onSourceError","onSourceSuccess","options","renderMode","rotate"]);const[E,C]=Ji(),{value:S,error:T}=E,[M,k]=Ji(),{value:P,error:R}=M,L=(0,a.useRef)(new Hi),I=(0,a.useRef)([]),D=(0,a.useRef)(void 0),F=(0,a.useRef)(void 0);h&&h!==D.current&&sn(h)&&(Ii(!Oi(h,D.current),'File prop passed to <Document /> changed, but it\'s equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "file" prop.'),D.current=h),A&&A!==F.current&&(Ii(!Oi(A,F.current),'Options prop passed to <Document /> changed, but it\'s equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "options" prop.'),F.current=A);const O=(0,a.useRef)({scrollPageIntoView:t=>{const{dest:e,pageNumber:s,pageIndex:i=s-1}=t;if(p)return void p({dest:e,pageIndex:i,pageNumber:s});const n=I.current[i];n?n.scrollIntoView():Ii(!1,`An internal link leading to page ${s} was clicked, but neither <Document> was provided with onItemClick nor it was able to find the page within itself. Either provide onItemClick to <Document> and handle navigating by yourself or ensure that all pages are rendered within <Document>.`)}});(0,a.useImperativeHandle)(e,(()=>({linkService:L,pages:I,viewer:O})),[]),(0,a.useEffect)((function(){C({type:"RESET"})}),[h,C]);const N=(0,a.useCallback)((()=>{return t=this,e=void 0,i=function*(){if(!h)return null;if("string"==typeof h)return Gi(h)?{data:Wi(h)}:(Ki(),{url:h});if(h instanceof tn)return{range:h};if(h instanceof ArrayBuffer)return{data:h};if($i&&(t=h,(0,Li.A)($i,"isBlob can only be used in a browser environment"),t instanceof Blob)){const t=yield function(t){return new Promise(((e,s)=>{const i=new FileReader;i.onload=()=>{if(!i.result)return s(new Error("Error while reading a file."));e(i.result)},i.onerror=t=>{if(!t.target)return s(new Error("Error while reading a file."));const{error:e}=t.target;if(!e)return s(new Error("Error while reading a file."));switch(e.code){case e.NOT_FOUND_ERR:return s(new Error("Error while reading a file: File not found."));case e.SECURITY_ERR:return s(new Error("Error while reading a file: Security error."));case e.ABORT_ERR:return s(new Error("Error while reading a file: Aborted."));default:return s(new Error("Error while reading a file."))}},i.readAsArrayBuffer(t)}))}(h);return{data:t}}var t;if((0,Li.A)("object"==typeof h,"Invalid parameter in file, need either Uint8Array, string or a parameter object"),(0,Li.A)(sn(h),"Invalid parameter object: need either .data, .range or .url"),"url"in h&&"string"==typeof h.url){if(Gi(h.url)){const{url:t}=h,e=Zi(h,["url"]),s=Wi(t);return Object.assign({data:s},e)}Ki()}return h},new((s=void 0)||(s=Promise))((function(n,a){function r(t){try{h(i.next(t))}catch(t){a(t)}}function o(t){try{h(i.throw(t))}catch(t){a(t)}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(r,o)}h((i=i.apply(t,e||[])).next())}));var t,e,s,i}),[h]);function B(t,e){I.current[t]=e}function H(t){delete I.current[t]}(0,a.useEffect)((()=>{const t=ki(N());return t.promise.then((t=>{C({type:"RESOLVE",value:t})})).catch((t=>{C({type:"REJECT",error:t})})),()=>{Xi(t)}}),[N,C]),(0,a.useEffect)((()=>{void 0!==S&&(!1!==S?y&&y():T&&(Ii(!1,T.toString()),v&&v(T)))}),[S]),(0,a.useEffect)((function(){k({type:"RESET"})}),[k,S]),(0,a.useEffect)((function(){if(!S)return;const t=Object.assign(Object.assign({},S),A),e=Ei(t);m&&(e.onProgress=m),b&&(e.onPassword=b);const s=e;return s.promise.then((t=>{k({type:"RESOLVE",value:t})})).catch((t=>{s.destroyed||k({type:"REJECT",error:t})})),()=>{s.destroy()}}),[A,k,S]),(0,a.useEffect)((()=>{void 0!==P&&(!1!==P?P&&(f&&f(P),I.current=new Array(P.numPages),L.current.setDocument(P)):R&&(Ii(!1,R.toString()),g&&g(R)))}),[P]),(0,a.useEffect)((function(){L.current.setViewer(O.current),L.current.setExternalLinkRel(r),L.current.setExternalLinkTarget(o)}),[r,o]);const z=(0,a.useMemo)((()=>({imageResourcesPath:c,linkService:L.current,onItemClick:p,pdf:P,registerPage:B,renderMode:w,rotate:x,unregisterPage:H})),[c,p,P,w,x]),j=(0,a.useMemo)((()=>Mi(_,(()=>P))),[_,P]);return(0,Ci.jsx)("div",Object.assign({className:Ri("react-pdf__Document",i),ref:l,style:{"--scale-factor":"1"}},j,{children:h?null==P?(0,Ci.jsx)(Bi,{type:"loading",children:"function"==typeof d?d():d}):!1===P?(0,Ci.jsx)(Bi,{type:"error",children:"function"==typeof n?n():n}):(0,Ci.jsx)(Ni.Provider,{value:z,children:s}):(0,Ci.jsx)(Bi,{type:"no-data",children:"function"==typeof u?u():u})}))}));function an(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var s=t.filter(Boolean);return s.length<=1?s[0]||null:function(t){s.forEach((function(e){"function"==typeof e?e(t):e&&(e.current=t)}))}}var rn=(0,a.createContext)(null);const on={Document:null,DocumentFragment:null,Part:"group",Sect:"group",Div:"group",Aside:"note",NonStruct:"none",P:null,H:"heading",Title:null,FENote:"note",Sub:"group",Lbl:null,Span:null,Em:null,Strong:null,Link:"link",Annot:"note",Form:"form",Ruby:null,RB:null,RT:null,RP:null,Warichu:null,WT:null,WP:null,L:"list",LI:"listitem",LBody:null,Table:"table",TR:"row",TH:"columnheader",TD:"cell",THead:"columnheader",TBody:null,TFoot:null,Caption:null,Figure:"figure",Formula:null,Artifact:null},hn=/^H(\d+)$/;function ln(t){return"children"in t}function cn(t){return!!ln(t)&&1===t.children.length&&0 in t.children&&"id"in t.children[0]}function dn(t){const e={};if(ln(t)){if(void 0!==t.alt&&(e["aria-label"]=t.alt),void 0!==t.lang&&(e.lang=t.lang),cn(t)){const[s]=t.children;if(s){const t=dn(s);return Object.assign(Object.assign({},e),t)}}}else"id"in t&&(e["aria-owns"]=t.id);return e}function un(t){return t?Object.assign(Object.assign({},function(t){const e={};if(ln(t)){const{role:s}=t,i=s.match(hn);if(i)e.role="heading",e["aria-level"]=Number(i[1]);else if(function(t){return t in on}(s)){const t=on[s];t&&(e.role=t)}}return e}(t)),dn(t)):null}function pn({className:t,node:e}){const s=(0,a.useMemo)((()=>un(e)),[e]),i=(0,a.useMemo)((()=>ln(e)?cn(e)?null:e.children.map(((t,e)=>(0,Ci.jsx)(pn,{node:t},e))):null),[e]);return(0,Ci.jsx)("span",Object.assign({className:t},s,{children:i}))}function gn(){return(0,a.useContext)(rn)}function mn(){const t=gn();(0,Li.A)(t,"Unable to find Page context.");const{onGetStructTreeError:e,onGetStructTreeSuccess:s}=t,[i,n]=Ji(),{value:r,error:o}=i,{customTextRenderer:h,page:l}=t;return(0,a.useEffect)((function(){n({type:"RESET"})}),[n,l]),(0,a.useEffect)((function(){if(h)return;if(!l)return;const t=ki(l.getStructTree()),e=t;return t.promise.then((t=>{n({type:"RESOLVE",value:t})})).catch((t=>{n({type:"REJECT",error:t})})),()=>Xi(e)}),[h,l,n]),(0,a.useEffect)((()=>{void 0!==r&&(!1!==r?r&&s&&s(r):o&&(Ii(!1,o.toString()),e&&e(o)))}),[r]),r?(0,Ci.jsx)(pn,{className:"react-pdf__Page__structTree structTree",node:r}):null}const fn=Ai;function bn(t){const e=gn();(0,Li.A)(e,"Unable to find Page context.");const s=Object.assign(Object.assign({},e),t),{_className:i,canvasBackground:n,devicePixelRatio:r=qi(),onRenderError:o,onRenderSuccess:h,page:l,renderForms:c,renderTextLayer:d,rotate:u,scale:p}=s,{canvasRef:g}=t;(0,Li.A)(l,"Attempted to render page canvas, but no page was specified.");const m=(0,a.useRef)(null);function f(t){(function(t){return"RenderingCancelledException"===t.name})(t)||(Ii(!1,t.toString()),o&&o(t))}const b=(0,a.useMemo)((()=>l.getViewport({scale:p*r,rotation:u})),[r,l,u,p]),v=(0,a.useMemo)((()=>l.getViewport({scale:p,rotation:u})),[l,u,p]);(0,a.useEffect)((function(){if(!l)return;l.cleanup();const{current:t}=m;if(!t)return;t.width=b.width,t.height=b.height,t.style.width=`${Math.floor(v.width)}px`,t.style.height=`${Math.floor(v.height)}px`,t.style.visibility="hidden";const e={annotationMode:c?fn.ENABLE_FORMS:fn.ENABLE,canvasContext:t.getContext("2d",{alpha:!1}),viewport:b};n&&(e.background=n);const s=l.render(e),i=s;return s.promise.then((()=>{t.style.visibility="",l&&h&&h(Yi(l,p))})).catch(f),()=>Xi(i)}),[n,m,r,l,c,b,v]);const y=(0,a.useCallback)((()=>{const{current:t}=m;t&&(t.width=0,t.height=0)}),[m]);return(0,a.useEffect)((()=>y),[y]),(0,Ci.jsx)("canvas",{className:`${i}__canvas`,dir:"ltr",ref:an(g,m),style:{display:"block",userSelect:"none"},children:d?(0,Ci.jsx)(mn,{}):null})}function vn(){const t=gn();(0,Li.A)(t,"Unable to find Page context.");const{customTextRenderer:e,onGetTextError:s,onGetTextSuccess:i,onRenderTextLayerError:n,onRenderTextLayerSuccess:r,page:o,pageIndex:h,pageNumber:l,rotate:c,scale:d}=t;(0,Li.A)(o,"Attempted to load page text content, but no page was specified.");const[u,p]=Ji(),{value:g,error:m}=u,f=(0,a.useRef)(null),b=(0,a.useRef)(void 0);Ii(1===parseInt(window.getComputedStyle(document.body).getPropertyValue("--react-pdf-text-layer"),10),"TextLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-text-layer"),(0,a.useEffect)((function(){p({type:"RESET"})}),[o,p]),(0,a.useEffect)((function(){if(!o)return;const t=ki(o.getTextContent()),e=t;return t.promise.then((t=>{p({type:"RESOLVE",value:t})})).catch((t=>{p({type:"REJECT",error:t})})),()=>Xi(e)}),[o,p]),(0,a.useEffect)((()=>{void 0!==g&&(!1!==g?g&&i&&i(g):m&&(Ii(!1,m.toString()),s&&s(m)))}),[g]);const v=(0,a.useCallback)((()=>{r&&r()}),[r]),y=(0,a.useCallback)((t=>{Ii(!1,t.toString()),n&&n(t)}),[n]),A=(0,a.useMemo)((()=>o.getViewport({scale:d,rotation:c})),[o,c,d]);return(0,a.useLayoutEffect)((function(){if(!o||!g)return;const{current:t}=f;if(!t)return;t.innerHTML="";const s=o.streamTextContent({includeMarkedContent:!0}),i=new _i({container:t,textContentSource:s,viewport:A}),n=i;return i.render().then((()=>{const s=document.createElement("div");s.className="endOfContent",t.append(s),b.current=s;const i=t.querySelectorAll('[role="presentation"]');if(e){let t=0;g.items.forEach(((s,n)=>{if(!function(t){return"str"in t}(s))return;const a=i[t];if(!a)return;const r=e(Object.assign({pageIndex:h,pageNumber:l,itemIndex:n},s));a.innerHTML=r,t+=s.str&&s.hasEOL?2:1}))}v()})).catch(y),()=>Xi(n)}),[e,y,v,o,h,l,g,A]),(0,Ci.jsx)("div",{className:Ri("react-pdf__Page__textContent","textLayer"),onMouseUp:function(){const t=b.current;t&&t.classList.remove("active")},onMouseDown:function(){const t=b.current;t&&t.classList.add("active")},ref:f})}function yn(){return(0,a.useContext)(Ni)}function An(){const t=yn(),e=gn();(0,Li.A)(e,"Unable to find Page context.");const s=Object.assign(Object.assign({},t),e),{imageResourcesPath:i,linkService:n,onGetAnnotationsError:r,onGetAnnotationsSuccess:o,onRenderAnnotationLayerError:h,onRenderAnnotationLayerSuccess:l,page:c,pdf:d,renderForms:u,rotate:p,scale:g=1}=s;(0,Li.A)(d,"Attempted to load page annotations, but no document was specified. Wrap <Page /> in a <Document /> or pass explicit `pdf` prop."),(0,Li.A)(c,"Attempted to load page annotations, but no page was specified."),(0,Li.A)(n,"Attempted to load page annotations, but no linkService was specified.");const[m,f]=Ji(),{value:b,error:v}=m,y=(0,a.useRef)(null);Ii(1===parseInt(window.getComputedStyle(document.body).getPropertyValue("--react-pdf-annotation-layer"),10),"AnnotationLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-annotations"),(0,a.useEffect)((function(){f({type:"RESET"})}),[f,c]),(0,a.useEffect)((function(){if(!c)return;const t=ki(c.getAnnotations()),e=t;return t.promise.then((t=>{f({type:"RESOLVE",value:t})})).catch((t=>{f({type:"REJECT",error:t})})),()=>{Xi(e)}}),[f,c,u]),(0,a.useEffect)((()=>{void 0!==b&&(!1!==b?b&&o&&o(b):v&&(Ii(!1,v.toString()),r&&r(v)))}),[b]);const A=(0,a.useMemo)((()=>c.getViewport({scale:g,rotation:p})),[c,p,g]);return(0,a.useEffect)((function(){if(!(d&&c&&n&&b))return;const{current:t}=y;if(!t)return;const e=A.clone({dontFlip:!0}),s={accessibilityManager:null,annotationCanvasMap:null,annotationEditorUIManager:null,div:t,l10n:null,page:c,viewport:e},a={annotations:b,annotationStorage:d.annotationStorage,div:t,imageResourcesPath:i,linkService:n,page:c,renderForms:u,viewport:e};t.innerHTML="";try{new yi(s).render(a),l&&l()}catch(t){!function(t){Ii(!1,`${t}`),h&&h(t)}(t)}return()=>{}}),[b,i,n,c,u,A]),(0,Ci.jsx)("div",{className:Ri("react-pdf__Page__annotations","annotationLayer"),ref:y})}const wn=1;function xn(t){const e=yn(),s=Object.assign(Object.assign({},e),t),{_className:i="react-pdf__Page",_enableRegisterUnregisterPage:n=!0,canvasBackground:r,canvasRef:o,children:h,className:l,customRenderer:c,customTextRenderer:d,devicePixelRatio:u,error:p="Failed to load the page.",height:g,inputRef:m,loading:f="Loading page…",noData:b="No page specified.",onGetAnnotationsError:v,onGetAnnotationsSuccess:y,onGetStructTreeError:A,onGetStructTreeSuccess:w,onGetTextError:x,onGetTextSuccess:_,onLoadError:E,onLoadSuccess:C,onRenderAnnotationLayerError:S,onRenderAnnotationLayerSuccess:T,onRenderError:M,onRenderSuccess:k,onRenderTextLayerError:P,onRenderTextLayerSuccess:R,pageIndex:L,pageNumber:I,pdf:D,registerPage:F,renderAnnotationLayer:O=!0,renderForms:N=!1,renderMode:B="canvas",renderTextLayer:H=!0,rotate:z,scale:j=wn,unregisterPage:$,width:U}=s,V=function(t,e){var s={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(s[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(s[i[n]]=t[i[n]])}return s}(s,["_className","_enableRegisterUnregisterPage","canvasBackground","canvasRef","children","className","customRenderer","customTextRenderer","devicePixelRatio","error","height","inputRef","loading","noData","onGetAnnotationsError","onGetAnnotationsSuccess","onGetStructTreeError","onGetStructTreeSuccess","onGetTextError","onGetTextSuccess","onLoadError","onLoadSuccess","onRenderAnnotationLayerError","onRenderAnnotationLayerSuccess","onRenderError","onRenderSuccess","onRenderTextLayerError","onRenderTextLayerSuccess","pageIndex","pageNumber","pdf","registerPage","renderAnnotationLayer","renderForms","renderMode","renderTextLayer","rotate","scale","unregisterPage","width"]),[G,W]=Ji(),{value:q,error:K}=G,X=(0,a.useRef)(null);(0,Li.A)(D,"Attempted to load a page, but no document was specified. Wrap <Page /> in a <Document /> or pass explicit `pdf` prop.");const Y=Vi(I)?I-1:null!=L?L:null,Q=null!=I?I:Vi(L)?L+1:null,J=null!=z?z:q?q.rotate:null,Z=(0,a.useMemo)((()=>{if(!q)return null;let t=1;const e=null!=j?j:wn;if(U||g){const e=q.getViewport({scale:1,rotation:J});U?t=U/e.width:g&&(t=g/e.height)}return e*t}),[g,q,J,j,U]);(0,a.useEffect)((function(){return()=>{Vi(Y)&&n&&$&&$(Y)}}),[n,D,Y,$]),(0,a.useEffect)((function(){W({type:"RESET"})}),[W,D,Y]),(0,a.useEffect)((function(){if(!D||!Q)return;const t=ki(D.getPage(Q)),e=t;return t.promise.then((t=>{W({type:"RESOLVE",value:t})})).catch((t=>{W({type:"REJECT",error:t})})),()=>Xi(e)}),[W,D,Y,Q,F]),(0,a.useEffect)((()=>{void 0!==q&&(!1!==q?function(){if(C){if(!q||!Z)return;C(Yi(q,Z))}if(n&&F){if(!Vi(Y)||!X.current)return;F(Y,X.current)}}():K&&(Ii(!1,K.toString()),E&&E(K)))}),[q,Z]);const tt=(0,a.useMemo)((()=>q&&Vi(Y)&&Q&&Vi(J)&&Vi(Z)?{_className:i,canvasBackground:r,customTextRenderer:d,devicePixelRatio:u,onGetAnnotationsError:v,onGetAnnotationsSuccess:y,onGetStructTreeError:A,onGetStructTreeSuccess:w,onGetTextError:x,onGetTextSuccess:_,onRenderAnnotationLayerError:S,onRenderAnnotationLayerSuccess:T,onRenderError:M,onRenderSuccess:k,onRenderTextLayerError:P,onRenderTextLayerSuccess:R,page:q,pageIndex:Y,pageNumber:Q,renderForms:N,renderTextLayer:H,rotate:J,scale:Z}:null),[i,r,d,u,v,y,A,w,x,_,S,T,M,k,P,R,q,Y,Q,N,H,J,Z]),et=(0,a.useMemo)((()=>Mi(V,(()=>q?Z?Yi(q,Z):void 0:q))),[V,q,Z]),st=`${Y}@${Z}/${J}`;return(0,Ci.jsx)("div",Object.assign({className:Ri(i,l),"data-page-number":Q,ref:an(m,X),style:{"--scale-factor":`${Z}`,backgroundColor:r||"white",position:"relative",minWidth:"min-content",minHeight:"min-content"}},et,{children:Q?null===D||null==q?(0,Ci.jsx)(Bi,{type:"loading",children:"function"==typeof f?f():f}):!1===D||!1===q?(0,Ci.jsx)(Bi,{type:"error",children:"function"==typeof p?p():p}):(0,Ci.jsxs)(rn.Provider,{value:tt,children:[function(){switch(B){case"custom":return(0,Li.A)(c,'renderMode was set to "custom", but no customRenderer was passed.'),(0,Ci.jsx)(c,{},`${st}_custom`);case"none":return null;default:return(0,Ci.jsx)(bn,{canvasRef:o},`${st}_canvas`)}}(),H?(0,Ci.jsx)(vn,{},`${st}_text`):null,O?(0,Ci.jsx)(An,{},`${st}_annotations`):null,h]}):(0,Ci.jsx)(Bi,{type:"no-data",children:"function"==typeof b?b():b})}))}var _n=s(70337),En=s(20568),Cn=s(76089),Sn=(0,r.IWl)((function(t){var e=t.pdfjsWorkerSrc,s=t.classnames,i=t.className,r=t.loading,o=t.width,h=void 0===o?300:o,l=(0,n.zs)(a.useState(t.file),2),c=l[0],d=l[1],u=(0,n.zs)(a.useState(!1),2),p=u[0],g=u[1],m=(0,n.zs)(a.useState(1),2),f=m[0],b=m[1],v=(0,n.zs)(a.useState(1),2),y=v[0],A=v[1],w=(0,n.zs)(a.useState(1),2),x=w[0],_=w[1],E=a.useRef();function C(t){var e=f+t;e<=0||e>x||b(e)}function S(t){A(y*t)}function T(){return a.createElement("div",{className:s("PdfViewer-Loading")},a.createElement(Cn.A,null))}return a.useEffect((function(){e&&(wi.workerSrc=e)}),[t.pdfjsWorkerSrc]),a.useEffect((function(){t.file instanceof ArrayBuffer&&t.file.byteLength>0?d(t.file):d(void 0)}),[t.file]),a.createElement("div",{className:s(i,"PdfViewer")},!c||r?T():a.createElement(a.Fragment,null,a.createElement("div",{className:s("PdfViewer-Content",{"is-loaded":p})},a.createElement(nn,{file:c,onLoadSuccess:function(t){var e=t.numPages;g(!0),_(e)},onLoadError:function(t){return console.log(t)},loading:T()},a.createElement(xn,{className:s("PdfViewer-Content-Page"),pageNumber:f,width:h,height:t.height,loading:T(),noData:a.createElement("div",null,"No PDF data"),scale:y,renderTextLayer:!1,renderAnnotationLayer:!1}))),p?a.createElement("div",{className:s("PdfViewer-Tool")},a.createElement(_n.In,{className:"icon",icon:"prev",onClick:function(){return C(-1)}}),a.createElement(En.A,{className:"page-input",value:f,onBlur:function(t){var e=+t.target.value;isNaN(e)||e<=0||e>x?E.current&&(E.current.value=f+""):b(e)},ref:E}),a.createElement("span",{className:"gap"},"/"),a.createElement("span",null,x),a.createElement(_n.In,{className:"icon",icon:"next",onClick:function(){return C(1)}}),a.createElement(_n.In,{className:"icon",icon:"zoom-in",onClick:function(){return S(1.2)}}),a.createElement(_n.In,{className:"icon",icon:"zoom-out",onClick:function(){return S(.8)}})):null))}))}}]);
|