directus-extension-texttoanything 1.7.7 → 1.7.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app.js +1 -1
- package/package.json +1 -1
package/dist/app.js
CHANGED
|
@@ -19,4 +19,4 @@ import{defineOperationApp as t,useStores as e,useApi as i,defineModule as s,defi
|
|
|
19
19
|
*
|
|
20
20
|
* @licend The above is the entire license notice for the
|
|
21
21
|
* JavaScript code in this page
|
|
22
|
-
*/const Cr=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),Rr=[.001,0,0,.001,0,0],Mr=1.35,Pr=1,Lr=2,Dr=4,Ir=16,Or=32,Nr=64,Fr=128,Br=256,jr={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},zr={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,SIGNATURE:101},Vr={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,DRAW_STEP:41},Ur=0,Hr=1,$r=2,Wr=3,Gr=3,qr=4,Kr={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Xr={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},Yr=1,Qr=2,Jr=3,Zr=4,to=5,eo={ERRORS:0,WARNINGS:1,INFOS:5},io={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},so=0,no=1,ao=2,ro=3;let oo=eo.WARNINGS;function lo(t){Number.isInteger(t)&&(oo=t)}function ho(){return oo}function co(t){oo>=eo.INFOS&&console.log(`Info: ${t}`)}function uo(t){oo>=eo.WARNINGS&&console.log(`Warning: ${t}`)}function po(t){throw new Error(t)}function go(t,e){t||po(e)}function fo(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=decodeURIComponent(escape(t))}catch{}}const s=e?URL.parse(t,e):URL.parse(t);return function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s)?s:null}function _o(t,e,i=!1){const s=URL.parse(t);return s?(s.hash=e,s.href):i&&fo(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function mo(t,e,i,s=!1){return Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1}),i}const vo=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class bo extends vo{constructor(t,e){super(t,"PasswordException"),this.code=e}}class yo extends vo{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class wo extends vo{constructor(t){super(t,"InvalidPDFException")}}class xo extends vo{constructor(t,e,i){super(t,"ResponseException"),this.status=e,this.missing=i}}class Ao extends vo{constructor(t){super(t,"FormatError")}}class ko extends vo{constructor(t){super(t,"AbortException")}}function To(t){"object"==typeof t&&void 0!==t?.length||po("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const s=[];for(let n=0;n<e;n+=i){const a=Math.min(n+i,e),r=t.subarray(n,a);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function So(t){"string"!=typeof t&&po("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let s=0;s<e;++s)i[s]=255&t.charCodeAt(s);return i}class Eo{static get isLittleEndian(){return mo(this,"isLittleEndian",function(){const t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return mo(this,"isEvalSupported",function(){try{return new Function(""),!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return mo(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return mo(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){const{platform:t,userAgent:e}=navigator;return mo(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCSSRoundSupported(){return mo(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const Co=Array.from(Array(256).keys(),(t=>t.toString(16).padStart(2,"0")));class Ro{static makeHexColor(t,e,i){return`#${Co[t]}${Co[e]}${Co[i]}`}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e,i=0){const s=t[i],n=t[i+1];t[i]=s*e[0]+n*e[2]+e[4],t[i+1]=s*e[1]+n*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const s=e[0],n=e[1],a=e[2],r=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],c=t[i+e+1];t[i+e]=h*s+c*a+o,t[i+e+1]=h*n+c*r+l}}static applyInverseTransform(t,e){const i=t[0],s=t[1],n=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-s*e[2]+e[2]*e[5]-e[4]*e[3])/n,t[1]=(-i*e[1]+s*e[0]+e[4]*e[1]-e[5]*e[0])/n}static axialAlignedBoundingBox(t,e,i){const s=e[0],n=e[1],a=e[2],r=e[3],o=e[4],l=e[5],h=t[0],c=t[1],d=t[2],u=t[3];let p=s*h+o,g=p,f=s*d+o,_=f,m=r*c+l,v=m,b=r*u+l,y=b;if(0!==n||0!==a){const t=n*h,e=n*d,i=a*c,s=a*u;p+=i,_+=i,f+=s,g+=s,m+=t,y+=t,b+=e,v+=e}i[0]=Math.min(i[0],p,f,g,_),i[1]=Math.min(i[1],m,b,v,y),i[2]=Math.max(i[2],p,f,g,_),i[3]=Math.max(i[3],m,b,v,y)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const i=t[0],s=t[1],n=t[2],a=t[3],r=i**2+s**2,o=i*n+s*a,l=n**2+a**2,h=(r+l)/2,c=Math.sqrt(h**2-(r*l-o**2));e[0]=Math.sqrt(h+c||1),e[1]=Math.sqrt(h-c||1)}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 i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t),i[1]=Math.min(i[1],e),i[2]=Math.max(i[2],t),i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,s,n){n[0]=Math.min(n[0],t,i),n[1]=Math.min(n[1],e,s),n[2]=Math.max(n[2],t,i),n[3]=Math.max(n[3],e,s)}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const c=1-l,d=l*l,u=d*l,p=c*(c*(c*t+3*l*e)+3*d*i)+u*s,g=c*(c*(c*n+3*l*a)+3*d*r)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,c,d){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-c/h,d));const u=h**2-4*c*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,d),this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,d)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){l[0]=Math.min(l[0],t,r),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,r),l[3]=Math.max(l[3],e,o),this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l),this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l)}}let Mo=null,Po=null;function Lo(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);return crypto.getRandomValues(t),To(t)}const Do="pdfjs_internal_id_";function Io(t,e,i){return Math.min(Math.max(t,e),i)}function Oo(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(To(t))}"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise((i=>{i(t(...e))}))}),"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(t){return t.reduce(((t,e)=>t+e),0)});const No="http://www.w3.org/2000/svg";class Fo{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Bo(t,e="text"){if($o(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{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)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void i(n.response)}i(n.responseText)}},n.send(null)}))}class jo{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t,this.userUnit=e,this.scale=i,this.rotation=s,this.offsetX=n,this.offsetY=a,i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,c,d,u,p,g,f,_;switch((s%=360)<0&&(s+=360),s){case 180:h=-1,c=0,d=0,u=1;break;case 90:h=0,c=1,d=1,u=0;break;case 270:h=0,c=-1,d=-1,u=0;break;case 0:h=1,c=0,d=0,u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}r&&(d=-d,u=-u),0===h?(p=Math.abs(l-t[1])*i+n,g=Math.abs(o-t[0])*i+a,f=(t[3]-t[1])*i,_=(t[2]-t[0])*i):(p=Math.abs(o-t[0])*i+n,g=Math.abs(l-t[1])*i+a,f=(t[2]-t[0])*i,_=(t[3]-t[1])*i),this.transform=[h*i,c*i,d*i,u*i,p-h*i*o-d*i*l,g-c*i*o-u*i*l],this.width=f,this.height=_}get rawDims(){const t=this.viewBox;return mo(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new jo({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){const i=[t,e];return Ro.applyTransform(i,this.transform),i}convertToViewportRectangle(t){const e=[t[0],t[1]];Ro.applyTransform(e,this.transform);const i=[t[2],t[3]];return Ro.applyTransform(i,this.transform),[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){const i=[t,e];return Ro.applyInverseTransform(i,this.transform),i}}class zo extends vo{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Vo(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function Uo(t){return"string"==typeof t&&/\.pdf$/i.test(t)}class Ho{started=Object.create(null);times=[];time(t){t in this.started&&uo(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||uo(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:s,end:n}of this.times)t.push(`${i.padEnd(e)} ${n-s}ms\n`);return t.join("")}}function $o(t,e){const i=e?URL.parse(t,e):URL.parse(t);return"http:"===i?.protocol||"https:"===i?.protocol}function Wo(t){t.preventDefault()}function Go(t){t.preventDefault(),t.stopPropagation()}class qo{static#i;static toDateObject(t){if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#i.exec(t);if(!e)return null;const i=parseInt(e[1],10);let s=parseInt(e[2],10);s=s>=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let c=parseInt(e[9],10)||0;return c=c>=0&&c<=59?c:0,"-"===l?(a+=h,r+=c):"+"===l&&(a-=h,r-=c),new Date(Date.UTC(i,s,n,a,r,o))}}function Ko(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):(uo(`Not a valid color format: "${t}"`),[0,0,0])}function Xo(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function Yo(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function Qo(t,e,i=!1,s=!0){if(e instanceof jo){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=Eo.isCSSRoundSupported,o=`var(--total-scale-factor) * ${s}px`,l=`var(--total-scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x))`:`calc(${o})`,c=r?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;i&&e.rotation%180!=0?(a.width=c,a.height=h):(a.width=h,a.height=c)}s&&t.setAttribute("data-main-rotation",e.rotation)}class Jo{constructor(){const{pixelRatio:t}=Jo;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,i,s,n=-1){let a=1/0,r=1/0,o=1/0;(i=Jo.capPixels(i,n))>0&&(a=Math.sqrt(i/(t*e))),-1!==s&&(r=s/t,o=s/e);const l=Math.min(a,r,o);return(this.sx>l||this.sy>l)&&(this.sx=l,this.sy=l,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}}const Zo=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class tl{#s=null;#n=null;#a;#r=null;#o=null;#l=null;static#h=null;constructor(t){this.#a=t,tl.#h||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",Wo,{signal:e}),t.addEventListener("pointerdown",tl.#c,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons",t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#s}static#c(t){t.stopPropagation()}#u(t){this.#a._focusEventsAllowed=!1,Go(t)}#p(t){this.#a._focusEventsAllowed=!0,Go(t)}#g(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#u.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#p.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Wo,{signal:e})}hide(){this.#s.classList.add("hidden"),this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden"),this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete",i.tabIndex=0,i.setAttribute("data-l10n-id",tl.#h[t]),this.#g(i),i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal}),this.#r.append(i)}get#f(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#g(e),this.#r.prepend(e,this.#f),this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#g(e),this.#r.prepend(e,this.#f)}async addEditSignatureButton(t){const e=this.#l=await t.renderEditButton(this.#a);this.#g(e),this.#r.prepend(e,this.#f)}updateEditSignatureButton(t){this.#l&&(this.#l.title=t)}remove(){this.#s.remove(),this.#n?.destroy(),this.#n=null}}class el{#r=null;#s=null;#_;constructor(t){this.#_=t}#m(){const t=this.#s=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",Wo,{signal:this.#_._signal});const e=this.#r=document.createElement("div");return e.className="buttons",t.append(e),this.#v(),t}#b(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(t<i)continue;const a=n.x+(e?n.width:0);t>i?(s=a,i=t):e?a>s&&(s=a):a<s&&(s=a)}return[e?1-s:s,i]}show(t,e,i){const[s,n]=this.#b(e,i),{style:a}=this.#s||=this.#m();t.append(this.#s),a.insetInlineEnd=100*s+"%",a.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#s.remove()}#v(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const i=this.#_._signal;t.addEventListener("contextmenu",Wo,{signal:i}),t.addEventListener("click",(()=>{this.#_.highlightSelection("floating_button")}),{signal:i}),this.#r.append(t)}}function il(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class sl{#y=0;get id(){return"pdfjs_internal_editor_"+this.#y++}}class nl{#w=Lo();#y=0;#x=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,<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>';return mo(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#A(t,e){this.#x||=new Map;let i=this.#x.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#w}_${this.#y++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await Bo(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=nl._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n,i.isSvg=!0,t()},s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=s.onerror=a}));s.readAsDataURL(t),await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){uo(t),i=null}return this.#x.set(t,i),i&&this.#x.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#A(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#A(t,t)}async getFromBlob(t,e){const i=await e;return this.#A(t,i)}async getFromId(t){this.#x||=new Map;const e=this.#x.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#x||=new Map;let i=this.#x.get(t);if(i?.bitmap)return i.refCounter+=1,i;const s=new OffscreenCanvas(e.width,e.height);return s.getContext("2d").drawImage(e,0,0),i={bitmap:s.transferToImageBitmap(),id:`image_${this.#w}_${this.#y++}`,refCounter:1,isSvg:!1},this.#x.set(t,i),this.#x.set(i.id,i),i}getSvgUrl(t){const e=this.#x.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#x||=new Map;const e=this.#x.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#w}_`)}}class al{#k=[];#T=!1;#S;#E=-1;constructor(t=128){this.#S=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(s&&t(),this.#T)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#E)return this.#k.length>0&&(this.#k.length=0),this.#E=0,void this.#k.push(o);if(a&&this.#k[this.#E].type===n)return r&&(o.undo=this.#k[this.#E].undo),void(this.#k[this.#E]=o);const l=this.#E+1;l===this.#S?this.#k.splice(0,1):(this.#E=l,l<this.#k.length&&this.#k.splice(l)),this.#k.push(o)}undo(){if(-1===this.#E)return;this.#T=!0;const{undo:t,post:e}=this.#k[this.#E];t(),e?.(),this.#T=!1,this.#E-=1}redo(){if(this.#E<this.#k.length-1){this.#E+=1,this.#T=!0;const{cmd:t,post:e}=this.#k[this.#E];t(),e?.(),this.#T=!1}}hasSomethingToUndo(){return-1!==this.#E}hasSomethingToRedo(){return this.#E<this.#k.length-1}cleanType(t){if(-1!==this.#E){for(let e=this.#E;e>=0;e--)if(this.#k[e].type!==t)return this.#k.splice(e+1,this.#E-e),void(this.#E=e);this.#k.length=0,this.#E=-1}}destroy(){this.#k=null}}class rl{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Eo.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");e&&i?(this.callbacks.set(t.slice(4),{callback:s,options:n}),this.allKeys.add(t.split("+").at(-1))):e||i||(this.callbacks.set(t,{callback:s,options:n}),this.allKeys.add(t.split("+").at(-1)))}}#C(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 i=this.callbacks.get(this.#C(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;r&&!r(t,e)||(s.bind(t,...a,e)(),n||Go(e))}}class ol{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",e.style.colorScheme="only light",document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,Ko(s))}e.remove()}(t),mo(this,"_colors",t)}convert(t){const e=Ko(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ol._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Ro.makeHexColor(...e):t}}class ll{#R=new AbortController;#M=null;#P=new Map;#L=new Map;#D=null;#I=null;#O=null;#N=new al;#F=null;#B=null;#j=0;#z=new Set;#V=null;#U=null;#H=new Set;_editorUndoBar=null;#$=!1;#W=!1;#G=!1;#q=null;#K=null;#X=null;#Y=null;#Q=!1;#J=null;#Z=new sl;#tt=!1;#et=!1;#it=null;#st=null;#nt=null;#at=null;#rt=null;#ot=zr.NONE;#lt=new Set;#ht=null;#ct=null;#dt=null;#ut=null;#pt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#gt=[0,0];#ft=null;#_t=null;#mt=null;#vt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=ll.prototype,e=t=>t.#_t.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},s=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return mo(this,"_keyboardManager",new rl([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["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:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#_t.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#_t.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,i,s,n,a,r,o,l,h,c,d,u,p){const g=this._signal=this.#R.signal;this.#_t=t,this.#mt=e,this.#D=i,this.#ct=s,this._eventBus=n,n._on("editingaction",this.onEditingAction.bind(this),{signal:g}),n._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),n._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),n._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),n._on("setpreference",this.onSetPreference.bind(this),{signal:g}),n._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:g}),this.#bt(),this.#yt(),this.#wt(),this.#I=a.annotationStorage,this.#q=a.filterFactory,this.#dt=r,this.#Y=o||null,this.#$=l,this.#W=h,this.#G=c,this.#rt=d||null,this.viewParameters={realScale:Fo.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=u||null,this._supportsPinchToZoom=!1!==p}destroy(){this.#vt?.resolve(),this.#vt=null,this.#R?.abort(),this.#R=null,this._signal=null;for(const t of this.#L.values())t.destroy();this.#L.clear(),this.#P.clear(),this.#H.clear(),this.#at?.clear(),this.#M=null,this.#lt.clear(),this.#N.destroy(),this.#D?.destroy(),this.#ct?.destroy(),this.#J?.hide(),this.#J=null,this.#nt?.destroy(),this.#nt=null,this.#K&&(clearTimeout(this.#K),this.#K=null),this.#ft&&(clearTimeout(this.#ft),this.#ft=null),this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#rt}get useNewAltTextFlow(){return this.#W}get useNewAltTextWhenAddingImage(){return this.#G}get hcmFilter(){return mo(this,"hcmFilter",this.#dt?this.#q.addHCMFilter(this.#dt.foreground,this.#dt.background):"none")}get direction(){return mo(this,"direction",getComputedStyle(this.#_t).direction)}get highlightColors(){return mo(this,"highlightColors",this.#Y?new Map(this.#Y.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return mo(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#B=t}setMainHighlightColorPicker(t){this.#nt=t}editAltText(t,e=!1){this.#D?.editAltText(this,t,e)}getSignature(t){this.#ct?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#ct}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#G=e}onPageChanging({pageNumber:t}){this.#j=t-1}focusMainContainer(){this.#_t.focus()}findParent(t,e){for(const i of this.#L.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#mt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#H.add(t)}removeShouldRescale(t){this.#H.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Fo.PDF_TO_CSS_UNITS;for(const t of this.#H)t.onScaleChanging();this.#B?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#xt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#At(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#L.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#xt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#At(o),c=this.#ot===zr.NONE,d=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r}),c&&this.showAllEditors("highlight",!0,!0)};c?this.switchToMode(zr.HIGHLIGHT,d):d()}#kt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#xt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#J||=new el(this),this.#J.show(e,i,"ltr"===this.direction))}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#Tt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#ht&&(this.#J?.hide(),this.#ht=null,this.#St({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#ht)return;const i=this.#xt(t).closest(".textLayer");if(i){if(this.#J?.hide(),this.#ht=e,this.#St({hasSelectedText:!0}),(this.#ot===zr.HIGHLIGHT||this.#ot===zr.NONE)&&(this.#ot===zr.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#Q=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#ot===zr.HIGHLIGHT?this.#At(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),n=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#Et("main_toolbar"))};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}}else this.#ht&&(this.#J?.hide(),this.#ht=null,this.#St({hasSelectedText:!1}))}#Et(t=""){this.#ot===zr.HIGHLIGHT?this.highlightSelection(t):this.#$&&this.#kt()}#bt(){document.addEventListener("selectionchange",this.#Tt.bind(this),{signal:this._signal})}#Ct(){if(this.#X)return;this.#X=new AbortController;const t=this.combinedSignal(this.#X);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Rt(){this.#X?.abort(),this.#X=null}blur(){if(this.isShiftKeyDown=!1,this.#Q&&(this.#Q=!1,this.#Et("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#lt)if(e.div.contains(t)){this.#st=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#st)return;const[t,e]=this.#st;this.#st=null,e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal}),e.focus()}#wt(){if(this.#it)return;this.#it=new AbortController;const t=this.combinedSignal(this.#it);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Mt(){this.#it?.abort(),this.#it=null}#Pt(){if(this.#F)return;this.#F=new AbortController;const t=this.combinedSignal(this.#F);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Lt(){this.#F?.abort(),this.#F=null}#yt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#wt(),this.#Pt()}removeEditListeners(){this.#Mt(),this.#Lt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#M?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#lt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#U)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void uo(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#Dt(e);this.#It(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){uo(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#ot===zr.NONE||this.isEditorHandlingKeyboard||ll._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#Q&&(this.#Q=!1,this.#Et("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#St(t){Object.entries(t).some((([t,e])=>this.#pt[t]!==e))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#pt,t)}),this.#ot===zr.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Ot([[Vr.HIGHLIGHT_FREE,!0]]))}#Ot(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Ct(),this.#Pt(),this.#St({isEditing:this.#ot!==zr.NONE,isEmpty:this.#Nt(),hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:this.#N.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Rt(),this.#Lt(),this.#St({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#U){this.#U=t;for(const t of this.#U)this.#Ot(t.defaultPropertiesToUpdate)}}getId(){return this.#Z.id}get currentLayer(){return this.#L.get(this.#j)}getLayer(t){return this.#L.get(t)}get currentPageIndex(){return this.#j}addLayer(t){this.#L.set(t.pageIndex,t),this.#tt?t.enable():t.disable()}removeLayer(t){this.#L.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#ot!==t&&(!this.#vt||(await this.#vt.promise,this.#vt))){if(this.#vt=Promise.withResolvers(),this.#B?.commitOrRemove(),this.#ot=t,t===zr.NONE)return this.setEditingState(!1),this.#Ft(),this._editorUndoBar?.hide(),void this.#vt.resolve();t===zr.SIGNATURE&&await(this.#ct?.loadSignatures()),this.setEditingState(!0),await this.#Bt(),this.unselectAll();for(const e of this.#L.values())e.updateMode(t);if(!e)return i&&this.addNewEditorFromKeyboard(),void this.#vt.resolve();for(const t of this.#P.values())t.annotationElementId===e||t.id===e?(this.setSelected(t),t.enterInEditMode()):t.unselect();this.#vt.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#ot&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#U){switch(t){case Vr.CREATE:return void this.currentLayer.addNewEditor(e);case Vr.HIGHLIGHT_DEFAULT_COLOR:this.#nt?.updateColor(e);break;case Vr.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#ut||=new Map).set(t,e),this.showAllEditors("highlight",e)}for(const i of this.#lt)i.updateParams(t,e);for(const i of this.#U)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#P.values())i.editorType===t&&i.show(e);(this.#ut?.get(Vr.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Ot([[Vr.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#et!==t){this.#et=t;for(const e of this.#L.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Bt(){if(!this.#tt){this.#tt=!0;const t=[];for(const e of this.#L.values())t.push(e.enable());await Promise.all(t);for(const t of this.#P.values())t.enable()}}#Ft(){if(this.unselectAll(),this.#tt){this.#tt=!1;for(const t of this.#L.values())t.disable();for(const t of this.#P.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#P.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#P.get(t)}addEditor(t){this.#P.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#K&&clearTimeout(this.#K),this.#K=setTimeout((()=>{this.focusMainContainer(),this.#K=null}),0)),this.#P.delete(t.id),t.annotationElementId&&this.#at?.delete(t.annotationElementId),this.unselect(t),t.annotationElementId&&this.#z.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#z.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#z.has(t)}removeDeletedAnnotationElement(t){this.#z.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#Dt(t){const e=this.#L.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#M!==t&&(this.#M=t,t&&this.#Ot(t.propertiesToUpdate))}get#jt(){let t=null;for(t of this.#lt);return t}updateUI(t){this.#jt===t&&this.#Ot(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Ot(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#lt.has(t))return this.#lt.delete(t),t.unselect(),void this.#St({hasSelectedEditor:this.hasSelection});this.#lt.add(t),t.select(),this.#Ot(t.propertiesToUpdate),this.#St({hasSelectedEditor:!0})}setSelected(t){this.#B?.commitOrRemove();for(const e of this.#lt)e!==t&&e.unselect();this.#lt.clear(),this.#lt.add(t),t.select(),this.#Ot(t.propertiesToUpdate),this.#St({hasSelectedEditor:!0})}isSelected(t){return this.#lt.has(t)}get firstSelectedEditor(){return this.#lt.values().next().value}unselect(t){t.unselect(),this.#lt.delete(t),this.#St({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#lt.size}get isEnterHandled(){return 1===this.#lt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#N.undo(),this.#St({hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Nt()}),this._editorUndoBar?.hide()}redo(){this.#N.redo(),this.#St({hasSomethingToUndo:!0,hasSomethingToRedo:this.#N.hasSomethingToRedo(),isEmpty:this.#Nt()})}addCommands(t){this.#N.add(t),this.#St({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Nt()})}cleanUndoStack(t){this.#N.cleanType(t)}#Nt(){if(0===this.#P.size)return!0;if(1===this.#P.size)for(const t of this.#P.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#lt],i=()=>{for(const t of e)this.#Dt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo:i,mustExec:!0})}commitOrRemove(){this.#M?.commitOrRemove()}hasSomethingToControl(){return this.#M||this.hasSelection}#It(t){for(const t of this.#lt)t.unselect();this.#lt.clear();for(const e of t)e.isEmpty()||(this.#lt.add(e),e.select());this.#St({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#lt)t.commit();this.#It(this.#P.values())}unselectAll(){if((!this.#M||(this.#M.commitOrRemove(),this.#ot===zr.NONE))&&!this.#B?.commitOrRemove()&&this.hasSelection){for(const t of this.#lt)t.unselect();this.#lt.clear(),this.#St({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#gt[0]+=t,this.#gt[1]+=e;const[s,n]=this.#gt,a=[...this.#lt];this.#ft&&clearTimeout(this.#ft),this.#ft=setTimeout((()=>{this.#ft=null,this.#gt[0]=this.#gt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#P.has(t.id)&&(t.translateInPage(s,n),t.translationDone())},undo:()=>{for(const t of a)this.#P.has(t.id)&&(t.translateInPage(-s,-n),t.translationDone())},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e),i.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#V=new Map;for(const t of this.#lt)this.#V.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#V)return!1;this.disableUserSelect(!1);const t=this.#V;this.#V=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t)a.newX=i,a.newY=s,a.newPageIndex=n,e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex;if(!e)return!1;const i=(t,e,i,s)=>{if(this.#P.has(t.id)){const n=this.#L.get(s);n?t._setParentAndPosition(n,e,i):(t.pageIndex=s,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:s,newY:n,newPageIndex:a}]of t)i(e,s,n,a)},undo:()=>{for(const[e,{savedX:s,savedY:n,savedPageIndex:a}]of t)i(e,s,n,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#V)for(const i of this.#V.keys())i.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.#lt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#M===t}getActive(){return this.#M}getMode(){return this.#ot}get imageManager(){return mo(this,"imageManager",new nl)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i<s;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;const{x:i,y:s,width:n,height:a}=t.getBoundingClientRect();let r;switch(t.getAttribute("data-main-rotation")){case"90":r=(t,e,r,o)=>({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;t<i;t++){const i=e.getRangeAt(t);if(!i.collapsed)for(const{x:t,y:e,width:s,height:n}of i.getClientRects())0!==s&&0!==n&&o.push(r(t,e,s,n))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#O||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#O?.delete(t)}renderAnnotationElement(t){const e=this.#O?.get(t.data.id);if(!e)return;const i=this.#I.getRawValue(e);i&&(this.#ot!==zr.NONE||i.hasBeenModified)&&i.renderAnnotationElement(t)}setMissingCanvas(t,e,i){const s=this.#at?.get(t);s&&(s.setCanvas(e,i),this.#at.delete(t))}addMissingCanvas(t,e){(this.#at||=new Map).set(t,e)}}class hl{#o=null;#zt=!1;#Vt=null;#Ut=null;#Ht=null;#$t=null;#Wt=!1;#Gt=null;#a=null;#qt=null;#Kt=null;#Xt=!1;static#Yt=null;static _l10n=null;constructor(t){this.#a=t,this.#Xt=t._uiManager.useNewAltTextFlow,hl.#Yt||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){hl._l10n??=t}async render(){const t=this.#Vt=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#Ut=document.createElement("span");t.append(e),this.#Xt?(t.classList.add("new"),t.setAttribute("data-l10n-id",hl.#Yt.missing),e.setAttribute("data-l10n-id",hl.#Yt["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const i=this.#a._uiManager._signal;t.addEventListener("contextmenu",Wo,{signal:i}),t.addEventListener("pointerdown",(t=>t.stopPropagation()),{signal:i});const s=t=>{t.preventDefault(),this.#a._uiManager.editAltText(this.#a),this.#Xt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Qt}})};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",(e=>{e.target===t&&"Enter"===e.key&&(this.#Wt=!0,s(e))}),{signal:i}),await this.#Jt(),t}get#Qt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){this.#Vt&&(this.#Vt.focus({focusVisible:this.#Wt}),this.#Wt=!1)}isEmpty(){return this.#Xt?null===this.#o:!this.#o&&!this.#zt}hasData(){return this.#Xt?null!==this.#o||!!this.#qt:this.isEmpty()}get guessedText(){return this.#qt}async setGuessedText(t){null===this.#o&&(this.#qt=t,this.#Kt=await hl._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#Jt())}toggleAltTextBadge(t=!1){if(!this.#Xt||this.#o)return this.#Gt?.remove(),void(this.#Gt=null);if(!this.#Gt){const t=this.#Gt=document.createElement("div");t.className="noAltTextBadge",this.#a.div.append(t)}this.#Gt.classList.toggle("hidden",!t)}serialize(t){let e=this.#o;return t||this.#qt!==e||(e=this.#Kt),{altText:e,decorative:this.#zt,guessedText:this.#qt,textWithDisclaimer:this.#Kt}}get data(){return{altText:this.#o,decorative:this.#zt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){i&&(this.#qt=i,this.#Kt=s),this.#o===t&&this.#zt===e||(n||(this.#o=t,this.#zt=e),this.#Jt())}toggle(t=!1){this.#Vt&&(!t&&this.#$t&&(clearTimeout(this.#$t),this.#$t=null),this.#Vt.disabled=!t)}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Qt}})}destroy(){this.#Vt?.remove(),this.#Vt=null,this.#Ut=null,this.#Ht=null,this.#Gt?.remove(),this.#Gt=null}async#Jt(){const t=this.#Vt;if(!t)return;if(this.#Xt){if(t.classList.toggle("done",!!this.#o),t.setAttribute("data-l10n-id",hl.#Yt[this.#Qt]),this.#Ut?.setAttribute("data-l10n-id",hl.#Yt[`${this.#Qt}-label`]),!this.#o)return void this.#Ht?.remove()}else{if(!this.#o&&!this.#zt)return t.classList.remove("done"),void this.#Ht?.remove();t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#Ht;if(!e){this.#Ht=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#$t),this.#$t=null}),{once:!0}),t.addEventListener("mouseenter",(()=>{this.#$t=setTimeout((()=>{this.#$t=null,this.#Ht.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s}),t.addEventListener("mouseleave",(()=>{this.#$t&&(clearTimeout(this.#$t),this.#$t=null),this.#Ht?.classList.remove("show")}),{signal:s})}this.#zt?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#o),e.parentNode||t.append(e);const i=this.#a.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class cl{#_t;#Zt=!1;#te=null;#ee;#ie;#se;#ne;#ae=null;#re;#oe=null;#le;#he=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#_t=t,this.#te=i,this.#ee=e,this.#ie=s,this.#se=n,this.#ne=a,this.#le=new AbortController,this.#re=AbortSignal.any([r,this.#le.signal]),t.addEventListener("touchstart",this.#ce.bind(this),{passive:!1,signal:this.#re})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Jo.pixelRatio}#ce(t){if(this.#ee?.())return;if(1===t.touches.length){if(this.#ae)return;const t=this.#ae=new AbortController,e=AbortSignal.any([this.#re,t.signal]),i=this.#_t,s={capture:!0,signal:e,passive:!1},n=t=>{"touch"===t.pointerType&&(this.#ae?.abort(),this.#ae=null)};return i.addEventListener("pointerdown",(t=>{"touch"===t.pointerType&&(Go(t),n(t))}),s),i.addEventListener("pointerup",n,s),void i.addEventListener("pointercancel",n,s)}if(!this.#he){this.#he=new AbortController;const t=AbortSignal.any([this.#re,this.#he.signal]),e=this.#_t,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#de.bind(this),i);const s=this.#ue.bind(this);e.addEventListener("touchend",s,i),e.addEventListener("touchcancel",s,i),i.capture=!0,e.addEventListener("pointerdown",Go,i),e.addEventListener("pointermove",Go,i),e.addEventListener("pointercancel",Go,i),e.addEventListener("pointerup",Go,i),this.#ie?.()}if(Go(t),2!==t.touches.length||this.#te?.())return void(this.#oe=null);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]),this.#oe={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#de(t){if(!this.#oe||2!==t.touches.length)return;Go(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:a,screenY:r}=i,o=this.#oe,{touch0X:l,touch0Y:h,touch1X:c,touch1Y:d}=o,u=c-l,p=d-h,g=a-s,f=r-n,_=Math.hypot(g,f)||1,m=Math.hypot(u,p)||1;if(!this.#Zt&&Math.abs(m-_)<=cl.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(o.touch0X=s,o.touch0Y=n,o.touch1X=a,o.touch1Y=r,!this.#Zt)return void(this.#Zt=!0);const v=[(s+a)/2,(n+r)/2];this.#se?.(v,m,_)}#ue(t){t.touches.length>=2||(this.#he&&(this.#he.abort(),this.#he=null,this.#ne?.()),this.#oe&&(Go(t),this.#oe=null,this.#Zt=!1))}destroy(){this.#le?.abort(),this.#le=null,this.#ae?.abort(),this.#ae=null}}class dl{#pe=null;#ge=null;#o=null;#fe=!1;#_e=null;#me="";#ve=!1;#be=null;#ye=null;#we=null;#xe=null;#Ae="";#ke=!1;#Te=null;#Se=!1;#Ee=!1;#Ce=!1;#Re=null;#Me=0;#Pe=0;#Le=null;#De=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#Ie=!1;#Oe=dl._zIndex++;static _borderLineWidth=-1;static _colorManager=new ol;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=dl.prototype._resizeWithKeyboard,e=ll.TRANSLATE_SMALL,i=ll.TRANSLATE_BIG;return mo(this,"_resizerKeyboardManager",new rl([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],dl.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,s],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 isDrawer(){return!1}static get _defaultLineColor(){return mo(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new ul({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(dl._l10n??=t,dl._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),-1!==dl._borderLineWidth)return;const i=getComputedStyle(document.documentElement);dl._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){po("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#Ie}set _isDraggable(t){this.#Ie=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.#Oe}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#Ne(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ke?this.#ke=!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,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s),this.x=(t+i)/n,this.y=(e+s)/a,this.fixAndSetPosition()}_moveAfterPaste(t,e){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s),this._onTranslated()}#Fe([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s),this.x+=i/t,this.y+=s/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#Fe(this.parentDimensions,t,e)}translateInPage(t,e){this.#Te||=[this.x,this.y,this.width,this.height],this.#Fe(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Te||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;if(this.x+=t/s,this.y+=e/n,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:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o,r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`,h.top=`${(100*r).toFixed(2)}%`,this._onTranslating(a,r),i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Te&&(this.#Te[0]!==this.x||this.#Te[1]!==this.y)}get _hasBeenResized(){return!!this.#Te&&(this.#Te[2]!==this.width||this.#Te[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=dl,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:a,width:r,height:o}=this;if(r*=i,o*=s,n*=i,a*=s,this._mustFixPosition)switch(t){case 0:n=Io(n,0,i-r),a=Io(a,0,s-o);break;case 90:n=Io(n,0,i-o),a=Io(a,r,s);break;case 180:n=Io(n,r,i),a=Io(a,o,s);break;case 270:n=Io(n,o,i),a=Io(a,0,s-r)}this.x=n/=i,this.y=a/=s;const[l,h]=this.getBaseTranslation();n+=l,a+=h,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#Be(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return dl.#Be(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return dl.#Be(t,e,360-this.parentRotation)}#je(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/i).toFixed(2)}%`,this.#ve||(n.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#ve&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`),this.#ve||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#ze(){if(this.#be)return;this.#be=document.createElement("div"),this.#be.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#be.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#Ve.bind(this,i),{signal:e}),t.addEventListener("contextmenu",Wo,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#be)}#Ve(t,e){e.preventDefault();const{isMac:i}=Eo.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1,this.#ye=[e.screenX,e.screenY];const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#Ue.bind(this,t),{passive:!0,capture:!0,signal:a}),window.addEventListener("touchmove",Go,{passive:!1,signal:a}),window.addEventListener("contextmenu",Wo,{signal:a}),this.#we={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#o?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=r,this.div.style.cursor=o,this.#He()};window.addEventListener("pointerup",l,{signal:a}),window.addEventListener("blur",l,{signal:a})}#$e(t,e,i,s){this.width=i,this.height=s,this.x=t,this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s),this.fixAndSetPosition(),this._onResized()}_onResized(){}#He(){if(!this.#we)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#we;this.#we=null;const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:this.#$e.bind(this,n,a,r,o),undo:this.#$e.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Ue(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=dl.MIN_SIZE/i,h=dl.MIN_SIZE/s,c=this.#je(this.rotation),d=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],u=this.#je(360-this.rotation);let p,g,f=!1,_=!1;switch(t){case"topLeft":f=!0,p=(t,e)=>[0,0],g=(t,e)=>[t,e];break;case"topMiddle":p=(t,e)=>[t/2,0],g=(t,e)=>[t/2,e];break;case"topRight":f=!0,p=(t,e)=>[t,0],g=(t,e)=>[0,e];break;case"middleRight":_=!0,p=(t,e)=>[t,e/2],g=(t,e)=>[0,e/2];break;case"bottomRight":f=!0,p=(t,e)=>[t,e],g=(t,e)=>[0,0];break;case"bottomMiddle":p=(t,e)=>[t/2,e],g=(t,e)=>[t/2,0];break;case"bottomLeft":f=!0,p=(t,e)=>[0,e],g=(t,e)=>[t,0];break;case"middleLeft":_=!0,p=(t,e)=>[0,e/2],g=(t,e)=>[t,e/2]}const m=p(r,o),v=g(r,o);let b=d(...v);const y=dl._round(n+b[0]),w=dl._round(a+b[1]);let x,A,k=1,T=1;if(e.fromKeyboard)({deltaX:x,deltaY:A}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#ye;[x,A]=this.screenToPageTranslation(t-s,i-n),this.#ye[0]=t,this.#ye[1]=i}if([x,A]=((t,e)=>[u[0]*t+u[2]*e,u[1]*t+u[3]*e])(x/i,A/s),f){const t=Math.hypot(r,o);k=T=Math.max(Math.min(Math.hypot(v[0]-m[0]-x,v[1]-m[1]-A)/t,1/r,1/o),l/r,h/o)}else _?k=Io(Math.abs(v[0]-m[0]-x),l,1)/r:T=Io(Math.abs(v[1]-m[1]-A),h,1)/o;const S=dl._round(r*k),E=dl._round(o*T);b=d(...g(S,E));const C=y-b[0],R=w-b[1];this.#Te||=[this.x,this.y,this.width,this.height],this.width=S,this.height=E,this.x=C,this.y=R,this.setDims(i*S,s*E),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){return this._editToolbar||this.#Ee||(this._editToolbar=new tl(this),this.div.append(this._editToolbar.render()),this.#o&&await this._editToolbar.addAltText(this.#o)),this._editToolbar}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#o?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#o||(hl.initialize(dl._l10n),this.#o=new hl(this),this.#pe&&(this.#o.data=this.#pe,this.#pe=null),await this.addEditToolbar())}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#fe?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#We();const[e,i]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*i/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/i).toFixed(2)}%`);const[s,n]=this.getInitialTranslation();return this.translate(s,n),il(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#De||=new cl({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ge.bind(this),onPinching:this.#qe.bind(this),onPinchEnd:this.#Ke.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),t}#Ge(){this.#we={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#o?.toggle(!1),this.parent.togglePointerEvents(!1)}#qe(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#je(this.rotation),a=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[r,o]=this.parentDimensions,l=this.x,h=this.y,c=this.width,d=this.height,u=dl.MIN_SIZE/r,p=dl.MIN_SIZE/o;s=Math.max(Math.min(s,1/c,1/d),u/c,p/d);const g=dl._round(c*s),f=dl._round(d*s);if(g===c&&f===d)return;this.#Te||=[l,h,c,d];const _=a(c/2,d/2),m=dl._round(l+_[0]),v=dl._round(h+_[1]),b=a(g/2,f/2);this.x=m-b[0],this.y=v-b[1],this.width=g,this.height=f,this.setDims(r*g,o*f),this.fixAndSetPosition(),this._onResizing()}#Ke(){this.#o?.toggle(!0),this.parent.togglePointerEvents(!0),this.#He()}pointerdown(t){const{isMac:e}=Eo.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#ke=!0,this._isDraggable?this.#Xe(t):this.#Ye(t))}#Ye(t){const{isMac:e}=Eo.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#Xe(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),a={capture:!0,passive:!1,signal:n},r=t=>{s.abort(),this.#_e=null,this.#ke=!1,this._uiManager.endDragSession()||this.#Ye(t),i&&this._onStopDragging()};e&&(this.#Me=t.clientX,this.#Pe=t.clientY,this.#_e=t.pointerId,this.#me=t.pointerType,window.addEventListener("pointermove",(t=>{i||(i=!0,this._onStartDragging());const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#_e)return void Go(t);const[a,r]=this.screenToPageTranslation(e-this.#Me,s-this.#Pe);this.#Me=e,this.#Pe=s,this._uiManager.dragSelectedEditors(a,r)}),a),window.addEventListener("touchmove",Go,a),window.addEventListener("pointerdown",(t=>{t.pointerType===this.#me&&(this.#De||t.isPrimary)&&r(t),Go(t)}),a));const o=t=>{this.#_e&&this.#_e!==t.pointerId?Go(t):r(t)};window.addEventListener("pointerup",o,{signal:n}),window.addEventListener("blur",o,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Re&&clearTimeout(this.#Re),this.#Re=setTimeout((()=>{this.#Re=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,c=this.x*n,d=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[c+l+r,a-d-h-p+o,c+l+u+r,a-d-h+o];case 90:return[c+h+r,a-d+l+o,c+h+p+r,a-d+l+u+o];case 180:return[c-l-u+r,a-d+h+o,c-l+r,a-d+h+p+o];case 270:return[c-h-p+r,a-d-l-u+o,c-h+r,a-d-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#Ee=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#Ee=!1,!0)}isInEditMode(){return this.#Ee}shouldGetKeyboardEvents(){return this.#Ce}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:a}=window;return e<a&&s>0&&t<n&&i>0}#We(){if(this.#xe||!this.div)return;this.#xe=new AbortController;const t=this._uiManager.combinedSignal(this.#xe);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#We()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){po("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation,s.#pe=t.accessibilityData,s._isCopy=t.isCopy||!1;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);return s.x=r/n,s.y=o/a,s.width=l/n,s.height=h/a,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#xe?.abort(),this.#xe=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#Re&&(clearTimeout(this.#Re),this.#Re=null),this.#Ne(),this.removeEditToolbar(),this.#Le){for(const t of this.#Le.values())clearTimeout(t);this.#Le=null}this.parent=null,this.#De?.destroy(),this.#De=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#ze(),this.#be.classList.remove("hidden"))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#we={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#be.children;if(!this.#ge){this.#ge=Array.from(e);const t=this.#Qe.bind(this),i=this.#Je.bind(this),s=this._uiManager._signal;for(const e of this.#ge){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:s}),e.addEventListener("blur",i,{signal:s}),e.addEventListener("focus",this.#Ze.bind(this,n),{signal:s}),e.setAttribute("data-l10n-id",dl._l10nResizer[n])}}const i=this.#ge[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#ge.length/4);if(n!==s){if(n<s)for(let t=0;t<s-n;t++)this.#be.append(this.#be.firstChild);else if(n>s)for(let t=0;t<n-s;t++)this.#be.firstChild.before(this.#be.lastChild);let t=0;for(const i of e){const e=this.#ge[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",dl._l10nResizer[e])}}this.#ti(0),this.#Ce=!0,this.#be.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#Qe(t){dl._resizerKeyboardManager.exec(this,t)}#Je(t){this.#Ce&&t.relatedTarget?.parentNode!==this.#be&&this.#Ne()}#Ze(t){this.#Ae=this.#Ce?t:""}#ti(t){if(this.#ge)for(const e of this.#ge)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#Ce&&this.#Ue(this.#Ae,{deltaX:t,deltaY:e,fromKeyboard:!0})}#Ne(){this.#Ce=!1,this.#ti(-1),this.#He()}_stopResizingWithKeyboard(){this.#Ne(),this.div.focus()}select(){this.isSelected&&this._editToolbar||(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),this._editToolbar?(this._editToolbar?.show(),this.#o?.toggleAltTextBadge(!1)):this.addEditToolbar().then((()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()})))}unselect(){this.isSelected&&(this.isSelected=!1,this.#be?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#o?.toggleAltTextBadge(!0))}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.id})}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#Se}set isEditing(t){this.#Se=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#ve=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i,s.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.#Le||=new Map;const{action:e}=t;let i=this.#Le.get(e);return i&&clearTimeout(i),i=setTimeout((()=>{this._reportTelemetry(t),this.#Le.delete(e),0===this.#Le.size&&(this.#Le=null)}),dl._telemetryTimeout),void this.#Le.set(e,i)}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.#fe=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#fe=!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 ul extends dl{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const pl=3285377520,gl=4294901760,fl=65535;class _l{constructor(t){this.h1=t?4294967295&t:pl,this.h2=t?4294967295&t:pl}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let s=0,n=t.length;s<n;s++){const n=t.charCodeAt(s);n<=255?e[i++]=n:(e[i++]=n>>>8,e[i++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let t=0;t<s;t++)1&t?(r=a[t],r=r*c&gl|r*u&fl,r=r<<15|r>>>17,r=r*d&gl|r*p&fl,l^=r,l=l<<13|l>>>19,l=5*l+3864292196):(o=a[t],o=o*c&gl|o*u&fl,o=o<<15|o>>>17,o=o*d&gl|o*p&fl,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(r=0,n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s],r=r*c&gl|r*u&fl,r=r<<15|r>>>17,r=r*d&gl|r*p&fl,1&s?l^=r:h^=r}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&gl|36045*t&fl,e=4283543511*e&gl|(2950163797*(e<<16|t>>>16)&gl)>>>16,t^=e>>>1,t=444984403*t&gl|60499*t&fl,e=3301882366*e&gl|(3120437893*(e<<16|t>>>16)&gl)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const ml=Object.freeze({map:null,hash:"",transfer:void 0});class vl{#ei=!1;#ii=null;#si=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const i=this.#si.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#si.get(t)}remove(t){if(this.#si.delete(t),0===this.#si.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor){for(const t of this.#si.values())if(t instanceof dl)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#si.get(t);let s=!1;if(void 0!==i)for(const[t,n]of Object.entries(e))i[t]!==n&&(s=!0,i[t]=n);else s=!0,this.#si.set(t,e);s&&this.#ni(),e instanceof dl&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#si.has(t)}get size(){return this.#si.size}#ni(){this.#ei||(this.#ei=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#ei&&(this.#ei=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new bl(this)}get serializable(){if(0===this.#si.size)return ml;const t=new Map,e=new _l,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#si){const r=a instanceof dl?a.serialize(!1,s):a;r&&(t.set(i,r),e.update(`${i}:${JSON.stringify(r)}`),n||=!!r.bitmap)}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:ml}get editorStats(){let t=null;const e=new Map;for(const i of this.#si.values()){if(!(i instanceof dl))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor),t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);i||(i=new Map,a.set(t,i));const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#ii=null}get modifiedIds(){if(this.#ii)return this.#ii;const t=[];for(const e of this.#si.values())e instanceof dl&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#ii={ids:new Set(t),hash:t.join(",")}}[Symbol.iterator](){return this.#si.entries()}}class bl extends vl{#ai;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#ai={map:n,hash:i,transfer:s}}get print(){po("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ai}get modifiedIds(){return mo(this,"modifiedIds",{ids:new Set,hash:""})}}class yl{#ri=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.#ri.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#ri.has(t.loadedName))if(go(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:e,src:s,style:n}=t,a=new FontFace(e,s,n);this.addNativeFontFace(a);try{await a.load(),this.#ri.add(e),i?.(t)}catch{uo(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}}else po("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(i){throw uo(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return mo(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return mo(this,"isSyncFontLoadingSupported",Cr||Eo.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(go(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return mo(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function s(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=s(c,976,h.length,h);const d=1482184792;let u=i(c,16);for(n=0,a=h.length-3;n<a;n+=4)u=u-d+i(h,n)|0;var p;n<h.length&&(u=u-d+i(h+"XXX",n)|0),c=s(c,16,4,(p=u,String.fromCharCode(p>>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${h}";src:${`url(data:font/opentype;base64,${btoa(c)});`}}`;this.insertRule(g);const f=this._document.createElement("div");f.style.visibility="hidden",f.style.width=f.style.height="10px",f.style.position="absolute",f.style.top=f.style.left="0px";for(const e of[t.loadedName,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,f.append(t)}this._document.body.append(f),function t(e,i){if(++l>30)return uo("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,(()=>{f.remove(),e.complete()}))}}class wl{constructor(t,e=null){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this._inspectFont=e}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=`url(data:${this.mimetype};base64,${Oo(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){uo(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");return this.fontExtraProperties||t.delete(i),this.compiledGlyphs[e]=n}}function xl(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const Al=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,kl=function(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[s,n,...a]=i;if(!t(s)&&!Number.isInteger(s))return!1;if(!e(n))return!1;const r=a.length;let o=!0;switch(n.name){case"XYZ":if(r<2||r>3)return!1;break;case"Fit":case"FitB":return 0===r;case"FitH":case"FitBH":case"FitV":case"FitBV":if(r>1)return!1;break;case"FitR":if(4!==r)return!1;o=!1;break;default:return!1}for(const t of a)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,Al,(t=>"object"==typeof t&&"string"==typeof t?.name));class Tl{#oi=new Map;#li=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#li.then((()=>{for(const[t]of this.#oi)t.call(this,i)}))}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted)return void uo("LoopbackPort - cannot use an `aborted` signal.");const a=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",a),n.addEventListener("abort",a)}this.#oi.set(e,s)}removeEventListener(t,e){const i=this.#oi.get(e);i?.(),this.#oi.delete(e)}terminate(){for(const[,t]of this.#oi)t?.();this.#oi.clear()}}const Sl=1,El=2,Cl=1,Rl=2,Ml=3,Pl=4,Ll=5,Dl=6,Il=7,Ol=8;function Nl(){}function Fl(t){if(t instanceof ko||t instanceof wo||t instanceof bo||t instanceof xo||t instanceof yo)return t;switch(t instanceof Error||"object"==typeof t&&null!==t||po('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new ko(t.message);case"InvalidPDFException":return new wo(t.message);case"PasswordException":return new bo(t.message,t.code);case"ResponseException":return new xo(t.message,t.status,t.missing);case"UnknownErrorException":return new yo(t.message,t.details)}return new yo(t.message,t.toString())}class Bl{#hi=new AbortController;constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),i.addEventListener("message",this.#ci.bind(this),{signal:this.#hi.signal})}#ci({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#di(t);if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===Sl)i.resolve(t.data);else{if(t.callback!==El)throw new Error("Unexpected callback case");i.reject(Fl(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:i,targetName:s,callback:Sl,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:i,targetName:s,callback:El,callbackId:t.callbackId,reason:Fl(e)})}))}else t.streamId?this.#ui(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:Dl,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{go(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:Cl,streamId:n,reason:Fl(t)}),e.promise}},i)}#ui(t){const e=t.streamId,i=this.sourceName,s=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:i,targetName:s,stream:Pl,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:Ml,streamId:e}),delete a.streamSinks[e])},error(t){go(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:Ll,streamId:e,reason:Fl(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,Promise.try(r,t.data,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:Ol,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:Ol,streamId:e,reason:Fl(t)})}))}#di(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case Ol:t.success?a.startCall.resolve():a.startCall.reject(Fl(t.reason));break;case Il:t.success?a.pullCall.resolve():a.pullCall.reject(Fl(t.reason));break;case Dl:if(!r){n.postMessage({sourceName:i,targetName:s,stream:Il,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,Promise.try(r.onPull||Nl).then((function(){n.postMessage({sourceName:i,targetName:s,stream:Il,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:Il,streamId:e,reason:Fl(t)})}));break;case Pl:if(go(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case Ml:if(go(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#pi(a,e);break;case Ll:go(a,"error should have stream controller"),a.controller.error(Fl(t.reason)),this.#pi(a,e);break;case Rl:t.success?a.cancelCall.resolve():a.cancelCall.reject(Fl(t.reason)),this.#pi(a,e);break;case Cl:if(!r)break;const o=Fl(t.reason);Promise.try(r.onCancel||Nl,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:Rl,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:Rl,streamId:e,reason:Fl(t)})})),r.sinkCapability.reject(o),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#pi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#hi?.abort(),this.#hi=null}}class jl{#gi=!1;constructor({enableHWA:t=!1}){this.#gi=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#gi})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){po("Abstract method `_createCanvas` called.")}}class zl extends jl{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}}class Vl{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){po("Abstract method `_fetch` called.")}}class Ul extends Vl{async _fetch(t){const e=await Bo(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):So(e)}}class Hl{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class $l extends Hl{#fi;#_i;#mi;#vi;#bi;#yi;#y=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#vi=t,this.#bi=e}get#x(){return this.#_i||=new Map}get#wi(){return this.#yi||=new Map}get#xi(){if(!this.#mi){const t=this.#bi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#bi.createElementNS(No,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#mi=this.#bi.createElementNS(No,"defs"),t.append(i),i.append(this.#mi),this.#bi.body.append(t)}return this.#mi}#Ai(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++)n[t]=e[t]/255,a[t]=i[t]/255,r[t]=s[t]/255;return[n.join(","),a.join(","),r.join(",")]}#ki(t){if(void 0===this.#fi){this.#fi="";const t=this.#bi.URL;t!==this.#bi.baseURI&&(Vo(t)?uo('#createUrl: ignore "data:"-URL for performance reasons.'):this.#fi=_o(t,""))}return`url(${this.#fi}#${t})`}addFilter(t){if(!t)return"none";let e=this.#x.get(t);if(e)return e;const[i,s,n]=this.#Ai(t),a=1===t.length?i:`${i}${s}${n}`;if(e=this.#x.get(a),e)return this.#x.set(t,e),e;const r=`g_${this.#vi}_transfer_map_${this.#y++}`,o=this.#ki(r);this.#x.set(t,o),this.#x.set(a,o);const l=this.#Ti(r);return this.#Si(i,s,n,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#wi.get(s);if(n?.key===i)return n.url;if(n?(n.filter?.remove(),n.key=i,n.url="none",n.filter=null):(n={key:i,url:"none",filter:null},this.#wi.set(s,n)),!t||!e)return n.url;const a=this.#Ei(t);t=Ro.makeHexColor(...a);const r=this.#Ei(e);if(e=Ro.makeHexColor(...r),this.#xi.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 l=o.join(","),h=`g_${this.#vi}_hcm_filter`,c=n.filter=this.#Ti(h);this.#Si(l,l,l,c),this.#Ci(c);const d=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};return this.#Si(d(0,5),d(1,5),d(2,5),c),n.url=this.#ki(h),n.url}addAlphaFilter(t){let e=this.#x.get(t);if(e)return e;const[i]=this.#Ai([t]),s=`alpha_${i}`;if(e=this.#x.get(s),e)return this.#x.set(t,e),e;const n=`g_${this.#vi}_alpha_map_${this.#y++}`,a=this.#ki(n);this.#x.set(t,a),this.#x.set(s,a);const r=this.#Ti(n);return this.#Ri(i,r),a}addLuminosityFilter(t){let e,i,s=this.#x.get(t||"luminosity");if(s)return s;if(t?([e]=this.#Ai([t]),i=`luminosity_${e}`):i="luminosity",s=this.#x.get(i),s)return this.#x.set(t,s),s;const n=`g_${this.#vi}_luminosity_map_${this.#y++}`,a=this.#ki(n);this.#x.set(t,a),this.#x.set(i,a);const r=this.#Ti(n);return this.#Mi(r),t&&this.#Ri(e,r),a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#wi.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.#wi.set(t,r)),!e||!i)return r.url;const[o,l]=[e,i].map(this.#Ei.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,u]=[s,n].map(this.#Ei.bind(this));c<h&&([h,c,d,u]=[c,h,u,d]),this.#xi.style.color="";const p=(t,e,i)=>{const s=new Array(256),n=(c-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},g=`g_${this.#vi}_hcm_${t}_filter`,f=r.filter=this.#Ti(g);return this.#Ci(f),this.#Si(p(d[0],u[0],5),p(d[1],u[1],5),p(d[2],u[2],5),f),r.url=this.#ki(g),r.url}destroy(t=!1){t&&this.#yi?.size||(this.#mi?.parentNode.parentNode.remove(),this.#mi=null,this.#_i?.clear(),this.#_i=null,this.#yi?.clear(),this.#yi=null,this.#y=0)}#Mi(t){const e=this.#bi.createElementNS(No,"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)}#Ci(t){const e=this.#bi.createElementNS(No,"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)}#Ti(t){const e=this.#bi.createElementNS(No,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#xi.append(e),e}#Pi(t,e,i){const s=this.#bi.createElementNS(No,e);s.setAttribute("type","discrete"),s.setAttribute("tableValues",i),t.append(s)}#Si(t,e,i,s){const n=this.#bi.createElementNS(No,"feComponentTransfer");s.append(n),this.#Pi(n,"feFuncR",t),this.#Pi(n,"feFuncG",e),this.#Pi(n,"feFuncB",i)}#Ri(t,e){const i=this.#bi.createElementNS(No,"feComponentTransfer");e.append(i),this.#Pi(i,"feFuncA",t)}#Ei(t){return this.#xi.style.color=t,Ko(getComputedStyle(this.#xi).getPropertyValue("color"))}}class Wl{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){po("Abstract method `_fetch` called.")}}class Gl extends Wl{async _fetch(t){const e=await Bo(t,"arraybuffer");return new Uint8Array(e)}}class ql{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!t)throw new Error("Wasm filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load wasm data at: ${e}`)}))}async _fetch(t){po("Abstract method `_fetch` called.")}}class Kl extends ql{async _fetch(t){const e=await Bo(t,"arraybuffer");return new Uint8Array(e)}}async function Xl(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}Cr&&uo("Please use the `legacy` build in Node.js environments.");class Yl extends Hl{}class Ql extends jl{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class Jl extends Vl{async _fetch(t){return Xl(t)}}class Zl extends Wl{async _fetch(t){return Xl(t)}}class th extends ql{async _fetch(t){return Xl(t)}}const eh="Fill",ih="Stroke",sh="Shading";function nh(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s),t.clip(n)}class ah{isModifyingCurrentTransform(){return!1}getPattern(){po("Abstract method `getPattern` called.")}}class rh extends ah{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,i,s){let n;if(s===ih||s===eh){const a=e.current.getClippedPathBoundingBox(s,Xo(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-a[0],-a[1]),i=Ro.transform(i,[1,0,0,1,a[0],a[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),nh(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),n=t.createPattern(l.canvas,"no-repeat");const c=new DOMMatrix(i);n.setTransform(c)}else nh(t,this._bbox),n=this._createGradient(t);return n}}function oh(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,c=t.data,d=4*t.width;let u;l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u),l[s+1]>l[n+1]&&(u=s,s=n,n=u,u=r,r=o,o=u),l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u);const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,f=(l[s]+e.offsetX)*e.scaleX,_=(l[s+1]+e.offsetY)*e.scaleY,m=(l[n]+e.offsetX)*e.scaleX,v=(l[n+1]+e.offsetY)*e.scaleY;if(g>=v)return;const b=h[a],y=h[a+1],w=h[a+2],x=h[r],A=h[r+1],k=h[r+2],T=h[o],S=h[o+1],E=h[o+2],C=Math.round(g),R=Math.round(v);let M,P,L,D,I,O,N,F;for(let t=C;t<=R;t++){if(t<_){const e=t<g?0:(g-t)/(g-_);M=p-(p-f)*e,P=b-(b-x)*e,L=y-(y-A)*e,D=w-(w-k)*e}else{let e;e=t>v?1:_===v?0:(_-t)/(_-v),M=f-(f-m)*e,P=x-(x-T)*e,L=A-(A-S)*e,D=k-(k-E)*e}let e;e=t<g?0:t>v?1:(g-t)/(g-v),I=p-(p-m)*e,O=b-(b-T)*e,N=y-(y-S)*e,F=w-(w-E)*e;const i=Math.round(Math.min(M,I)),s=Math.round(Math.max(M,I));let n=d*t+4*i;for(let t=i;t<=s;t++)e=(M-t)/(M-I),e<0?e=0:e>1&&(e=1),c[n++]=P-(P-O)*e|0,c[n++]=L-(L-N)*e|0,c[n++]=D-(D-F)*e|0,c[n++]=255}}function lh(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a<l;a++){let e=a*o;for(let a=0;a<h;a++,e++)oh(t,i,s[e],s[e+1],s[e+o],n[e],n[e+1],n[e+o]),oh(t,i,s[e+o+1],s[e+1],s[e+o],n[e+o+1],n[e+1],n[e+o])}break;case"triangles":for(a=0,r=s.length;a<r;a+=3)oh(t,i,s[a],s[a+1],s[a+2],n[a],n[a+1],n[a+2]);break;default:throw new Error("illegal figure")}}class hh extends ah{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null}_createMeshCanvas(t,e,i){const s=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),a=Math.ceil(this._bounds[2])-s,r=Math.ceil(this._bounds[3])-n,o=Math.min(Math.ceil(Math.abs(a*t[0]*1.1)),3e3),l=Math.min(Math.ceil(Math.abs(r*t[1]*1.1)),3e3),h=a/o,c=r/l,d={coords:this._coords,colors:this._colors,offsetX:-s,offsetY:-n,scaleX:1/h,scaleY:1/c},u=o+4,p=l+4,g=i.getCanvas("mesh",u,p),f=g.context,_=f.createImageData(o,l);if(e){const t=_.data;for(let i=0,s=t.length;i<s;i+=4)t[i]=e[0],t[i+1]=e[1],t[i+2]=e[2],t[i+3]=255}for(const t of this._figures)lh(_,t,d);f.putImageData(_,2,2);return{canvas:g.canvas,offsetX:s-2*h,offsetY:n-2*c,scaleX:h,scaleY:c}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,s){nh(t,this._bbox);const n=new Float32Array(2);if(s===sh)Ro.singularValueDecompose2dScale(Xo(t),n);else if(this.matrix){Ro.singularValueDecompose2dScale(this.matrix,n);const[t,i]=n;Ro.singularValueDecompose2dScale(e.baseTransform,n),n[0]*=t,n[1]*=i}else Ro.singularValueDecompose2dScale(e.baseTransform,n);const a=this._createMeshCanvas(n,s===sh?null:this._background,e.cachedCanvases);return s!==sh&&(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 ch extends ah{getPattern(){return"hotpink"}}const dh=1,uh=2;class ph{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,s){this.color=t[1],this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.ctx=e,this.canvasGraphicsFactory=i,this.baseTransform=s}createPatternCanvas(t){const{bbox:e,operatorList:i,paintType:s,tilingType:n,color:a,canvasGraphicsFactory:r}=this;let{xstep:o,ystep:l}=this;o=Math.abs(o),l=Math.abs(l),co("TilingType: "+n);const h=e[0],c=e[1],d=e[2],u=e[3],p=d-h,g=u-c,f=new Float32Array(2);Ro.singularValueDecompose2dScale(this.matrix,f);const[_,m]=f;Ro.singularValueDecompose2dScale(this.baseTransform,f);const v=_*f[0],b=m*f[1];let y=p,w=g,x=!1,A=!1;const k=Math.ceil(o*v),T=Math.ceil(l*b);k>=Math.ceil(p*v)?y=o:x=!0,T>=Math.ceil(g*b)?w=l:A=!0;const S=this.getSizeAndScale(y,this.ctx.canvas.width,v),E=this.getSizeAndScale(w,this.ctx.canvas.height,b),C=t.cachedCanvases.getCanvas("pattern",S.size,E.size),R=C.context,M=r.createCanvasGraphics(R);if(M.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(M,s,a),R.translate(-S.scale*h,-E.scale*c),M.transform(S.scale,0,0,E.scale,0,0),R.save(),this.clipBbox(M,h,c,d,u),M.baseTransform=Xo(M.ctx),M.executeOperatorList(i),M.endDrawing(),R.restore(),x||A){const e=C.canvas;x&&(y=o),A&&(w=l);const i=this.getSizeAndScale(y,this.ctx.canvas.width,v),s=this.getSizeAndScale(w,this.ctx.canvas.height,b),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),d=r.context,u=x?Math.floor(p/o):0,f=A?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=f;i++)d.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:c}}return{canvas:C.canvas,scaleX:S.scale,scaleY:E.scale,offsetX:h,offsetY:c}}getSizeAndScale(t,e,i){const s=Math.max(ph.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);return n>=s?n=s:i=n/t,{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r),Ro.axialAlignedBoundingBox([e,i,s,n],Xo(t.ctx),t.current.minMax),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case dh:const{fillStyle:t,strokeStyle:a}=this.ctx;s.fillStyle=n.fillColor=t,s.strokeStyle=n.strokeColor=a;break;case uh:s.fillStyle=s.strokeStyle=i,n.fillColor=n.strokeColor=i;break;default:throw new Ao(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,s){let n=i;s!==sh&&(n=Ro.transform(n,e.baseTransform),this.matrix&&(n=Ro.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 gh({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=Eo.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],c=s>>3,d=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s<n;s++){for(const s=e+c;e<s;e++){const s=e<u?t[e]:255;i[p++]=128&s?h:l,i[p++]=64&s?h:l,i[p++]=32&s?h:l,i[p++]=16&s?h:l,i[p++]=8&s?h:l,i[p++]=4&s?h:l,i[p++]=2&s?h:l,i[p++]=1&s?h:l}if(0===d)continue;const s=e<u?t[e++]:255;for(let t=0;t<d;t++)i[p++]=s&1<<7-t?h:l}return{srcPos:e,destPos:p}}const fh=16,_h=new DOMMatrix,mh=new Float32Array(2),vh=new Float32Array([1/0,1/0,-1/0,-1/0]);class bh{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,i){let s;return void 0!==this.cache[t]?(s=this.cache[t],this.canvasFactory.reset(s,e,i)):(s=this.canvasFactory.create(e,i),this.cache[t]=s),s}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 yh(t,e,i,s,n,a,r,o,l,h){const[c,d,u,p,g,f]=Xo(t);if(0===d&&0===u){const _=r*c+g,m=Math.round(_),v=o*p+f,b=Math.round(v),y=(r+l)*c+g,w=Math.abs(Math.round(y)-m)||1,x=(o+h)*p+f,A=Math.abs(Math.round(x)-b)||1;return t.setTransform(Math.sign(c),0,0,Math.sign(p),m,b),t.drawImage(e,i,s,n,a,0,0,w,A),t.setTransform(c,d,u,p,g,f),[w,A]}if(0===c&&0===p){const _=o*u+g,m=Math.round(_),v=r*d+f,b=Math.round(v),y=(o+h)*u+g,w=Math.abs(Math.round(y)-m)||1,x=(r+l)*d+f,A=Math.abs(Math.round(x)-b)||1;return t.setTransform(0,Math.sign(d),Math.sign(u),0,m,b),t.drawImage(e,i,s,n,a,0,0,A,w),t.setTransform(c,d,u,p,g,f),[A,w]}t.drawImage(e,i,s,n,a,r,o,l,h);return[Math.hypot(c,d)*l,Math.hypot(u,p)*h]}class wh{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=Rr;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=Ur;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(t,e){this.clipBox=new Float32Array([0,0,t,e]),this.minMax=vh.slice()}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t}getPathBoundingBox(t=eh,e=null){const i=this.minMax.slice();if(t===ih){e||po("Stroke bounding box must include transform."),Ro.singularValueDecompose2dScale(e,mh);const t=mh[0]*this.lineWidth/2,s=mh[1]*this.lineWidth/2;i[0]-=t,i[1]-=s,i[2]+=t,i[3]+=s}return i}updateClipFromPath(){const t=Ro.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(vh,0)}getClippedPathBoundingBox(t=eh,e=null){return Ro.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function xh(t,e){if(e instanceof ImageData)return void t.putImageData(e,0,0);const i=e.height,s=e.width,n=i%fh,a=(i-n)/fh,r=0===n?a:a+1,o=t.createImageData(s,fh);let l,h=0;const c=e.data,d=o.data;let u,p,g,f;if(e.kind===Kr.GRAYSCALE_1BPP){const e=c.byteLength,i=new Uint32Array(d.buffer,0,d.byteLength>>2),f=i.length,_=s+7>>3,m=4294967295,v=Eo.isLittleEndian?4278190080:255;for(u=0;u<r;u++){for(g=u<a?fh:n,l=0,p=0;p<g;p++){const t=e-h;let n=0;const a=t>_?s:8*t-7,r=-8&a;let o=0,d=0;for(;n<r;n+=8)d=c[h++],i[l++]=128&d?m:v,i[l++]=64&d?m:v,i[l++]=32&d?m:v,i[l++]=16&d?m:v,i[l++]=8&d?m:v,i[l++]=4&d?m:v,i[l++]=2&d?m:v,i[l++]=1&d?m:v;for(;n<a;n++)0===o&&(d=c[h++],o=128),i[l++]=d&o?m:v,o>>=1}for(;l<f;)i[l++]=0;t.putImageData(o,0,u*fh)}}else if(e.kind===Kr.RGBA_32BPP){for(p=0,f=s*fh*4,u=0;u<a;u++)d.set(c.subarray(h,h+f)),h+=f,t.putImageData(o,0,p),p+=fh;u<r&&(f=s*n*4,d.set(c.subarray(h,h+f)),t.putImageData(o,0,p))}else{if(e.kind!==Kr.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=fh,f=s*g,u=0;u<r;u++){for(u>=a&&(g=n,f=s*g),l=0,p=f;p--;)d[l++]=c[h++],d[l++]=c[h++],d[l++]=c[h++],d[l++]=255;t.putImageData(o,0,u*fh)}}}function Ah(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,s=e.width,n=i%fh,a=(i-n)/fh,r=0===n?a:a+1,o=t.createImageData(s,fh);let l=0;const h=e.data,c=o.data;for(let e=0;e<r;e++){const i=e<a?fh:n;({srcPos:l}=gh({src:h,srcPos:l,dest:c,width:s,height:i,nonBlackColor:0})),t.putImageData(o,0,e*fh)}}function kh(t,e){const i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of i)void 0!==t[s]&&(e[s]=t[s]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function Th(t){t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0);const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function Sh(t,e){if(e)return!0;Ro.singularValueDecompose2dScale(t,mh);const i=Math.fround(Jo.pixelRatio*Fo.PDF_TO_CSS_UNITS);return mh[0]<=i&&mh[1]<=i}const Eh=["butt","round","square"],Ch=["miter","round","bevel"],Rh={},Mh={};class Ph{constructor(t,e,i,s,n,{optionalContentConfig:a,markedContentStack:r=null},o,l){this.ctx=t,this.current=new wh(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=i,this.canvasFactory=s,this.filterFactory=n,this.groupStack=[],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 bh(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return"string"==typeof t?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:s=null}){const n=this.ctx.canvas.width,a=this.ctx.canvas.height,r=this.ctx.fillStyle;if(this.ctx.fillStyle=s||"#ffffff",this.ctx.fillRect(0,0,n,a),this.ctx.fillStyle=r,i){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(...Xo(this.compositeCtx))}this.ctx.save(),Th(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=Xo(this.ctx)}executeOperatorList(t,e,i,s){const n=t.argsArray,a=t.fnArray;let r=e||0;const o=n.length;if(o===r)return r;const l=o-r>10&&"function"==typeof i,h=l?Date.now()+15:0;let c=0;const d=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint)return s.breakIt(r,i),r;if(p=a[r],p!==io.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,i),r}if(r++,r===o)return r;if(l&&++c>10){if(Date.now()>h)return i(),r;c=0}}}#Li(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#Li(),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.#Di()}#Di(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,s=t.height??t.displayHeight;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,c="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;r>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),r/=l/e),o>2&&h>1&&(i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/i),n=this.cachedCanvases.getCanvas(c,e,i),a=n.context,a.clearRect(0,0,e,i),a.drawImage(t,0,0,l,h,0,0,e,i),t=n.canvas,l=e,h=i,c="prescale1"===c?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=Xo(e);let o,l,h,c;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]),o=this._cachedBitmapsMap.get(e),o||(o=new Map,this._cachedBitmapsMap.set(e,o));const i=o.get(l);if(i&&!a){return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])}}h=i}h||(c=this.cachedCanvases.getCanvas("maskCanvas",i,s),Ah(c.context,t));let d=Ro.transform(r,[1/i,0,0,-1/s,0,0]);d=Ro.transform(d,[1,0,0,1,0,-s]);const u=vh.slice();Ro.axialAlignedBoundingBox([0,0,i,s],d,u);const[p,g,f,_]=u,m=Math.round(f-p)||1,v=Math.round(_-g)||1,b=this.cachedCanvases.getCanvas("fillCanvas",m,v),y=b.context,w=p,x=g;y.translate(-w,-x),y.transform(...d),h||(h=this._scaleImage(c.canvas,Yo(y)),h=h.img,o&&a&&o.set(l,h)),y.imageSmoothingEnabled=Sh(Xo(y),t.interpolate),yh(y,h,0,0,h.width,h.height,0,0,i,s),y.globalCompositeOperation="source-in";const A=Ro.transform(Yo(y),[1,0,0,1,-w,-x]);return y.fillStyle=a?n.getPattern(e,this,A,eh):n,y.fillRect(0,0,i,s),o&&!a&&(this.cachedCanvases.delete("fillCanvas"),o.set(l,b.canvas)),{canvas:b.canvas,offsetX:Math.round(w),offsetY:Math.round(x)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=Eh[t]}setLineJoin(t){this.ctx.lineJoin=Ch[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(t),i.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.ctx.globalAlpha=this.current.fillAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}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,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;const n=this.ctx=s.context;n.setTransform(this.suspendedCtx.getTransform()),kh(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,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,s,n,a,r){e.transform(t,i,s,n,a,r),this.__originalTransform(t,i,s,n,a,r)},t.setTransform=function(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r),this.__originalSetTransform(t,i,s,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,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r),this.__originalBezierCurveTo(t,i,s,n,a,r)},t.rect=function(t,i,s,n){e.rect(t,i,s,n),this.__originalRect(t,i,s,n)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(n,this.suspendedCtx),this.setGState([["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),kh(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,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;0!==r&&0!==o&&(this.genericComposeSMask(e.context,i,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(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,c){let d=t.canvas,u=o-h,p=l-c;if(a)if(u<0||p<0||u+i>d.width||p+s>d.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),e=t.context;e.drawImage(d,-u,-p),e.globalCompositeOperation="destination-atop",e.fillStyle=a,e.fillRect(0,0,i,s),e.globalCompositeOperation="source-over",d=t.canvas,u=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,s),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=a,t.fillRect(u,p,i,s),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,l,i,s),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(d,u,p,i,s,o,l,i,s),e.restore()}save(){this.inSMaskMode&&kh(this.ctx,this.suspendedCtx),this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){0!==this.stateStack.length?(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&kh(this.suspendedCtx,this.ctx),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){let[s]=e;if(!i)return s||=e[0]=new Path2D,void this[t](s);if(!(s instanceof Path2D)){const t=e[0]=new Path2D;for(let e=0,i=s.length;e<i;)switch(s[e++]){case so:t.moveTo(s[e++],s[e++]);break;case no:t.lineTo(s[e++],s[e++]);break;case ao:t.bezierCurveTo(s[e++],s[e++],s[e++],s[e++],s[e++],s[e++]);break;case ro:t.closePath();break;default:uo(`Unrecognized drawing path operator: ${s[e-1]}`)}s=t}Ro.axialAlignedBoundingBox(i,Xo(this.ctx),this.current.minMax),this[t](s)}closePath(){this.ctx.closePath()}stroke(t,e=!0){const i=this.ctx,s=this.current.strokeColor;if(i.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof s&&s?.getPattern){const e=s.isModifyingCurrentTransform()?i.getTransform():null;if(i.save(),i.strokeStyle=s.getPattern(i,this,Yo(i),ih),e){const s=new Path2D;s.addPath(t,i.getTransform().invertSelf().multiplySelf(e)),t=s}this.rescaleAndStroke(t,!1),i.restore()}else this.rescaleAndStroke(t,!0);e&&this.consumePath(t,this.current.getClippedPathBoundingBox(ih,Xo(this.ctx))),i.globalAlpha=this.current.fillAlpha}closeStroke(t){this.stroke(t)}fill(t,e=!0){const i=this.ctx,s=this.current.fillColor;let n=!1;if(this.current.patternFill){const e=s.isModifyingCurrentTransform()?i.getTransform():null;if(i.save(),i.fillStyle=s.getPattern(i,this,Yo(i),eh),e){const s=new Path2D;s.addPath(t,i.getTransform().invertSelf().multiplySelf(e)),t=s}n=!0}const a=this.current.getClippedPathBoundingBox();this.contentVisible&&null!==a&&(this.pendingEOFill?(i.fill(t,"evenodd"),this.pendingEOFill=!1):i.fill(t)),n&&i.restore(),e&&this.consumePath(t,a)}eoFill(t){this.pendingEOFill=!0,this.fill(t)}fillStroke(t){this.fill(t,!1),this.stroke(t,!1),this.consumePath(t)}eoFillStroke(t){this.pendingEOFill=!0,this.fillStroke(t)}closeFillStroke(t){this.fillStroke(t)}closeEOFillStroke(t){this.pendingEOFill=!0,this.fillStroke(t)}endPath(t){this.consumePath(t)}rawFillPath(t){this.ctx.fill(t)}clip(){this.pendingClip=Rh}eoClip(){this.pendingClip=Mh}beginText(){this.current.textMatrix=null,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)return;const i=new Path2D,s=e.getTransform().invertSelf();for(const{transform:e,x:n,y:a,fontSize:r,path:o}of t)i.addPath(o,new DOMMatrix(e).preMultiplySelf(s).translate(n,a).scale(r,-r));e.clip(i),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const i=this.commonObjs.get(t),s=this.current;if(!i)throw new Error(`Can't find font for ${t}`);if(s.fontMatrix=i.fontMatrix||Rr,0!==s.fontMatrix[0]&&0!==s.fontMatrix[3]||uo("Invalid font matrix for font "+t),e<0?(e=-e,s.fontDirection=-1):s.fontDirection=1,this.current.font=i,this.current.fontSize=e,i.isType3Font)return;const n=i.loadedName||"sans-serif",a=i.systemFontInfo?.css||`"${n}", ${i.fallbackName}`;let r="normal";i.black?r="900":i.bold&&(r="bold");const o=i.italic?"italic":"normal";let l=e;e<16?l=16:e>100&&(l=100),this.current.fontSizeScale=e/l,this.ctx.font=`${o} ${r} ${l}px ${a}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t){const{current:e}=this;e.textMatrix=t,e.textMatrixScale=Math.hypot(t[0],t[1]),e.x=e.lineX=0,e.y=e.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#Ii(t,e,i){const s=new Path2D;return s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e)),s}paintChar(t,e,i,s,n){const a=this.ctx,r=this.current,o=r.font,l=r.textRenderingMode,h=r.fontSize/r.fontSizeScale,c=l&Gr,d=!!(l&qr),u=r.patternFill&&!o.missingFile,p=r.patternStroke&&!o.missingFile;let g;if((o.disableFontFace||d||u||p)&&(g=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||u||p){let t;if(a.save(),a.translate(e,i),a.scale(h,-h),c!==Ur&&c!==$r||(s?(t=a.getTransform(),a.setTransform(...s),a.fill(this.#Ii(g,t,s))):a.fill(g)),c===Hr||c===$r)if(n){t||=a.getTransform(),a.setTransform(...n);const{a:e,b:i,c:s,d:r}=t,o=Ro.inverseTransform(n),l=Ro.transform([e,i,s,r,0,0],o);Ro.singularValueDecompose2dScale(l,mh),a.lineWidth*=Math.max(mh[0],mh[1])/h,a.stroke(this.#Ii(g,t,n))}else a.lineWidth/=h,a.stroke(g);a.restore()}else c!==Ur&&c!==$r||a.fillText(t,e,i),c!==Hr&&c!==$r||a.strokeText(t,e,i);if(d){(this.pendingTextPaths||=[]).push({transform:Xo(a),x:e,y:i,fontSize:h,path:g})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){i=!0;break}return mo(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,c=t.length,d=i.vertical,u=d?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],f=e.textRenderingMode===Ur&&!i.disableFontFace&&!e.patternFill;let _,m;if(n.save(),e.textMatrix&&n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(h,-1):n.scale(h,1),e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,Yo(n),eh);_=Xo(n),n.restore(),n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,Yo(n),ih);m=Xo(n),n.restore(),n.strokeStyle=t}let v=e.lineWidth;const b=e.textMatrixScale;if(0===b||0===v){const t=e.textRenderingMode&Gr;t!==Hr&&t!==$r||(v=this.getSinglePixelWidth())}else v/=b;if(1!==a&&(n.scale(a,a),v/=a),n.lineWidth=v,i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t)i.push(e.unicode),s+=e.width;return n.fillText(i.join(""),0,0),e.x+=s*g*h,n.restore(),void this.compose()}let y,w=0;for(y=0;y<c;++y){const e=t[y];if("number"==typeof e){w+=u*e*s/1e3;continue}let h=!1;const c=(e.isSpace?o:0)+r,v=e.fontChar,b=e.accent;let x,A,k=e.width;if(d){const t=e.vmetric||p,i=-(e.vmetric?t[1]:.5*k)*g,s=t[2]*g;k=t?-t[0]:k,x=i/a,A=(w+s)/a}else x=w/a,A=0;if(i.remeasure&&k>0){const t=1e3*n.measureText(v).width/s*a;if(k<t&&this.isFontSubpixelAAEnabled){const e=k/t;h=!0,n.save(),n.scale(e,1),x/=e}else k!==t&&(x+=(k-t)/2e3*s/a)}if(this.contentVisible&&(e.isInFont||i.missingFile))if(f&&!b)n.fillText(v,x,A);else if(this.paintChar(v,x,A,_,m),b){const t=x+s*b.offset.x/a,e=A-s*b.offset.y/a;this.paintChar(b.fontChar,t,e,_,m)}w+=d?k*g-c*l:k*g+c*l,h&&n.restore()}d?e.y-=w:e.x+=w*h,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,i=this.current,s=i.font,n=i.fontSize,a=i.fontDirection,r=s.vertical?1:-1,o=i.charSpacing,l=i.wordSpacing,h=i.textHScale*a,c=i.fontMatrix||Rr,d=t.length;let u,p,g,f;if(!(i.textRenderingMode===Wr)&&0!==n){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),i.textMatrix&&e.transform(...i.textMatrix),e.translate(i.x,i.y+i.textRise),e.scale(h,a),u=0;u<d;++u){if(p=t[u],"number"==typeof p){f=r*p*n/1e3,this.ctx.translate(f,0),i.x+=f*h;continue}const a=(p.isSpace?l:0)+o,d=s.charProcOperatorList[p.operatorListId];d?this.contentVisible&&(this.save(),e.scale(n,n),e.transform(...c),this.executeOperatorList(d),this.restore()):uo(`Type3 character "${p.operatorListId}" is not available.`);const _=[p.width,0];Ro.applyTransform(_,c),g=_[0]*n+a,e.translate(g,0),i.x+=g*h}e.restore()}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,i,s,n,a){const r=new Path2D;r.rect(i,s,n-i,a-s),this.ctx.clip(r),this.endPath()}getColorN_Pattern(t){let e;if("TilingPattern"===t[0]){const i=this.baseTransform||Xo(this.ctx),s={createCanvasGraphics:t=>new Ph(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new ph(t,this.ctx,s,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t){this.ctx.strokeStyle=this.current.strokeColor=t,this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t){this.ctx.fillStyle=this.current.fillColor=t,this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=function(t){switch(t[0]){case"RadialAxial":return new rh(t);case"Mesh":return new hh(t);case"Dummy":return new ch}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t)),this.cachedPatterns.set(t,i)),e&&(i.matrix=e),i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,Yo(e),sh);const s=Yo(e);if(s){const{width:t,height:i}=e.canvas,n=vh.slice();Ro.axialAlignedBoundingBox([0,0,t,i],s,n);const[a,r,o,l]=n;this.ctx.fillRect(a,r,o-a,l-r)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){po("Should not call beginInlineImage")}beginImageData(){po("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=Xo(this.ctx),e)){Ro.axialAlignedBoundingBox(e,this.baseTransform,this.current.minMax);const[t,i,s,n]=e,a=new Path2D;a.rect(t,i,s-t,n-i),this.ctx.clip(a),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||co("TODO: Support non-isolated groups."),t.knockout&&uo("Knockout groups not supported.");const i=Xo(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let s=vh.slice();Ro.axialAlignedBoundingBox(t.bbox,Xo(e),s);const n=[0,0,e.canvas.width,e.canvas.height];s=Ro.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const c=this.cachedCanvases.getCanvas(h,o,l),d=c.context;d.translate(-a,-r),d.transform(...i);let u=new Path2D;const[p,g,f,_]=t.bbox;if(u.rect(p,g,f-p,_-g),t.matrix){const e=new Path2D;e.addPath(u,new DOMMatrix(t.matrix)),u=e}d.clip(u),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()),kh(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,i=this.groupStack.pop();if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const t=Xo(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...t);const i=vh.slice();Ro.axialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t,i),this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,e,i,s,n){if(this.#Li(),Th(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0],i[5]-=e[1],(e=e.slice())[0]=e[1]=0,e[2]=s,e[3]=a,Ro.singularValueDecompose2dScale(Xo(this.ctx),mh);const{viewportScale:n}=this,r=Math.ceil(s*this.outputScaleX*n),o=Math.ceil(a*this.outputScaleY*n);this.annotationCanvas=this.canvasFactory.create(r,o);const{canvas:l,context:h}=this.annotationCanvas;this.annotationCanvasMap.set(t,l),this.annotationCanvas.savedCtx=this.ctx,this.ctx=h,this.ctx.save(),this.ctx.setTransform(mh[0],0,0,-mh[1],0,a*mh[1]),Th(this.ctx)}else{Th(this.ctx),this.endPath();const t=new Path2D;t.rect(e[0],e[1],s,a),this.ctx.clip(t)}}this.current=new wh(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...i),this.transform(...s)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#Di(),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 i=this.ctx,s=this._createMaskCanvas(t),n=s.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(n,s.offsetX,s.offsetY),i.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=Xo(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;t<h;t+=2){const h=Ro.transform(o,[e,i,s,n,a[t],a[t+1]]);r.drawImage(l.canvas,h[4],h[5])}r.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,i=this.current.fillColor,s=this.current.patternFill;for(const n of t){const{data:t,width:a,height:r,transform:o}=n,l=this.cachedCanvases.getCanvas("maskCanvas",a,r),h=l.context;h.save();Ah(h,this.getObject(t,n)),h.globalCompositeOperation="source-in",h.fillStyle=s?i.getPattern(h,this,Yo(e),eh):i,h.fillRect(0,0,a,r),h.restore(),e.save(),e.transform(...o),e.scale(1,-1),yh(e,l.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):uo("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,i,s){if(!this.contentVisible)return;const n=this.getObject(t);if(!n)return void uo("Dependent image isn't ready yet");const a=n.width,r=n.height,o=[];for(let t=0,n=s.length;t<n;t+=2)o.push({transform:[e,0,0,i,s[t],s[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:i,height:s}=t,n=this.cachedCanvases.getCanvas("inlineImage",i,s),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,i=t.height,s=this.ctx;this.save();const{filter:n}=s;let a;if("none"!==n&&""!==n&&(s.filter="none"),s.scale(1/e,-1/i),t.bitmap)a=this.applyTransferMapsToBitmap(t);else if("function"==typeof HTMLElement&&t instanceof HTMLElement||!t.data)a=t;else{const s=this.cachedCanvases.getCanvas("inlineImage",e,i).context;xh(s,t),a=this.applyTransferMapsToCanvas(s)}const r=this._scaleImage(a,Yo(s));s.imageSmoothingEnabled=Sh(Xo(s),t.interpolate),yh(s,r.img,0,0,r.paintWidth,r.paintHeight,0,-i,e,i),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.ctx;let s;if(t.bitmap)s=t.bitmap;else{const e=t.width,i=t.height,n=this.cachedCanvases.getCanvas("inlineImage",e,i).context;xh(n,t),s=this.applyTransferMapsToCanvas(n)}for(const t of e)i.save(),i.transform(...t.transform),i.scale(1,-1),yh(i,s,t.x,t.y,t.w,t.h,0,-1,1,1),i.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,e){const i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(e);const s=this.ctx;this.pendingClip&&(i||(this.pendingClip===Mh?s.clip(t,"evenodd"):s.clip(t)),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Xo(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]),i=Math.hypot(t[0],t[2]),s=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,s)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:i,c:s,d:n}=this.ctx.getTransform();let a,r;if(0===i&&0===s){const i=Math.abs(e),s=Math.abs(n);if(i===s)if(0===t)a=r=1/i;else{const e=i*t;a=r=e<1?1/e:1}else if(0===t)a=1/i,r=1/s;else{const e=i*t,n=s*t;a=e<1?1/e:1,r=n<1?1/n:1}}else{const o=Math.abs(e*n-i*s),l=Math.hypot(e,i),h=Math.hypot(s,n);if(0===t)a=h/o,r=l/o;else{const e=t*o;a=h>e?h/e:1,r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:s}}=this,[n,a]=this.getScaleForStroking();if(n===a)return i.lineWidth=(s||1)*n,void i.stroke(t);const r=i.getLineDash();e&&i.save(),i.scale(n,a),_h.a=1/n,_h.d=1/a;const o=new Path2D;if(o.addPath(t,_h),r.length>0){const t=Math.max(n,a);i.setLineDash(r.map((e=>e/t))),i.lineDashOffset/=t}i.lineWidth=s||1,i.stroke(o),e&&i.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in io)void 0!==Ph.prototype[t]&&(Ph.prototype[io[t]]=Ph.prototype[t]);class Lh{static#Oi=null;static#Ni="";static get workerPort(){return this.#Oi}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Oi=t}static get workerSrc(){return this.#Ni}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Ni=t}}class Dh{#Fi;#Bi;constructor({parsedData:t,rawData:e}){this.#Fi=t,this.#Bi=e}getRaw(){return this.#Bi}get(t){return this.#Fi.get(t)??null}[Symbol.iterator](){return this.#Fi.entries()}}const Ih=Symbol("INTERNAL");class Oh{#ji=!1;#zi=!1;#Vi=!1;#Ui=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#ji=!!(t&Lr),this.#zi=!!(t&Dr),this.name=e,this.intent=i,this.usage=s,this.rbGroups=n}get visible(){if(this.#Vi)return this.#Ui;if(!this.#Ui)return!1;const{print:t,view:e}=this.usage;return this.#ji?"OFF"!==e?.viewState:!this.#zi||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Ih&&po("Internal method `_setVisible` called."),this.#Vi=i,this.#Ui=e}}class Nh{#Hi=null;#$i=new Map;#Wi=null;#Gi=null;constructor(t,e=Lr){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Gi=t.order;for(const i of t.groups)this.#$i.set(i.id,new Oh(e,i));if("OFF"===t.baseState)for(const t of this.#$i.values())t._setVisible(Ih,!1);for(const e of t.on)this.#$i.get(e)._setVisible(Ih,!0);for(const e of t.off)this.#$i.get(e)._setVisible(Ih,!1);this.#Wi=this.getHash()}}#qi(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s<e;s++){const e=t[s];let n;if(Array.isArray(e))n=this.#qi(e);else{if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;n=this.#$i.get(e).visible}switch(i){case"And":if(!n)return!1;break;case"Or":if(n)return!0;break;case"Not":return!n;default:return!0}}return"And"===i}isVisible(t){if(0===this.#$i.size)return!0;if(!t)return co("Optional content group not defined."),!0;if("OCG"===t.type)return this.#$i.has(t.id)?this.#$i.get(t.id).visible:(uo(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#qi(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;if(this.#$i.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;if(!this.#$i.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;if(!this.#$i.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;if(this.#$i.get(e).visible)return!1}return!0}return uo(`Unknown optional content policy ${t.policy}.`),!0}return uo(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,i=!0){const s=this.#$i.get(t);if(s){if(i&&e&&s.rbGroups.length)for(const e of s.rbGroups)for(const i of e)i!==t&&this.#$i.get(i)?._setVisible(Ih,!1,!0);s._setVisible(Ih,!!e,!0),this.#Hi=null}else uo(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(const s of t){switch(s){case"ON":case"OFF":case"Toggle":i=s;continue}const t=this.#$i.get(s);if(t)switch(i){case"ON":this.setVisibility(s,!0,e);break;case"OFF":this.setVisibility(s,!1,e);break;case"Toggle":this.setVisibility(s,!t.visible,e)}}this.#Hi=null}get hasInitialVisibility(){return null===this.#Wi||this.getHash()===this.#Wi}getOrder(){return this.#$i.size?this.#Gi?this.#Gi.slice():[...this.#$i.keys()]:null}getGroup(t){return this.#$i.get(t)||null}getHash(){if(null!==this.#Hi)return this.#Hi;const t=new _l;for(const[e,i]of this.#$i)t.update(`${e}:${i.visible}`);return this.#Hi=t.hexdigest()}[Symbol.iterator](){return this.#$i.entries()}}class Fh{constructor(t,{disableRange:e=!1,disableStream:i=!1}){go(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,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=!i,this._isRangeSupported=!e,this._contentLength=s,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 i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{go(this._rangeReaders.some((function(e){return e._begin===t&&(e._enqueue(i),!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(){go(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Bh(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new jh(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class Bh{constructor(t,e,i=!1,s=null){this._stream=t,this._done=i||!1,this._filename=Uo(s)?s: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){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}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 jh{constructor(t,e,i){this._stream=t,this._begin=e,this._end=i,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 zh(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function Vh(t){return URL.parse(t)?.origin??null}function Uh({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return n;if(n.suggestedLength=a,a<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;return"identity"!==(t.get("Content-Encoding")||"identity")||(n.allowRangeRequests=!0),n}function Hh(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=s("filename\\*","i").exec(t);if(i){i=i[1];let t=r(i);return t=unescape(t),t=o(t),t=l(t),a(t)}if(i=function(t){const e=[];let i;const n=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,s,n]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[s,n]}const a=[];for(let t=0;t<e.length&&t in e;++t){let[i,s]=e[t];s=r(s),i&&(s=unescape(s),0===t&&(s=o(s))),a.push(s)}return a.join("")}(t),i)return a(l(i));if(i=s("filename","i").exec(t),i){i=i[1];let t=r(i);return t=l(t),a(t)}function s(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function n(t,i){if(t){if(!/^[\x00-\xFF]+$/.test(i))return i;try{const s=new TextDecoder(t,{fatal:!0}),n=So(i);i=s.decode(n),e=!1}catch{}}return i}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 i=e[t].indexOf('"');-1!==i&&(e[t]=e[t].slice(0,i),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 l(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(t,e,i,s){if("q"===i||"Q"===i)return n(e,s=(s=s.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(t,e){return String.fromCharCode(parseInt(e,16))})));try{s=atob(s)}catch{}return n(e,s)}))}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(Uo(t))return t}return null}function $h(t,e){return new xo(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t,404===t||0===t&&e.startsWith("file:"))}function Wh(t){return 200===t||206===t}function Gh(t,e,i){return{method:"GET",headers:t,signal:i.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function qh(t){return t instanceof Uint8Array?t.buffer:t instanceof ArrayBuffer?t:(uo(`getArrayBuffer - unexpected data format: ${t}`),new Uint8Array(t).buffer)}class Kh{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=zh(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return go(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new Xh(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new Yh(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Xh{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const i=new Headers(t.headers),s=e.url;fetch(s,Gh(i,this._withCredentials,this._abortController)).then((e=>{if(t._responseOrigin=Vh(e.url),!Wh(e.status))throw $h(e.status,s);this._reader=e.body.getReader(),this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=Uh({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n,this._contentLength=a||this._contentLength,this._filename=Hh(i),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ko("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:qh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Yh{constructor(t,e,i){this._stream=t,this._reader=null,this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!s.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,Gh(n,this._withCredentials,this._abortController)).then((e=>{const i=Vh(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!Wh(e.status))throw $h(e.status,a);this._readCapability.resolve(),this._reader=e.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:qh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Qh{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=zh(this.isHttp,e),this.withCredentials=i||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.expectedStatus=206):s.expectedStatus=200,e.responseType="arraybuffer",go(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,i),e.onprogress=this.onProgress.bind(this,i),s.onHeadersReceived=t.onHeadersReceived,s.onDone=t.onDone,s.onError=t.onError,s.onProgress=t.onProgress,e.send(null),i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==s.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===s.status&&this.isHttp)return void i.onError(s.status);const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus)return void i.onError(s.status);const a=function(t){const e=t.response;return"string"!=typeof e?e:So(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);e?i.onDone({begin:parseInt(e[1],10),chunk:a}):(uo('Missing or invalid "Content-Range" header.'),i.onError(0))}else a?i.onDone({begin:0,chunk:a}):i.onError(s.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 Jh{constructor(t){this._source=t,this._manager=new Qh(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return go(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Zh(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const i=new tc(this._manager,t,e);return i.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Zh{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=Vh(e.responseURL);const i=e.getAllResponseHeaders(),s=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]})):[]),{allowRangeRequests:n,suggestedLength:a}=Uh({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=a||this._contentLength,this._filename=Hh(s),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);if(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=$h(t,this._url),this._headersCapability.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._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);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 tc{constructor(t,e,i){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){const t=Vh(this._manager.getRequestXhr(this._requestId)?.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else 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??=$h(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 ec=/^[a-z][a-z0-9\-+.]+:/i;class ic{constructor(t){this.source=t,this.url=function(t){if(ec.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url),go("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return go(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new sc(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new nc(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class sc{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();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then((t=>{this._contentLength=t.size,this._setReadableStream(i.createReadStream(this._url)),this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=$h(0,this._url.href)),this._storedError=t,this._headersCapability.reject(t)}))}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();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{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 ko("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class nc{constructor(t,e,i){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const s=t.source;this._isStreamingSupported=!s.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:i-1}))}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();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded});return{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)}}const ac=Symbol("INITIAL_DATA");class rc{#Ki=Object.create(null);#Xi(t){return this.#Ki[t]||={...Promise.withResolvers(),data:ac}}get(t,e=null){if(e){const i=this.#Xi(t);return i.promise.then((()=>e(i.data))),null}const i=this.#Ki[t];if(!i||i.data===ac)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Ki[t];return!!e&&e.data!==ac}delete(t){const e=this.#Ki[t];return!(!e||e.data===ac)&&(delete this.#Ki[t],!0)}resolve(t,e=null){const i=this.#Xi(t);i.data=e,i.resolve()}clear(){for(const t in this.#Ki){const{data:e}=this.#Ki[t];e?.bitmap?.close()}this.#Ki=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Ki){const{data:e}=this.#Ki[t];e!==ac&&(yield[t,e])}}}class oc{#Yi=Promise.withResolvers();#_t=null;#Qi=!1;#Ji=!!globalThis.FontInspector?.enabled;#Zi=null;#ts=null;#es=0;#is=0;#ss=null;#ns=null;#as=0;#rs=0;#os=Object.create(null);#ls=[];#hs=null;#cs=[];#ds=new WeakMap;#us=null;static#ps=new Map;static#gs=new Map;static#fs=new WeakMap;static#_s=null;static#ms=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#hs=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#hs=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#_t=this.#ns=e,this.#rs=i.scale*Jo.pixelRatio,this.#as=i.rotation,this.#ts={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#us=[1,0,0,-1,-a,r+n],this.#is=s,this.#es=n,oc.#vs(),Qo(e,i),this.#Yi.promise.finally((()=>{oc.#ms.delete(this),this.#ts=null,this.#os=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Eo.platform;return mo(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const t=()=>{this.#ss.read().then((({value:e,done:i})=>{i?this.#Yi.resolve():(this.#Zi??=e.lang,Object.assign(this.#os,e.styles),this.#bs(e.items),t())}),this.#Yi.reject)};return this.#ss=this.#hs.getReader(),oc.#ms.add(this),t(),this.#Yi.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*Jo.pixelRatio,s=t.rotation;if(s!==this.#as&&(e?.(),this.#as=s,Qo(this.#ns,{rotation:s})),i!==this.#rs){e?.(),this.#rs=i;const t={div:null,properties:null,ctx:oc.#ys(this.#Zi)};for(const e of this.#cs)t.properties=this.#ds.get(e),t.div=e,this.#ws(t)}}cancel(){const t=new ko("TextLayer task cancelled.");this.#ss?.cancel(t).catch((()=>{})),this.#ss=null,this.#Yi.reject(t)}get textDivs(){return this.#cs}get textContentItemsStr(){return this.#ls}#bs(t){if(this.#Qi)return;this.#ts.ctx??=oc.#ys(this.#Zi);const e=this.#cs,i=this.#ls;for(const s of t){if(e.length>1e5)return uo("Ignoring additional textDivs for performance reasons."),void(this.#Qi=!0);if(void 0!==s.str)i.push(s.str),this.#xs(s);else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#_t;this.#_t=document.createElement("span"),this.#_t.classList.add("markedContent"),null!==s.id&&this.#_t.setAttribute("id",`${s.id}`),t.append(this.#_t)}else"endMarkedContent"===s.type&&(this.#_t=this.#_t.parentNode)}}#xs(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#cs.push(e);const s=Ro.transform(this.#us,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#os[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Ji&&a.fontSubstitution||a.fontFamily;r=oc.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*oc.#As(r,a,this.#Zi);let h,c;0===n?(h=s[4],c=s[5]-l):(h=s[4]+l*Math.sin(n),c=s[5]-l*Math.cos(n));const d="calc(var(--total-scale-factor) *",u=e.style;this.#_t===this.#ns?(u.left=`${(100*h/this.#is).toFixed(2)}%`,u.top=`${(100*c/this.#es).toFixed(2)}%`):(u.left=`${d}${h.toFixed(2)}px)`,u.top=`${d}${c.toFixed(2)}px)`),u.fontSize=`${d}${(oc.#_s*o).toFixed(2)}px)`,u.fontFamily=r,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#Ji&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==n&&(i.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]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}if(p&&(i.canvasWidth=a.vertical?t.height:t.width),this.#ds.set(e,i),this.#ts.div=e,this.#ts.properties=i,this.#ws(this.#ts),i.hasText&&this.#_t.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#_t.append(t)}}#ws(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";if(oc.#_s>1&&(a=`scale(${1/oc.#_s})`),0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;oc.#ks(s,o*this.#rs,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#rs/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`),a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#ms.size>0)){this.#ps.clear();for(const{canvas:t}of this.#gs.values())t.remove();this.#gs.clear()}}static#ys(t=null){let e=this.#gs.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#gs.set(t,e),this.#fs.set(e,{size:0,family:""})}return e}static#ks(t,e,i){const s=this.#fs.get(t);e===s.size&&i===s.family||(t.font=`${e}px ${i}`,s.size=e,s.family=i)}static#vs(){if(null!==this.#_s)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#_s=t.getBoundingClientRect().height,t.remove()}static#As(t,e,i){const s=this.#ps.get(t);if(s)return s;const n=this.#ys(i);n.canvas.width=n.canvas.height=30,this.#ks(n,30,t);const a=n.measureText(""),r=a.fontBoundingBoxAscent,o=Math.abs(a.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let l=.8;return r?l=r/(r+o):(Eo.platform.isFirefox&&uo("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)),this.#ps.set(t,l),l}}class lc{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let s=null;const n=i.name;if("#text"===n)s=i.value;else{if(!lc.shouldBuildText(n))return;i?.attributes?.textContent?s=i.attributes.textContent:i.value&&(s=i.value)}if(null!==s&&e.push({str:s}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}function hc(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new cc,{docId:i}=e,s=t.url?function(t){if(t instanceof URL)return t.href;if("string"==typeof t){if(Cr)return t;const e=URL.parse(t,window.location);if(e)return e.href}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(Cr&&"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 So(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,l=t.range instanceof dc?t.range:null,h=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let c=t.worker instanceof gc?t.worker:null;const d=t.verbosity,u="string"!=typeof t.docBaseUrl||Vo(t.docBaseUrl)?null:t.docBaseUrl,p=xl(t.cMapUrl),g=!1!==t.cMapPacked,f=t.CMapReaderFactory||(Cr?Jl:Ul),_=xl(t.iccUrl),m=xl(t.standardFontDataUrl),v=t.StandardFontDataFactory||(Cr?Zl:Gl),b=xl(t.wasmUrl),y=t.WasmFactory||(Cr?th:Kl),w=!0!==t.stopAtErrors,x=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,A=!1!==t.isEvalSupported,k="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!Cr,T="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!Cr&&(Eo.platform.isFirefox||!globalThis.chrome),S=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,E="boolean"==typeof t.disableFontFace?t.disableFontFace:Cr,C=!0===t.fontExtraProperties,R=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,P=!0===t.disableRange,L=!0===t.disableStream,D=!0===t.disableAutoFetch,I=!0===t.pdfBug,O=t.CanvasFactory||(Cr?Ql:zl),N=t.FilterFactory||(Cr?Yl:$l),F=!0===t.enableHWA,B=!1!==t.useWasm,j=l?l.length:t.length??NaN,z="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!Cr&&!E,V="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:!!(f===Ul&&v===Gl&&y===Kl&&p&&m&&b&&$o(p,document.baseURI)&&$o(m,document.baseURI)&&$o(b,document.baseURI));lo(d);const U={canvasFactory:new O({ownerDocument:M,enableHWA:F}),filterFactory:new N({docId:i,ownerDocument:M}),cMapReaderFactory:V?null:new f({baseUrl:p,isCompressed:g}),standardFontDataFactory:V?null:new v({baseUrl:m}),wasmFactory:V?null:new y({baseUrl:b})};c||(c=gc.create({verbosity:d,port:Lh.workerPort}),e._worker=c);const H={docId:i,apiVersion:"5.3.31",data:n,password:o,disableAutoFetch:D,rangeChunkSize:h,length:j,docBaseUrl:u,enableXfa:R,evaluatorOptions:{maxImageSize:x,disableFontFace:E,ignoreErrors:w,isEvalSupported:A,isOffscreenCanvasSupported:k,isImageDecoderSupported:T,canvasMaxAreaInBytes:S,fontExtraProperties:C,useSystemFonts:z,useWasm:B,useWorkerFetch:V,cMapUrl:p,iccUrl:_,standardFontDataUrl:m,wasmUrl:b}},$={ownerDocument:M,pdfBug:I,styleElement:null,loadingParams:{disableAutoFetch:D,enableXfa:R}};return c.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",H,n?[n.buffer]:null);let o;if(l)o=new Fh(l,{disableRange:P,disableStream:L});else if(!n){if(!s)throw new Error("getDocument - no `url` parameter provided.");const t=$o(s)?Kh:Cr?ic:Jh;o=new t({url:s,length:j,httpHeaders:a,withCredentials:r,rangeChunkSize:h,disableRange:P,disableStream:L})}return t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const s=new Bl(i,t,c.port),n=new fc(s,e,o,$,U);e._transport=n,s.send("Ready",null)}))})).catch(e._capability.reject),e}class cc{static#vi=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+cc.#vi++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class dc{#Yi=Promise.withResolvers();#Ts=[];#Ss=[];#Es=[];#Cs=[];constructor(t,e,i=!1,s=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=s}addRangeListener(t){this.#Cs.push(t)}addProgressListener(t){this.#Es.push(t)}addProgressiveReadListener(t){this.#Ss.push(t)}addProgressiveDoneListener(t){this.#Ts.push(t)}onDataRange(t,e){for(const i of this.#Cs)i(t,e)}onDataProgress(t,e){this.#Yi.promise.then((()=>{for(const i of this.#Es)i(t,e)}))}onDataProgressiveRead(t){this.#Yi.promise.then((()=>{for(const e of this.#Ss)e(t)}))}onDataProgressiveDone(){this.#Yi.promise.then((()=>{for(const t of this.#Ts)t()}))}transportReady(){this.#Yi.resolve()}requestDataRange(t,e){po("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class uc{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return mo(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 pc{#Rs=!1;constructor(t,e,i,s=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=s?new Ho:null,this._pdfBug=s,this.commonObjs=i.commonObjs,this.objs=new rc,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:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new jo({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return mo(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=jr.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:l=null,printAnnotationStorage:h=null,isEditing:c=!1}){this._stats?.time("Overall");const d=this._transport.getRenderingIntent(i,s,h,c),{renderingIntent:u,cacheKey:p}=d;this.#Rs=!1,r||=this._transport.getOptionalContentConfig(u);let g=this._intentStates.get(p);g||(g=Object.create(null),this._intentStates.set(p,g)),g.streamReaderCancelTimeout&&(clearTimeout(g.streamReaderCancelTimeout),g.streamReaderCancelTimeout=null);const f=!!(u&Dr);g.displayReadyCapability||(g.displayReadyCapability=Promise.withResolvers(),g.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(d));const _=t=>{g.renderTasks.delete(m),f&&(this.#Rs=!0),this.#Ms(),t?(m.capability.reject(t),this._abortOperatorList({intentState:g,reason:t instanceof Error?t:new Error(t)})):m.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},m=new mc({callback:_,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:!f,pdfBug:this._pdfBug,pageColors:l});(g.renderTasks||=new Set).add(m);const v=m.task;return Promise.all([g.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)_();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&u))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");m.initializeGraphics({transparency:t,optionalContentConfig:e}),m.operatorListChanged()}})).catch(_),v}getOperatorList({intent:t="display",annotationMode:e=jr.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);return r||(r=Object.create(null),this._intentStates.set(n.cacheKey,r)),r.opListReadCapability||(a=Object.create(null),a.operatorListChanged=function(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(a))},r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(a),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),r.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=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>lc.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function e(){s.read().then((function({value:i,done:s}){s?t(n):(n.lang??=i.lang,Object.assign(n.styles,i.styles),n.items.push(...i.items),e())}),i)}()}))}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 i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#Rs=!1,Promise.all(t)}cleanup(t=!1){this.#Rs=!0;const e=this.#Ms();return t&&e&&(this._stats&&=new Ho),e}#Ms(){if(!this.#Rs||this.destroyed)return!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.#Rs=!1,!0}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,s=t.length;i<s;i++)e.operatorList.fnArray.push(t.fnArray[i]),e.operatorList.argsArray.push(t.argsArray[i]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#Ms()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:s}){const{map:n,transfer:a}=i,r=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:s},a).getReader(),o=this._intentStates.get(e);o.streamReader=r;const l=()=>{r.read().then((({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())}),(t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#Ms()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof zo){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})}),i))}}if(t.streamReader.cancel(new ko(e.message)).catch((()=>{})),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class gc{#Yi=Promise.withResolvers();#Ps=null;#Oi=null;#Ls=null;static#Ds=0;static#Is=!1;static#Os=new WeakMap;static{Cr&&(this.#Is=!0,Lh.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const s=new URL(e,i);return i.origin===s.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))},this.fromPort=t=>{var e;if(e="`PDFWorker.fromPort` - please use `PDFWorker.create` instead.",console.log("Deprecated API usage: "+e),!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.create(t)}}constructor({name:t=null,port:e=null,verbosity:i=ho()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,e){if(gc.#Os.has(e))throw new Error("Cannot use more than one PDFWorker per port.");gc.#Os.set(e,this),this.#Ns(e)}else this.#Fs()}get promise(){return this.#Yi.promise}#Bs(){this.#Yi.resolve(),this.#Ps.send("configure",{verbosity:this.verbosity})}get port(){return this.#Oi}get messageHandler(){return this.#Ps}#Ns(t){this.#Oi=t,this.#Ps=new Bl("main","worker",t),this.#Ps.on("ready",(()=>{})),this.#Bs()}#Fs(){if(gc.#Is||gc.#js)return void this.#zs();let{workerSrc:t}=gc;try{gc._isSameOrigin(window.location,t)||(t=gc._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new Bl("main","worker",e),s=()=>{n.abort(),i.destroy(),e.terminate(),this.destroyed?this.#Yi.reject(new Error("Worker was destroyed")):this.#zs()},n=new AbortController;e.addEventListener("error",(()=>{this.#Ls||s()}),{signal:n.signal}),i.on("test",(t=>{n.abort(),!this.destroyed&&t?(this.#Ps=i,this.#Oi=e,this.#Ls=e,this.#Bs()):s()})),i.on("ready",(t=>{if(n.abort(),this.destroyed)s();else try{a()}catch{this.#zs()}}));const a=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void a()}catch{co("The worker has been disabled.")}this.#zs()}#zs(){gc.#Is||(uo("Setting up fake worker."),gc.#Is=!0),gc._setupFakeWorkerGlobal.then((t=>{if(this.destroyed)return void this.#Yi.reject(new Error("Worker was destroyed"));const e=new Tl;this.#Oi=e;const i="fake"+gc.#Ds++,s=new Bl(i+"_worker",i,e);t.setup(s,e),this.#Ps=new Bl(i,i+"_worker",e),this.#Bs()})).catch((t=>{this.#Yi.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0,this.#Ls?.terminate(),this.#Ls=null,gc.#Os.delete(this.#Oi),this.#Oi=null,this.#Ps?.destroy(),this.#Ps=null}static create(t){const e=this.#Os.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new gc(t)}static get workerSrc(){if(Lh.workerSrc)return Lh.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#js(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return mo(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#js)return this.#js;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class fc{#Vs=new Map;#Us=new Map;#Hs=new Map;#$s=new Map;#Ws=null;constructor(t,e,i,s,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new rc,this.fontLoader=new yl({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.wasmFactory=n.wasmFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=i,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#Gs(t,e=null){const i=this.#Vs.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);return this.#Vs.set(t,s),s}get annotationStorage(){return mo(this,"annotationStorage",new vl)}getRenderingIntent(t,e=jr.ENABLE,i=null,s=!1,n=!1){let a=Lr,r=ml;switch(t){case"any":a=Pr;break;case"display":break;case"print":a=Dr;break;default:uo(`getRenderingIntent - invalid intent: ${t}`)}const o=a&Dr&&i instanceof bl?i:this.annotationStorage;switch(e){case jr.DISABLE:a+=Nr;break;case jr.ENABLE:break;case jr.ENABLE_FORMS:a+=Ir;break;case jr.ENABLE_STORAGE:a+=Or,r=o.serializable;break;default:uo(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(a+=Fr),n&&(a+=Br);const{ids:l,hash:h}=o.modifiedIds;return{renderingIntent:a,cacheKey:[a,r.hash,h].join("_"),annotationStorageSerializable:r,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#Ws?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Us.values())t.push(e._destroy());this.#Us.clear(),this.#Hs.clear(),this.#$s.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.#Vs.clear(),this.filterFactory.destroy(),oc.cleanup(),this._networkStream?.cancelAllRequests(new ko("Worker was terminated.")),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)=>{go(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:i}){i?e.close():(go(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",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:s,contentLength:n}=this._fullReader;return i&&s||(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),{isStreamingSupported:i,isRangeSupported:s,contentLength:n}})),t.on("GetRangeReader",((t,e)=>{go(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then((function({value:t,done:i}){i?e.close():(go(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{i.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}):e.close()})),t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new uc(t,this))})),t.on("DocException",(t=>{e._capability.reject(Fl(t))})),t.on("PasswordRequest",(t=>{this.#Ws=Promise.withResolvers();try{if(!e.onPassword)throw Fl(t);const i=t=>{t instanceof Error?this.#Ws.reject(t):this.#Ws.resolve({password:t})};e.onPassword(i,t.code)}catch(t){this.#Ws.reject(t)}return this.#Ws.promise})),t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)})),t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#Us.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)})),t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in s){const t=s.error;uo(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const n=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new wl(s,n);this.fontLoader.bind(a).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a.fontExtraProperties&&a.data&&(a.data=null),this.commonObjs.resolve(e,a)}));break;case"CopyLocalImage":const{imageRef:r}=s;go(r,"The imageRef must be defined.");for(const t of this.#Us.values())for(const[,i]of t.objs)if(i?.ref===r)return i.dataLen?(this.commonObjs.resolve(e,structuredClone(i)),i.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null})),t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#Us.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()})),t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})})),t.on("FetchBinaryData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");const e=this[t.type];if(!e)throw new Error(`${t.type} not initialized, see the \`useWorkerFetch\` parameter.`);return e.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&uo("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,i=this.#Hs.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#$s.set(i.refStr,t);const s=new pc(e,i,this,this._params.pdfBug);return this.#Us.set(e,s),s}));return this.#Hs.set(e,s),s}getPageIndex(t){return Al(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.#Gs("GetFieldObjects")}hasJSActions(){return this.#Gs("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.#Gs("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.#Gs("GetOptionalContentConfig").then((e=>new Nh(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Vs.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Dh(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#Vs.set(t,i),i}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.#Us.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear(),t||this.fontLoader.clear(),this.#Vs.clear(),this.filterFactory.destroy(!0),oc.cleanup()}}cachedPageNumber(t){if(!Al(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#$s.get(e)??null}}class _c{#qs=null;onContinue=null;onError=null;constructor(t){this.#qs=t}get promise(){return this.#qs.capability.promise}cancel(t=0){this.#qs.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#qs.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#qs;return t.form||t.canvas&&e?.size>0}}class mc{#Ks=null;static#Xs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:c=!1,pageColors:d=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=s,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=c,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new _c(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(mc.#Xs.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.");mc.#Xs.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:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new Ph(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#Ks&&(window.cancelAnimationFrame(this.#Ks),this.#Ks=null),mc.#Xs.delete(this._canvas),t||=new zo(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}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?this.#Ks=window.requestAnimationFrame((()=>{this.#Ks=null,this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),mc.#Xs.delete(this._canvas),this.callback())))}}function vc(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function bc(t){return Math.max(0,Math.min(255,255*t))}class yc{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=bc(t),t,t]}static G_HTML([t]){const e=vc(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(bc)}static RGB_HTML(t){return`#${t.map(vc).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[bc(1-Math.min(1,t+s)),bc(1-Math.min(1,i+s)),bc(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class wc{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");return s.setAttribute("version","1.1"),i||(s.setAttribute("width",`${t}px`),s.setAttribute("height",`${e}px`)),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){po("Abstract method `_createSVG` called.")}}class xc extends wc{_createSVG(t){return document.createElementNS(No,t)}}class Ac{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",(t=>{s.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=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow),i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});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 l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t),r&&lc.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);l.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:i}),o.children?.length>0)h.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);r&&lc.shouldBuildText(c)&&l.push(t),d.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const kc=1e3,Tc=new WeakSet;class Sc{static create(t){switch(t.data.annotationType){case Xr.LINK:return new Cc(t);case Xr.TEXT:return new Rc(t);case Xr.WIDGET:switch(t.data.fieldType){case"Tx":return new Pc(t);case"Btn":return t.data.radioButton?new Ic(t):t.data.checkBox?new Dc(t):new Oc(t);case"Ch":return new Nc(t);case"Sig":return new Lc(t)}return new Mc(t);case Xr.POPUP:return new Fc(t);case Xr.FREETEXT:return new jc(t);case Xr.LINE:return new zc(t);case Xr.SQUARE:return new Vc(t);case Xr.CIRCLE:return new Uc(t);case Xr.POLYLINE:return new Hc(t);case Xr.CARET:return new Wc(t);case Xr.INK:return new Gc(t);case Xr.POLYGON:return new $c(t);case Xr.HIGHLIGHT:return new qc(t);case Xr.UNDERLINE:return new Kc(t);case Xr.SQUIGGLY:return new Xc(t);case Xr.STRIKEOUT:return new Yc(t);case Xr.STAMP:return new Qc(t);case Xr.FILEATTACHMENT:return new Jc(t);default:return new Ec(t)}}}class Ec{#Ys=null;#Qs=!1;#Js=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(i)),s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ec._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Ys||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#Zs(e),this.#Js?.popup.updateEdited(t)}resetEdited(){this.#Ys&&(this.#Zs(this.#Ys.rect),this.#Js?.popup.resetEdited(),this.#Ys=null)}#Zs(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t),e.left=100*(t[0]-r)/n+"%",e.top=100*(a-t[3]+o)/a+"%",0===s?(e.width=100*(t[2]-t[0])/n+"%",e.height=100*(t[3]-t[1])/a+"%"):this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Mc||(n.tabIndex=kc);const{style:a}=n;if(a.zIndex=this.parent.zIndex++,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Fc){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:r,height:o}=this;if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;a.borderRadius=e}else if(this instanceof Ic){const t=`calc(${r}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case Yr:a.borderStyle="solid";break;case Qr:a.borderStyle="dashed";break;case Jr:uo("Unimplemented border style: beveled");break;case Zr:uo("Unimplemented border style: inset");break;case to:a.borderBottomStyle="solid"}const s=e.borderColor||null;s?(this.#Qs=!0,a.borderColor=Ro.makeHexColor(0|s[0],0|s[1],0|s[2])):a.borderWidth=0}const l=Ro.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:c,pageX:d,pageY:u}=s.rawDims;a.left=100*(l[0]-d)/h+"%",a.top=100*(l[1]-u)/c+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/h+"%",a.height=100*o/c+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims;let{width:n,height:a}=this;t%180!=0&&([n,a]=[a,n]),e.style.width=100*n/i+"%",e.style.height=100*a/s+"%",e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=yc[`${n}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:yc[`${n}_rgb`](a)})};return mo(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor: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 i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];if(a){a({detail:{[s]:n},target:t}),delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#Qs){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=s-e,l=n-i,{svgFactory:h}=this,c=h.createElement("svg");c.classList.add("quadrilateralsContainer"),c.setAttribute("width",0),c.setAttribute("height",0);const d=h.createElement("defs");c.append(d);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),d.append(u);for(let i=2,s=t.length;i<s;i+=8){const s=t[i],a=t[i+1],c=t[i+2],d=t[i+3],p=h.createElement("rect"),g=(c-e)/o,f=(n-a)/l,_=(s-c)/o,m=(a-d)/l;p.setAttribute("x",g),p.setAttribute("y",f),p.setAttribute("width",_),p.setAttribute("height",m),u.append(p),r?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${f}" width="${_}" height="${m}"/>`)}this.#Qs&&(r.push("</g></svg>')"),a.backgroundImage=r.join("")),this.container.append(c),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#Js=new Fc({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){po("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Tc.has(r)?i.push({id:n,exportValue:s,domElement:r}):uo(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Tc.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class Cc extends Ec{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),s=!0):t.action?(this._bindNamedAction(i,t.action),s=!0):t.attachment?(this.#tn(i,t.attachment,t.attachmentDest),s=!0):t.setOCGState?(this.#en(i,t.setOCGState),s=!0):t.dest?(this._bindLink(i,t.dest),s=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),s=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),s=!0):this.isTooltipOnly&&!s&&(this._bindLink(i,""),s=!0)),this.container.classList.add("linkAnnotation"),s&&this.container.append(i),this.container}#in(){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.#in()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#in()}#tn(t,e,i=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#in()}#en(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#in()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}}),!1))}t.onclick||(t.onclick=()=>!1),this.#in()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#in(),!this._fieldObjects)return uo('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}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 i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Tc.has(i)?i.dispatchEvent(new Event("resetform")):uo(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class Rc extends Ec{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 Mc extends Ec{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Eo.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,n,a,s),"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":Ro.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,n=t.style;let a;const r=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(Mr*s))||1);a=Math.min(s,r(e/Mr))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(s,r(t/Mr))}n.fontSize=`calc(${a}px * var(--total-scale-factor))`,n.color=Ro.makeHexColor(i[0],i[1],i[2]),null!==this.data.textAlignment&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class Pc extends Mc{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=i),n.setValue(a.id,{[s]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.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?(i=document.createElement("textarea"),i.textContent=r??n,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type=this.data.password?"password":"text",i.setAttribute("value",r??n),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),Tc.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=kc,this._setRequired(i,this.data.required),a&&(i.maxLength=a),i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value}),this.setPropertyOnSiblings(i,"value",s.target.value,"value"),o.formattedValue=null})),i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null}));let l=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue),o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)})),i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s,null!=s&&i.target!==document.activeElement&&(i.target.value=s),t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",s);let a=o.userValue;!a||a.length<=s||(a=a.slice(0,s),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(s,i)})),i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:s}=t.target;o.lastCommittedValue!==s&&(o.lastCommittedValue=s,o.userValue=s,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))}));const s=l;l=null,i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i,o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),s(t)})),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})})),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}if(l&&i.addEventListener("blur",l),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--total-scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Lc extends Mc{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Dc extends Mc{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof s&&(s="Off"!==s,t.setValue(i,{value:s})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return Tc.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=kc,n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i),t.setValue(s.id,{value:i})}t.setValue(i,{value:a})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue})),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Ic extends Mc{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s&&(s=s!==e.buttonValue,t.setValue(i,{value:s})),s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");if(Tc.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.tabIndex=kc,n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue})),this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e),t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Oc extends Cc{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 Nc extends Mc{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Tc.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=kc;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(s.size=this.data.options.length,this.data.multiSelect&&(s.multiple=!0)),s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),n=!1),s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),s.prepend(t),a=()=>{t.remove(),s.removeEventListener("input",a),a=null},s.addEventListener("input",a)}const r=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let o=r(!1);const l=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};return this.enableScripting&&this.hasJSActions?(s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,l=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=l.has(t.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;if(n[a].selected=!1,s.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:l(i)}),o=r(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(i){const{index:n,displayValue:a,exportValue:h}=i.detail.insert,c=s.children[n],d=document.createElement("option");d.textContent=a,d.value=h,c?c.before(d):s.append(d),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e,n.value=i,s.append(n)}s.options.length>0&&(s.options[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)})),s.addEventListener("input",(i=>{const s=r(!0),n=r(!1);t.setValue(e,{value:s}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))):s.addEventListener("input",(function(i){t.setValue(e,{value:r(!0)})})),this.data.combo&&this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Fc extends Ec{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:Ec._hasPopupData(e)}),this.elements=i,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Bc({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 i of this.elements)i.popup=t,i.container.ariaHasPopup="dialog",e.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",e.map((t=>`${Do}${t}`)).join(",")),this.container}}class Bc{#sn=this.#nn.bind(this);#an=this.#rn.bind(this);#on=this.#ln.bind(this);#hn=this.#cn.bind(this);#dn=null;#_t=null;#un=null;#pn=null;#gn=null;#fn=null;#_n=null;#mn=!1;#vn=null;#E=null;#bn=null;#yn=null;#wn=null;#Ys=null;#xn=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:c}){this.#_t=t,this.#wn=s,this.#un=a,this.#yn=r,this.#fn=o,this.#dn=e,this.#bn=l,this.#_n=h,this.#gn=i,this.#pn=qo.toDateObject(n),this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger)t.addEventListener("click",this.#hn),t.addEventListener("mouseenter",this.#on),t.addEventListener("mouseleave",this.#an),t.classList.add("popupTriggerArea");for(const t of i)t.container?.addEventListener("keydown",this.#sn);this.#_t.hidden=!0,c&&this.#cn()}render(){if(this.#vn)return;const t=this.#vn=document.createElement("div");if(t.className="popup",this.#dn){const e=t.style.outlineColor=Ro.makeHexColor(...this.#dn);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");if(e.append(i),({dir:i.dir,str:i.textContent}=this.#wn),t.append(e),this.#pn){const t=document.createElement("span");t.classList.add("popupDate"),t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#pn.valueOf()})),e.append(t)}const s=this.#An;if(s)Ac.render({xfaHtml:s,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const e=this._formatContents(this.#un);t.append(e)}this.#_t.append(t)}get#An(){const t=this.#yn,e=this.#un;return!t?.str||e?.str&&e.str!==t.str?null:this.#yn.html||null}get#kn(){return this.#An?.attributes?.style?.fontSize||0}get#Tn(){return this.#An?.attributes?.style?.color||null}#Sn(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#Tn,fontSize:this.#kn?`calc(${this.#kn}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent"),i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t<e;++t){const n=s[t];i.append(document.createTextNode(n)),t<e-1&&i.append(document.createElement("br"))}return i}#nn(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#mn)&&this.#cn()}updateEdited({rect:t,popupContent:e}){this.#Ys||={contentsObj:this.#un,richText:this.#yn},t&&(this.#E=null),e&&(this.#yn=this.#Sn(e),this.#un=null),this.#vn?.remove(),this.#vn=null}resetEdited(){this.#Ys&&(({contentsObj:this.#un,richText:this.#yn}=this.#Ys),this.#Ys=null,this.#vn?.remove(),this.#vn=null,this.#E=null)}#En(){if(null!==this.#E)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:s,pageY:n}}}=this.#fn;let a=!!this.#_n,r=a?this.#_n:this.#bn;for(const t of this.#gn)if(!r||null!==Ro.intersect(t.data.rect,r)){r=t.data.rect,a=!0;break}const o=Ro.normalizeRect([r[0],t[3]-r[1]+t[1],r[2],t[3]-r[3]+t[1]]),l=a?r[2]-r[0]+5:0,h=o[0]+l,c=o[1];this.#E=[100*(h-s)/e,100*(c-n)/i];const{style:d}=this.#_t;d.left=`${this.#E[0]}%`,d.top=`${this.#E[1]}%`}#cn(){this.#mn=!this.#mn,this.#mn?(this.#ln(),this.#_t.addEventListener("click",this.#hn),this.#_t.addEventListener("keydown",this.#sn)):(this.#rn(),this.#_t.removeEventListener("click",this.#hn),this.#_t.removeEventListener("keydown",this.#sn))}#ln(){this.#vn||this.render(),this.isVisible?this.#mn&&this.#_t.classList.add("focused"):(this.#En(),this.#_t.hidden=!1,this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex)+1e3)}#rn(){this.#_t.classList.remove("focused"),!this.#mn&&this.isVisible&&(this.#_t.hidden=!0,this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex)-1e3)}forceHide(){this.#xn=this.isVisible,this.#xn&&(this.#_t.hidden=!0)}maybeShow(){this.#xn&&(this.#vn||this.#ln(),this.#xn=!1,this.#_t.hidden=!1)}get isVisible(){return!1===this.#_t.hidden}}class jc extends Ec{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=zr.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 i=document.createElement("span");i.textContent=e,t.append(i)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class zc extends Ec{#Cn=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=this.#Cn=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"),s.append(n),this.container.append(s),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Cn}addHighlightArea(){this.container.classList.add("highlightArea")}}class Vc extends Ec{#Rn=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=t.borderStyle.width,a=this.#Rn=this.svgFactory.createElement("svg:rect");return a.setAttribute("x",n/2),a.setAttribute("y",n/2),a.setAttribute("width",e-n),a.setAttribute("height",i-n),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),s.append(a),this.container.append(s),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Rn}addHighlightArea(){this.container.classList.add("highlightArea")}}class Uc extends Ec{#Mn=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=t.borderStyle.width,a=this.#Mn=this.svgFactory.createElement("svg:ellipse");return a.setAttribute("cx",e/2),a.setAttribute("cy",i/2),a.setAttribute("rx",e/2-n/2),a.setAttribute("ry",i/2-n/2),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),s.append(a),this.container.append(s),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Mn}addHighlightArea(){this.container.classList.add("highlightArea")}}class Hc extends Ec{#Pn=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:i,popupRef:s},width:n,height:a}=this;if(!e)return this.container;const r=this.svgFactory.create(n,a,!0);let o=[];for(let i=0,s=e.length;i<s;i+=2){const s=e[i]-t[0],n=t[3]-e[i+1];o.push(`${s},${n}`)}o=o.join(" ");const l=this.#Pn=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",o),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),r.append(l),this.container.append(r),!s&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Pn}addHighlightArea(){this.container.classList.add("highlightArea")}}class $c extends Hc{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Wc extends Ec{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 Gc extends Ec{#Ln=null;#Dn=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?zr.HIGHLIGHT:zr.INK}#In(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:i,borderStyle:s,popupRef:n}}=this,{transform:a,width:r,height:o}=this.#In(e,t),l=this.svgFactory.create(r,o,!0),h=this.#Ln=this.svgFactory.createElement("svg:g");l.append(h),h.setAttribute("stroke-width",s.width||1),h.setAttribute("stroke-linecap","round"),h.setAttribute("stroke-linejoin","round"),h.setAttribute("stroke-miterlimit",10),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),h.setAttribute("transform",a);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#Dn.push(e),e.setAttribute("points",i[t].join(",")),h.append(e)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:s}=t,n=this.#Ln;if(e>=0&&n.setAttribute("stroke-width",e||1),i)for(let t=0,e=this.#Dn.length;t<e;t++)this.#Dn[t].setAttribute("points",i[t].join(","));if(s){const{transform:t,width:e,height:i}=this.#In(this.data.rotation,s);n.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`),n.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#Dn}addHighlightArea(){this.container.classList.add("highlightArea")}}class qc extends Ec{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=zr.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class Kc extends Ec{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 Xc extends Ec{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 Yc extends Ec{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 Qc extends Ec{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=zr.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Jc extends Ec{#On=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 i;e.hasAppearance||0===e.fillAlpha?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)),i.addEventListener("dblclick",this.#Nn.bind(this)),this.#On=i;const{isMac:s}=Eo.platform;return t.addEventListener("keydown",(t=>{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Nn()})),!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#On}addHighlightArea(){this.container.classList.add("highlightArea")}#Nn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Zc{#Fn=null;#Bn=null;#jn=new Map;#zn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t,this.#Fn=e,this.#Bn=i,this.#zn=r||null,this.page=n,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#jn.size>0}async#Vn(t,e){const i=t.firstChild||t,s=i.id=`${Do}${e}`,n=await(this.#zn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t),this.#Fn?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;Qo(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new xc,annotationStorage:t.annotationStorage||new vl,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===Xr.POPUP;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;n.data=t;const i=Sc.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden"),await this.#Vn(a,t.id),i._isEditable&&(this.#jn.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}this.#Un()}async addLinkAnnotations(t,e){const i={data:null,layer:this.div,linkService:e,svgFactory:new xc,parent:this};for(const e of t){e.borderStyle||=Zc._defaultBorderStyle,i.data=e;const t=Sc.create(i);if(!t.isRenderable)continue;const s=t.render();await this.#Vn(s,e.id)}}update({viewport:t}){const e=this.div;this.viewport=t,Qo(e,{rotation:t.rotation}),this.#Un(),e.hidden=!1}#Un(){if(!this.#Bn)return;const t=this.div;for(const[e,i]of this.#Bn){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i);const a=this.#jn.get(e);a&&(a._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(e,s.id,i),a._hasNoCanvas=!1):a.canvas=i)}this.#Bn.clear()}getEditableAnnotations(){return Array.from(this.#jn.values())}getEditableAnnotation(t){return this.#jn.get(t)}static get _defaultBorderStyle(){return mo(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:Yr,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const td=/\r\n?|\n/g;class ed extends dl{#dn;#Hn="";#$n=`${this.id}-editor`;#Wn=null;#kn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=ed.prototype,e=t=>t.isEmpty(),i=ll.TRANSLATE_SMALL,s=ll.TRANSLATE_BIG;return mo(this,"_keyboardManager",new rl([[["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:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}]]))}static _type="freetext";static _editorType=zr.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#dn=t.color||ed._defaultColor||dl._defaultLineColor,this.#kn=t.fontSize||ed._defaultFontSize}static initialize(t,e){dl.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case Vr.FREETEXT_SIZE:ed._defaultFontSize=e;break;case Vr.FREETEXT_COLOR:ed._defaultColor=e}}updateParams(t,e){switch(t){case Vr.FREETEXT_SIZE:this.#Gn(e);break;case Vr.FREETEXT_COLOR:this.#qn(e)}}static get defaultPropertiesToUpdate(){return[[Vr.FREETEXT_SIZE,ed._defaultFontSize],[Vr.FREETEXT_COLOR,ed._defaultColor||dl._defaultLineColor]]}get propertiesToUpdate(){return[[Vr.FREETEXT_SIZE,this.#kn],[Vr.FREETEXT_COLOR,this.#dn]]}#Gn(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#kn)*this.parentScale),this.#kn=t,this.#Kn()},i=this.#kn;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Vr.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#qn(t){const e=t=>{this.#dn=this.editorDiv.style.color=t},i=this.#dn;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Vr.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-ed._internalPadding*t,-(ed._internalPadding+this.#kn)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#Wn=new AbortController;const t=this._uiManager.combinedSignal(this.#Wn);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return!!super.disableEditMode()&&(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#$n),this._isDraggable=!0,this.#Wn?.abort(),this.#Wn=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0)}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#Xn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(ed.#Yn(i)),e=i);return t.join("\n")}#Kn(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=s,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#Hn,e=this.#Hn=this.#Xn().trimEnd();if(t===e)return;const i=t=>{this.#Hn=t,t?(this.#Qn(),this._uiManager.rebuild(this),this.#Kn()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#Kn()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){ed._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(this._isCopy||this.annotationElementId)&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#$n),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#kn}px * var(--total-scale-factor))`,i.color=this.#dn,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(n[0]-h)/o,u=e+this.height-(n[1]-c)/l;break;case 90:d=t+(n[0]-h)/o,u=e-(n[1]-c)/l,[a,r]=[r,-a];break;case 180:d=t-this.width+(n[0]-h)/o,u=e-(n[1]-c)/l,[a,r]=[-a,-r];break;case 270:d=t+(n[0]-h-this.height*l)/o,u=e+(n[1]-c-this.width*o)/l,[a,r]=[-r,a]}this.setAt(d*i,u*s,a,r)}else this._moveAfterPaste(t,e);this.#Qn(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#Yn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(td,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=ed.#Jn(e.getData("text")||"").replaceAll(td,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n"))return a.insertNode(document.createTextNode(s)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(h.push(r.nodeValue.slice(o).replaceAll(td,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(ed.#Yn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(td,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(ed.#Yn(i))}this.#Hn=`${l.join("\n")}${s}${h.join("\n")}`,this.#Qn();const c=new Range;let d=Math.sumPrecise(l.map((t=>t.length)));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(d<=e){c.setStart(t,d),c.setEnd(t,d);break}d-=e}n.removeAllRanges(),n.addRange(c)}#Qn(){if(this.editorDiv.replaceChildren(),this.#Hn)for(const t of this.#Hn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#Zn(){return this.#Hn.replaceAll(" "," ")}static#Jn(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof jc){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:c}}}=t;if(!l||0===l.length)return null;s=t={annotationType:zr.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);return n.#kn=t.fontSize,n.#dn=Ro.makeHexColor(...t.color),n.#Hn=ed.#Jn(t.value),n.annotationElementId=t.id||null,n._initialData=s,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=ed._internalPadding*this.parentScale,i=this.getRect(e,e),s=dl._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#dn),n={annotationType:zr.FREETEXT,color:s,fontSize:this.#kn,value:this.#Zn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?(n.isCopy=!0,n):this.annotationElementId&&!this.#ta(n)?null:(n.id=this.annotationElementId,n)}#ta(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#kn}px * var(--total-scale-factor))`,i.color=this.#dn,e.replaceChildren();for(const t of this.#Hn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}const s=ed._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(s,s),popupContent:this.#Hn}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class id{static PRECISION=1e-4;toSVGPath(){po("Abstract method `toSVGPath` must be implemented.")}get box(){po("Abstract getter `box` must be implemented.")}serialize(t,e){po("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r]*s,a[r+1]=i+t[r+1]*n;return a}static _rescaleAndSwap(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r+1]*s,a[r+1]=i+t[r]*n;return a}static _translate(t,e,i,s){s||=new Float32Array(t.length);for(let n=0,a=t.length;n<a;n+=2)s[n]=e+t[n],s[n+1]=i+t[n+1];return s}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,s,n){switch(n){case 90:return[1-e/i,t/s];case 180:return[1-t/i,1-e/s];case 270:return[e/i,1-t/s];default:return[t/i,e/s]}}static _normalizePagePoint(t,e,i){switch(i){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,i,s,n,a){return[(t+5*i)/6,(e+5*s)/6,(5*i+n)/6,(5*s+a)/6,(i+n)/2,(s+a)/2]}}class sd{#ea;#ia=[];#sa;#na;#aa=[];#ra=new Float32Array(18);#oa;#la;#ha;#ca;#da;#ua;#pa=[];static#ga=8;static#fa=2;static#_a=sd.#ga+sd.#fa;constructor({x:t,y:e},i,s,n,a,r=0){this.#ea=i,this.#ua=n*s,this.#na=a,this.#ra.set([NaN,NaN,NaN,NaN,t,e],6),this.#sa=r,this.#ca=sd.#ga*s,this.#ha=sd.#_a*s,this.#da=s,this.#pa.push(t,e)}isEmpty(){return isNaN(this.#ra[8])}#ma(){const t=this.#ra.subarray(4,6),e=this.#ra.subarray(16,18),[i,s,n,a]=this.#ea;return[(this.#oa+(t[0]-e[0])/2-i)/n,(this.#la+(t[1]-e[1])/2-s)/a,(this.#oa+(e[0]-t[0])/2-i)/n,(this.#la+(e[1]-t[1])/2-s)/a]}add({x:t,y:e}){this.#oa=t,this.#la=e;const[i,s,n,a]=this.#ea;let[r,o,l,h]=this.#ra.subarray(8,12);const c=t-l,d=e-h,u=Math.hypot(c,d);if(u<this.#ha)return!1;const p=u-this.#ca,g=p/u,f=g*c,_=g*d;let m=r,v=o;r=l,o=h,l+=f,h+=_,this.#pa?.push(t,e);const b=f/p,y=-_/p*this.#ua,w=b*this.#ua;if(this.#ra.set(this.#ra.subarray(2,8),0),this.#ra.set([l+y,h+w],4),this.#ra.set(this.#ra.subarray(14,18),12),this.#ra.set([l-y,h-w],16),isNaN(this.#ra[6]))return 0===this.#aa.length&&(this.#ra.set([r+y,o+w],2),this.#aa.push(NaN,NaN,NaN,NaN,(r+y-i)/n,(o+w-s)/a),this.#ra.set([r-y,o-w],14),this.#ia.push(NaN,NaN,NaN,NaN,(r-y-i)/n,(o-w-s)/a)),this.#ra.set([m,v,r,o,l,h],6),!this.isEmpty();this.#ra.set([m,v,r,o,l,h],6);return Math.abs(Math.atan2(v-o,m-r)-Math.atan2(_,f))<Math.PI/2?([r,o,l,h]=this.#ra.subarray(2,6),this.#aa.push(NaN,NaN,NaN,NaN,((r+l)/2-i)/n,((o+h)/2-s)/a),[r,o,m,v]=this.#ra.subarray(14,18),this.#ia.push(NaN,NaN,NaN,NaN,((m+r)/2-i)/n,((v+o)/2-s)/a),!0):([m,v,r,o,l,h]=this.#ra.subarray(0,6),this.#aa.push(((m+5*r)/6-i)/n,((v+5*o)/6-s)/a,((5*r+l)/6-i)/n,((5*o+h)/6-s)/a,((r+l)/2-i)/n,((o+h)/2-s)/a),[l,h,r,o,m,v]=this.#ra.subarray(12,18),this.#ia.push(((m+5*r)/6-i)/n,((v+5*o)/6-s)/a,((5*r+l)/6-i)/n,((5*o+h)/6-s)/a,((r+l)/2-i)/n,((o+h)/2-s)/a),!0)}toSVGPath(){if(this.isEmpty())return"";const t=this.#aa,e=this.#ia;if(isNaN(this.#ra[6])&&!this.isEmpty())return this.#va();const i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#ba(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return this.#ya(i),i.join(" ")}#va(){const[t,e,i,s]=this.#ea,[n,a,r,o]=this.#ma();return`M${(this.#ra[2]-t)/i} ${(this.#ra[3]-e)/s} L${(this.#ra[4]-t)/i} ${(this.#ra[5]-e)/s} L${n} ${a} L${r} ${o} L${(this.#ra[16]-t)/i} ${(this.#ra[17]-e)/s} L${(this.#ra[14]-t)/i} ${(this.#ra[15]-e)/s} Z`}#ya(t){const e=this.#ia;t.push(`L${e[4]} ${e[5]} Z`)}#ba(t){const[e,i,s,n]=this.#ea,a=this.#ra.subarray(4,6),r=this.#ra.subarray(16,18),[o,l,h,c]=this.#ma();t.push(`L${(a[0]-e)/s} ${(a[1]-i)/n} L${o} ${l} L${h} ${c} L${(r[0]-e)/s} ${(r[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,a){return new nd(t,e,i,s,n,a)}getOutlines(){const t=this.#aa,e=this.#ia,i=this.#ra,[s,n,a,r]=this.#ea,o=new Float32Array((this.#pa?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2)o[t]=(this.#pa[t]-s)/a,o[t+1]=(this.#pa[t+1]-n)/r;if(o[o.length-2]=(this.#oa-s)/a,o[o.length-1]=(this.#la-n)/r,isNaN(i[6])&&!this.isEmpty())return this.#wa(o);const l=new Float32Array(this.#aa.length+24+this.#ia.length);let h=t.length;for(let e=0;e<h;e+=2)isNaN(t[e])?l[e]=l[e+1]=NaN:(l[e]=t[e],l[e+1]=t[e+1]);h=this.#xa(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(l[h]=l[h+1]=NaN,h+=2):(l[h]=e[t+i],l[h+1]=e[t+i+1],h+=2);return this.#Aa(l,h),this.newFreeDrawOutline(l,o,this.#ea,this.#da,this.#sa,this.#na)}#wa(t){const e=this.#ra,[i,s,n,a]=this.#ea,[r,o,l,h]=this.#ma(),c=new Float32Array(36);return c.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/a,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/a,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/a],0),this.newFreeDrawOutline(c,t,this.#ea,this.#da,this.#sa,this.#na)}#Aa(t,e){const i=this.#ia;return t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e),e+6}#xa(t,e){const i=this.#ra.subarray(4,6),s=this.#ra.subarray(16,18),[n,a,r,o]=this.#ea,[l,h,c,d]=this.#ma();return t.set([NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o],e),e+24}}class nd extends id{#ea;#ka=new Float32Array(4);#sa;#na;#pa;#da;#Ta;constructor(t,e,i,s,n,a){super(),this.#Ta=t,this.#pa=e,this.#ea=i,this.#da=s,this.#sa=n,this.#na=a,this.lastPoint=[NaN,NaN],this.#Sa(a);const[r,o,l,h]=this.#ka;for(let e=0,i=t.length;e<i;e+=2)t[e]=(t[e]-r)/l,t[e+1]=(t[e+1]-o)/h;for(let t=0,i=e.length;t<i;t+=2)e[t]=(e[t]-r)/l,e[t+1]=(e[t+1]-o)/h}toSVGPath(){const t=[`M${this.#Ta[4]} ${this.#Ta[5]}`];for(let e=6,i=this.#Ta.length;e<i;e+=6)isNaN(this.#Ta[e])?t.push(`L${this.#Ta[e+4]} ${this.#Ta[e+5]}`):t.push(`C${this.#Ta[e]} ${this.#Ta[e+1]} ${this.#Ta[e+2]} ${this.#Ta[e+3]} ${this.#Ta[e+4]} ${this.#Ta[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,i,s],n){const a=i-t,r=s-e;let o,l;switch(n){case 0:o=id._rescale(this.#Ta,t,s,a,-r),l=id._rescale(this.#pa,t,s,a,-r);break;case 90:o=id._rescaleAndSwap(this.#Ta,t,e,a,r),l=id._rescaleAndSwap(this.#pa,t,e,a,r);break;case 180:o=id._rescale(this.#Ta,i,e,-a,r),l=id._rescale(this.#pa,i,e,-a,r);break;case 270:o=id._rescaleAndSwap(this.#Ta,i,s,-a,-r),l=id._rescaleAndSwap(this.#pa,i,s,-a,-r)}return{outline:Array.from(o),points:[Array.from(l)]}}#Sa(t){const e=this.#Ta;let i=e[4],s=e[5];const n=[i,s,i,s];let a=i,r=s;const o=t?Math.max:Math.min;for(let t=6,l=e.length;t<l;t+=6){const l=e[t+4],h=e[t+5];if(isNaN(e[t]))Ro.pointBoundingBox(l,h,n),r<h?(a=l,r=h):r===h&&(a=o(a,l));else{const l=[1/0,1/0,-1/0,-1/0];Ro.bezierBoundingBox(i,s,...e.slice(t,t+6),l),Ro.rectBoundingBox(...l,n),r<l[3]?(a=l[2],r=l[3]):r===l[3]&&(a=o(a,l[2]))}i=l,s=h}const l=this.#ka;l[0]=n[0]-this.#sa,l[1]=n[1]-this.#sa,l[2]=n[2]-n[0]+2*this.#sa,l[3]=n[3]-n[1]+2*this.#sa,this.lastPoint=[a,r]}get box(){return this.#ka}newOutliner(t,e,i,s,n,a=0){return new sd(t,e,i,s,n,a)}getNewOutline(t,e){const[i,s,n,a]=this.#ka,[r,o,l,h]=this.#ea,c=n*l,d=a*h,u=i*l+r,p=s*h+o,g=this.newOutliner({x:this.#pa[0]*c+u,y:this.#pa[1]*d+p},this.#ea,this.#da,t,this.#na,e??this.#sa);for(let t=2;t<this.#pa.length;t+=2)g.add({x:this.#pa[t]*c+u,y:this.#pa[t+1]*d+p});return g.getOutlines()}}class ad{#ea;#Ea;#Ca=[];#Ra=[];constructor(t,e=0,i=0,s=!0){const n=[1/0,1/0,-1/0,-1/0],a=1e-4;for(const{x:i,y:s,width:r,height:o}of t){const t=Math.floor((i-e)/a)*a,l=Math.ceil((i+r+e)/a)*a,h=Math.floor((s-e)/a)*a,c=Math.ceil((s+o+e)/a)*a,d=[t,h,c,!0],u=[l,h,c,!1];this.#Ca.push(d,u),Ro.rectBoundingBox(t,h,l,c,n)}const r=n[2]-n[0]+2*i,o=n[3]-n[1]+2*i,l=n[0]-i,h=n[1]-i,c=this.#Ca.at(s?-1:-2),d=[c[0],c[2]];for(const t of this.#Ca){const[e,i,s]=t;t[0]=(e-l)/r,t[1]=(i-h)/o,t[2]=(s-h)/o}this.#ea=new Float32Array([l,h,r,o]),this.#Ea=d}getOutlines(){this.#Ca.sort(((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#Ca)e[3]?(t.push(...this.#Ma(e)),this.#Pa(e)):(this.#La(e),t.push(...this.#Ma(e)));return this.#Da(t)}#Da(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t<s;t+=2){const s=e[t][2],n=e[t+1][2];s.push(n),n.push(s),i.add(s),i.add(n)}const s=[];let n;for(;i.size>0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,c=a;for(n=[e,r],s.push(n);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,a,r,o,l]=t,h!==e&&(n.push(h,c,e,c===a?a:r),h=e),c=c===a?r:a}n.push(h,c)}return new rd(s,this.#ea,this.#Ea)}#Ia(t){const e=this.#Ra;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a<t?i=n+1:s=n-1}return s+1}#Pa([,t,e]){const i=this.#Ia(t);this.#Ra.splice(i,0,[t,e])}#La([,t,e]){const i=this.#Ia(t);for(let s=i;s<this.#Ra.length;s++){const[i,n]=this.#Ra[s];if(i!==t)break;if(i===t&&n===e)return void this.#Ra.splice(s,1)}for(let s=i-1;s>=0;s--){const[i,n]=this.#Ra[s];if(i!==t)break;if(i===t&&n===e)return void this.#Ra.splice(s,1)}}#Ma(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#Ia(s);for(let t=0;t<a;t++){const[i,s]=this.#Ra[t];for(let t=0,a=n.length;t<a;t++){const[,r,o]=n[t];if(!(s<=r||o<=i))if(r>=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1),t--,a--}else n[t][2]=i,o>s&&n.push([e,s,o])}}return n}}class rd extends id{#ea;#Oa;constructor(t,e,i){super(),this.#Oa=t,this.#ea=e,this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Oa){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n<e.length;n+=2){const a=e[n],r=e[n+1];a===i?(t.push(`V${r}`),s=r):r===s&&(t.push(`H${a}`),i=a)}t.push("Z")}return t.join(" ")}serialize([t,e,i,s],n){const a=[],r=i-t,o=s-e;for(const e of this.#Oa){const i=new Array(e.length);for(let n=0;n<e.length;n+=2)i[n]=t+e[n]*r,i[n+1]=s-e[n+1]*o;a.push(i)}return a}get box(){return this.#ea}get classNamesForOutlining(){return["highlightOutline"]}}class od extends sd{newFreeDrawOutline(t,e,i,s,n,a){return new ld(t,e,i,s,n,a)}}class ld extends nd{newOutliner(t,e,i,s,n,a=0){return new od(t,e,i,s,n,a)}}class hd{#Na=null;#Fa=null;#Ba;#ja=null;#za=!1;#Va=!1;#a=null;#Ua;#Ha=null;#_=null;#$a;static#Wa=null;static get _keyboardManager(){return mo(this,"_keyboardManager",new rl([[["Escape","mac+Escape"],hd.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],hd.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],hd.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],hd.prototype._moveToPrevious],[["Home","mac+Home"],hd.prototype._moveToBeginning],[["End","mac+End"],hd.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#Va=!1,this.#$a=Vr.HIGHLIGHT_COLOR,this.#a=t):(this.#Va=!0,this.#$a=Vr.HIGHLIGHT_DEFAULT_COLOR),this.#_=t?._uiManager||e,this.#Ua=this.#_._eventBus,this.#Ba=t?.color||this.#_?.highlightColors.values().next().value||"#FFFF98",hd.#Wa||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Na=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=this.#_._signal;t.addEventListener("click",this.#Ga.bind(this),{signal:e}),t.addEventListener("keydown",this.#nn.bind(this),{signal:e});const i=this.#Fa=document.createElement("span");return i.className="swatch",i.setAttribute("aria-hidden",!0),i.style.backgroundColor=this.#Ba,t.append(i),t}renderMainDropdown(){const t=this.#ja=this.#qa();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#qa(){const t=document.createElement("div"),e=this.#_._signal;t.addEventListener("contextmenu",Wo,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[i,s]of this.#_.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",s),n.title=i,n.setAttribute("data-l10n-id",hd.#Wa[i]);const a=document.createElement("span");n.append(a),a.className="swatch",a.style.backgroundColor=s,n.setAttribute("aria-selected",s===this.#Ba),n.addEventListener("click",this.#Ka.bind(this,s),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#nn.bind(this),{signal:e}),t}#Ka(t,e){e.stopPropagation(),this.#Ua.dispatch("switchannotationeditorparams",{source:this,type:this.#$a,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#Na)return void this.#Ga(t);const e=t.target.getAttribute("data-color");e&&this.#Ka(e,t)}_moveToNext(t){this.#Xa?t.target!==this.#Na?t.target.nextSibling?.focus():this.#ja.firstChild?.focus():this.#Ga(t)}_moveToPrevious(t){t.target!==this.#ja?.firstChild&&t.target!==this.#Na?(this.#Xa||this.#Ga(t),t.target.previousSibling?.focus()):this.#Xa&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Xa?this.#ja.firstChild?.focus():this.#Ga(t)}_moveToEnd(t){this.#Xa?this.#ja.lastChild?.focus():this.#Ga(t)}#nn(t){hd._keyboardManager.exec(this,t)}#Ga(t){if(this.#Xa)return void this.hideDropdown();if(this.#za=0===t.detail,this.#Ha||(this.#Ha=new AbortController,window.addEventListener("pointerdown",this.#c.bind(this),{signal:this.#_.combinedSignal(this.#Ha)})),this.#ja)return void this.#ja.classList.remove("hidden");const e=this.#ja=this.#qa();this.#Na.append(e)}#c(t){this.#ja?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#ja?.classList.add("hidden"),this.#Ha?.abort(),this.#Ha=null}get#Xa(){return this.#ja&&!this.#ja.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#Va||(this.#Xa?(this.hideDropdown(),this.#Na.focus({preventScroll:!0,focusVisible:this.#za})):this.#a?.unselect())}updateColor(t){if(this.#Fa&&(this.#Fa.style.backgroundColor=t),!this.#ja)return;const e=this.#_.highlightColors.values();for(const i of this.#ja.children)i.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#Na?.remove(),this.#Na=null,this.#Fa=null,this.#ja?.remove(),this.#ja=null}}class cd extends dl{#Ya=null;#Qa=0;#Ja;#Za=null;#n=null;#tr=null;#er=null;#ir=0;#sr=null;#nr=null;#y=null;#ar=!1;#Ea=null;#rr;#or=null;#lr="";#ua;#hr="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=zr.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=cd.prototype;return mo(this,"_keyboardManager",new rl([[["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||cd._defaultColor,this.#ua=t.thickness||cd._defaultThickness,this.#rr=t.opacity||cd._defaultOpacity,this.#Ja=t.boxes||null,this.#hr=t.methodOfCreation||"",this.#lr=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#ar=!0,this.#cr(t),this.#dr()):this.#Ja&&(this.#Ya=t.anchorNode,this.#Qa=t.anchorOffset,this.#er=t.focusNode,this.#ir=t.focusOffset,this.#ur(),this.#dr(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#ar?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#ua,methodOfCreation:this.#hr}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#ur(){const t=new ad(this.#Ja,.001);this.#nr=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#nr.box;const e=new ad(this.#Ja,.0025,.001,"ltr"===this._uiManager.direction);this.#tr=e.getOutlines();const{lastPoint:i}=this.#tr;this.#Ea=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#cr({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#nr=t;if(this.#tr=t.getNewOutline(this.#ua/2+1.5,.0025),e>=0)this.#y=e,this.#Za=i,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#or=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#tr.box,path:{d:this.#tr.toSVGPath()}},!0);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#y,{bbox:cd.#pr(this.#nr.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#or,{bbox:cd.#pr(this.#tr.box,e),path:{d:this.#tr.toSVGPath()}})}const[s,n,a,r]=t.box;switch(this.rotation){case 0:this.x=s,this.y=n,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-s,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-s,this.y=1-n,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=s,this.width=a*e/t,this.height=r*t/e;break}}const{lastPoint:o}=this.#tr;this.#Ea=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){dl.initialize(t,e),cd._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case Vr.HIGHLIGHT_DEFAULT_COLOR:cd._defaultColor=e;break;case Vr.HIGHLIGHT_THICKNESS:cd._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Ea}updateParams(t,e){switch(t){case Vr.HIGHLIGHT_COLOR:this.#qn(e);break;case Vr.HIGHLIGHT_THICKNESS:this.#gr(e)}}static get defaultPropertiesToUpdate(){return[[Vr.HIGHLIGHT_DEFAULT_COLOR,cd._defaultColor],[Vr.HIGHLIGHT_THICKNESS,cd._defaultThickness]]}get propertiesToUpdate(){return[[Vr.HIGHLIGHT_COLOR,this.color||cd._defaultColor],[Vr.HIGHLIGHT_THICKNESS,this.#ua||cd._defaultThickness],[Vr.HIGHLIGHT_FREE,this.#ar]]}#qn(t){const e=(t,e)=>{this.color=t,this.#rr=e,this.parent?.drawLayer.updateProperties(this.#y,{root:{fill:t,"fill-opacity":e}}),this.#n?.updateColor(t)},i=this.color,s=this.#rr;this.addCommands({cmd:e.bind(this,t,cd._defaultOpacity),undo:e.bind(this,i,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Vr.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#gr(t){const e=this.#ua,i=t=>{this.#ua=t,this.#fr(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Vr.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.#n=new hd({editor:this}),t.addColorPicker(this.#n)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#_r())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#_r())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#mr(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#dr(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#mr():t&&(this.#dr(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#fr(t){if(!this.#ar)return;this.#cr({highlightOutlines:this.#nr.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#mr(){null!==this.#y&&this.parent&&(this.parent.drawLayer.remove(this.#y),this.#y=null,this.parent.drawLayer.remove(this.#or),this.#or=null)}#dr(t=this.parent){null===this.#y&&(({id:this.#y,clipPathId:this.#Za}=t.drawLayer.draw({bbox:this.#nr.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#rr},rootClass:{highlight:!0,free:this.#ar},path:{d:this.#nr.toSVGPath()}},!1,!0)),this.#or=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#ar},bbox:this.#tr.box,path:{d:this.#tr.toSVGPath()}},this.#ar),this.#sr&&(this.#sr.style.clipPath=this.#Za))}static#pr([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;this.#ar?(t=(t-this.rotation+360)%360,i=cd.#pr(this.#nr.box,t)):i=cd.#pr([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#y,{bbox:i,root:{"data-main-rotation":t}}),e.updateProperties(this.#or,{bbox:cd.#pr(this.#tr.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#lr&&(t.setAttribute("aria-label",this.#lr),t.setAttribute("role","mark")),this.#ar?t.classList.add("free"):this.div.addEventListener("keydown",this.#vr.bind(this),{signal:this._uiManager._signal});const e=this.#sr=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#Za;const[i,s]=this.parentDimensions;return this.setDims(this.width*i,this.height*s),il(this,this.#sr,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#or,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#or,{rootClass:{hovered:!1}})}#vr(t){cd._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#br(!0);break;case 1:case 3:this.#br(!1)}}#br(t){if(!this.#Ya)return;const e=window.getSelection();t?e.setPosition(this.#Ya,this.#Qa):e.setPosition(this.#er,this.#ir)}select(){super.select(),this.#or&&this.parent?.drawLayer.updateProperties(this.#or,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#or&&(this.parent?.drawLayer.updateProperties(this.#or,{rootClass:{selected:!1}}),this.#ar||this.#br(!1))}get _mustFixPosition(){return!this.#ar}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#y,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#or,{rootClass:{hidden:!t}}))}#_r(){return this.#ar?this.rotation:0}#yr(){if(this.#ar)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#Ja,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:c}of n){const n=o*t+i,d=(1-l)*e+s;a[r]=a[r+4]=n,a[r+1]=a[r+3]=d,a[r+2]=a[r+6]=n+h*t,a[r+5]=a[r+7]=d-c*e,r+=8}return a}#wr(t){return this.#nr.serialize(t,this.#_r())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,c=t.combinedSignal(h),d=e=>{h.abort(),this.#xr(t,e)};window.addEventListener("blur",d,{signal:c}),window.addEventListener("pointerup",d,{signal:c}),window.addEventListener("pointerdown",Go,{capture:!0,passive:!1,signal:c}),window.addEventListener("contextmenu",Wo,{signal:c}),i.addEventListener("pointermove",this.#Ar.bind(this,t),{signal:c}),this._freeHighlight=new od({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#Ar(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#xr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof qc){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:zr.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof Gc){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:zr.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Ro.makeHexColor(...n),l.#rr=o||1,r&&(l.#ua=t.thickness),l.annotationElementId=t.id||null,l._initialData=s;const[h,c]=l.pageDimensions,[d,u]=l.pageTranslation;if(a){const t=l.#Ja=[];for(let e=0;e<a.length;e+=8)t.push({x:(a[e]-d)/h,y:1-(a[e+1]-u)/c,width:(a[e+2]-a[e])/h,height:(a[e+1]-a[e+5])/c});l.#ur(),l.#dr(),l.rotate(l.rotation)}else if(r){l.#ar=!0;const t=r[0],i={x:t[0]-d,y:c-(t[1]-u)},s=new od(i,[0,0,h,c],1,l.#ua/2,!0,.001);for(let e=0,n=t.length;e<n;e+=2)i.x=t[e]-d,i.y=c-(t[e+1]-u),s.add(i);const{id:n,clipPathId:a}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:s.toSVGPath()}},!0,!0);l.#cr({highlightOutlines:s.getOutlines(),highlightId:n,clipPathId:a}),l.#dr(),l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),i=dl._colorManager.convert(this.color),s={annotationType:zr.HIGHLIGHT,color:i,opacity:this.#rr,thickness:this.#ua,quadPoints:this.#yr(),outlines:this.#wr(e),pageIndex:this.pageIndex,rect:e,rotation:this.#_r(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#ta(s)?null:(s.id=this.annotationElementId,s)}#ta(t){const{color:e}=this._initialData;return t.color.some(((t,i)=>t!==e[i]))}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class dd{#kr=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#kr[t]=e}toSVGProperties(){const t=this.#kr;return this.#kr=Object.create(null),{root:t}}reset(){this.#kr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){po("Not implemented")}}class ud extends dl{#Tr=null;#Sr;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#Er=null;static#Cr=null;static#Rr=null;static#Mr=NaN;static#Pr=null;static#Lr=null;static#Dr=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#Sr=t.mustBeCommitted||!1,this._addOutlines(t)}_addOutlines(t){t.drawOutlines&&(this.#Ir(t),this.#dr())}#Ir({drawOutlines:t,drawId:e,drawingOptions:i}){this.#Tr=t,this._drawingOptions||=i,e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#Or(t,this.parent),this.#Nr(t.box)}#Or(t,e){const{id:i}=e.drawLayer.draw(ud._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){po("Not implemented")}static get typesMap(){po("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e),this._currentParent&&(ud.#Er.updateProperty(i,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],a=t=>{s.updateProperty(e,t);const i=this.#Tr.updateProperty(e,t);i&&this.#Nr(i),this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties())};this.addCommands({cmd:a.bind(this,i),undo:a.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,ud._mergeSVGProperties(this.#Tr.getPathResizingSVGProperties(this.#Fr()),{bbox:this.#Br()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,ud._mergeSVGProperties(this.#Tr.getPathResizedSVGProperties(this.#Fr()),{bbox:this.#Br()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Br()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,ud._mergeSVGProperties(this.#Tr.getPathTranslatedSVGProperties(this.#Fr(),this.parentDimensions),{bbox:this.#Br()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#Sr&&(this.#Sr=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#mr(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#dr(),this.#Nr(this.#Tr.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#mr()):t&&(this._uiManager.addShouldRescale(this),this.#dr(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#mr(){null!==this._drawId&&this.parent&&(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#dr(t=this.parent){null!==this._drawId&&this.parent===t||(null===this._drawId?(this._drawingOptions.updateAll(),this._drawId=this.#Or(this.#Tr,t)):this.parent.drawLayer.updateParent(this._drawId,t.drawLayer))}#jr([t,e,i,s]){const{parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/n),s*(n/a)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(a/n),s*(n/a)];default:return[t,e,i,s]}}#Fr(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(n/a),s*(a/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/a),s*(a/n)];default:return[t,e,i,s]}}#Nr(t){if([this.x,this.y,this.width,this.height]=this.#jr(t),this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Br(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*n+a)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(r/o),s*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),s*(o/r)];case 6:return[1-t-s*(o/r),1-e,s*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-s*(o/r),i*(r/o),s*(o/r)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/r),e,s*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-s*(o/r),i*(r/o),s*(o/r)];case 14:return[1-t,1-e-i*(r/o),s*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),s*(o/r)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,ud._mergeSVGProperties({bbox:this.#Br()},this.#Tr.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Nr(this.#Tr.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const i=super.render();i.classList.add("draw");const s=document.createElement("div");i.append(s),s.setAttribute("aria-hidden","true"),s.className="internal";const[n,a]=this.parentDimensions;return this.setDims(this.width*n,this.height*a),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),i}static createDrawerInstance(t,e,i,s,n){po("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=s;if(ud.#Pr&&ud.#Pr!==l)return;const{viewport:{rotation:h}}=t,{width:c,height:d}=n.getBoundingClientRect(),u=ud.#Cr=new AbortController,p=t.combinedSignal(u);ud.#Mr||=o,ud.#Pr??=l,window.addEventListener("pointerup",(t=>{ud.#Mr===t.pointerId?this._endDraw(t):ud.#Lr?.delete(t.pointerId)}),{signal:p}),window.addEventListener("pointercancel",(t=>{ud.#Mr===t.pointerId?this._currentParent.endDrawingSession():ud.#Lr?.delete(t.pointerId)}),{signal:p}),window.addEventListener("pointerdown",(t=>{ud.#Pr===t.pointerType&&((ud.#Lr||=new Set).add(t.pointerId),ud.#Er.isCancellable()&&(ud.#Er.removeLastElement(),ud.#Er.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))}),{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",Wo,{signal:p}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p}),n.addEventListener("touchmove",(t=>{t.timeStamp===ud.#Dr&&Go(t)}),{signal:p}),t.toggleDrawing(),e._editorUndoBar?.hide(),ud.#Er?t.drawLayer.updateProperties(this._currentDrawId,ud.#Er.startNew(a,r,c,d,h)):(e.updateUIForDefaultProperties(this),ud.#Er=this.createDrawerInstance(a,r,c,d,h),ud.#Rr=this.getDefaultDrawingOptions(),this._currentParent=t,({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(ud.#Rr.toSVGProperties(),ud.#Er.defaultSVGProperties),!0,!1)))}static _drawMove(t){if(ud.#Dr=-1,!ud.#Er)return;const{offsetX:e,offsetY:i,pointerId:s}=t;ud.#Mr===s&&(ud.#Lr?.size>=1?this._endDraw(t):(this._currentParent.drawLayer.updateProperties(this._currentDrawId,ud.#Er.add(e,i)),ud.#Dr=t.timeStamp,Go(t)))}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,ud.#Er=null,ud.#Rr=null,ud.#Pr=null,ud.#Dr=NaN),ud.#Cr&&(ud.#Cr.abort(),ud.#Cr=null,ud.#Mr=NaN,ud.#Lr=null)}static _endDraw(t){const e=this._currentParent;if(e)if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,ud.#Er.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const t=ud.#Er,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:Vr.DRAW_STEP})}else this.endDrawing(!1)}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(Vr.DRAW_STEP),!ud.#Er.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:ud.#Er.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:ud.#Rr,mustBeCommitted:!t});return this._cleanup(!0),a}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,a){po("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);return l.createDrawingOptions(t),l.#Ir({drawOutlines:o}),l.#dr(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#Tr.serialize([e,i,s,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class pd{#ra=new Float64Array(6);#Cn;#zr;#as;#ua;#pa;#Vr="";#Ur=0;#Oa=new gd;#Hr;#$r;constructor(t,e,i,s,n,a){this.#Hr=i,this.#$r=s,this.#as=n,this.#ua=a,[t,e]=this.#Wr(t,e);const r=this.#Cn=[NaN,NaN,NaN,NaN,t,e];this.#pa=[t,e],this.#zr=[{line:r,points:this.#pa}],this.#ra.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#ua=e)}#Wr(t,e){return id._normalizePoint(t,e,this.#Hr,this.#$r,this.#as)}isEmpty(){return!this.#zr||0===this.#zr.length}isCancellable(){return this.#pa.length<=10}add(t,e){[t,e]=this.#Wr(t,e);const[i,s,n,a]=this.#ra.subarray(2,6),r=t-n,o=e-a;return Math.hypot(this.#Hr*r,this.#$r*o)<=2?null:(this.#pa.push(t,e),isNaN(i)?(this.#ra.set([n,a,t,e],2),this.#Cn.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#ra[0])&&this.#Cn.splice(6,6),this.#ra.set([i,s,n,a,t,e],0),this.#Cn.push(...id.createBezierPoints(i,s,n,a,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const i=this.add(t,e);return i||(2===this.#pa.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Hr=i,this.#$r=s,this.#as=n,[t,e]=this.#Wr(t,e);const a=this.#Cn=[NaN,NaN,NaN,NaN,t,e];this.#pa=[t,e];const r=this.#zr.at(-1);return r&&(r.line=new Float32Array(r.line),r.points=new Float32Array(r.points)),this.#zr.push({line:a,points:this.#pa}),this.#ra.set(a,0),this.#Ur=0,this.toSVGPath(),null}getLastElement(){return this.#zr.at(-1)}setLastElement(t){return this.#zr?(this.#zr.push(t),this.#Cn=t.line,this.#pa=t.points,this.#Ur=0,{path:{d:this.toSVGPath()}}):this.#Oa.setLastElement(t)}removeLastElement(){if(!this.#zr)return this.#Oa.removeLastElement();this.#zr.pop(),this.#Vr="";for(let t=0,e=this.#zr.length;t<e;t++){const{line:e,points:i}=this.#zr[t];this.#Cn=e,this.#pa=i,this.#Ur=0,this.toSVGPath()}return{path:{d:this.#Vr}}}toSVGPath(){const t=id.svgRound(this.#Cn[4]),e=id.svgRound(this.#Cn[5]);if(2===this.#pa.length)return this.#Vr=`${this.#Vr} M ${t} ${e} Z`,this.#Vr;if(this.#pa.length<=6){const i=this.#Vr.lastIndexOf("M");this.#Vr=`${this.#Vr.slice(0,i)} M ${t} ${e}`,this.#Ur=6}if(4===this.#pa.length){const t=id.svgRound(this.#Cn[10]),e=id.svgRound(this.#Cn[11]);return this.#Vr=`${this.#Vr} L ${t} ${e}`,this.#Ur=12,this.#Vr}const i=[];0===this.#Ur&&(i.push(`M ${t} ${e}`),this.#Ur=6);for(let t=this.#Ur,e=this.#Cn.length;t<e;t+=6){const[e,s,n,a,r,o]=this.#Cn.slice(t,t+6).map(id.svgRound);i.push(`C${e} ${s} ${n} ${a} ${r} ${o}`)}return this.#Vr+=i.join(" "),this.#Ur=this.#Cn.length,this.#Vr}getOutlines(t,e,i,s){const n=this.#zr.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#Oa.build(this.#zr,t,e,i,this.#as,this.#ua,s),this.#ra=null,this.#Cn=null,this.#zr=null,this.#Vr=null,this.#Oa}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class gd extends id{#ka;#Gr=0;#sa;#zr;#Hr;#$r;#qr;#as;#ua;build(t,e,i,s,n,a,r){this.#Hr=e,this.#$r=i,this.#qr=s,this.#as=n,this.#ua=a,this.#sa=r??0,this.#zr=t,this.#Kr()}get thickness(){return this.#ua}setLastElement(t){return this.#zr.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#zr.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#zr)if(t.push(`M${id.svgRound(e[4])} ${id.svgRound(e[5])}`),6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${id.svgRound(e[10])} ${id.svgRound(e[11])}`);else for(let i=6,s=e.length;i<s;i+=6){const[s,n,a,r,o,l]=e.subarray(i,i+6).map(id.svgRound);t.push(`C${s} ${n} ${a} ${r} ${o} ${l}`)}else t.push("Z");return t.join("")}serialize([t,e,i,s],n){const a=[],r=[],[o,l,h,c]=this.#Xr();let d,u,p,g,f,_,m,v,b;switch(this.#as){case 0:b=id._rescale,d=t,u=e+s,p=i,g=-s,f=t+o*i,_=e+(1-l-c)*s,m=t+(o+h)*i,v=e+(1-l)*s;break;case 90:b=id._rescaleAndSwap,d=t,u=e,p=i,g=s,f=t+l*i,_=e+o*s,m=t+(l+c)*i,v=e+(o+h)*s;break;case 180:b=id._rescale,d=t+i,u=e,p=-i,g=s,f=t+(1-o-h)*i,_=e+l*s,m=t+(1-o)*i,v=e+(l+c)*s;break;case 270:b=id._rescaleAndSwap,d=t+i,u=e+s,p=-i,g=-s,f=t+(1-l-c)*i,_=e+(1-o-h)*s,m=t+(1-l)*i,v=e+(1-o)*s}for(const{line:t,points:e}of this.#zr)a.push(b(t,d,u,p,g,n?new Array(t.length):null)),r.push(b(e,d,u,p,g,n?new Array(e.length):null));return{lines:a,points:r,rect:[f,_,m,v]}}static deserialize(t,e,i,s,n,{paths:{lines:a,points:r},rotation:o,thickness:l}){const h=[];let c,d,u,p,g;switch(o){case 0:g=id._rescale,c=-t/i,d=e/s+1,u=1/i,p=-1/s;break;case 90:g=id._rescaleAndSwap,c=-e/s,d=-t/i,u=1/s,p=1/i;break;case 180:g=id._rescale,c=t/i+1,d=-e/s,u=-1/i,p=1/s;break;case 270:g=id._rescaleAndSwap,c=e/s+1,d=t/i+1,u=-1/s,p=-1/i}if(!a){a=[];for(const t of r){const e=t.length;if(2===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const i=new Float32Array(3*(e-2));a.push(i);let[s,n,r,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,s,n],0);for(let a=4;a<e;a+=2){const e=t[a],l=t[a+1];i.set(id.createBezierPoints(s,n,r,o,e,l),3*(a-2)),[s,n,r,o]=[r,o,e,l]}}}for(let t=0,e=a.length;t<e;t++)h.push({line:g(a[t].map((t=>t??NaN)),c,d,u,p),points:g(r[t].map((t=>t??NaN)),c,d,u,p)});const f=new this.prototype.constructor;return f.build(h,i,s,1,o,l,n),f}#Yr(t=this.#ua){const e=this.#sa+t/2*this.#qr;return this.#as%180==0?[e/this.#Hr,e/this.#$r]:[e/this.#$r,e/this.#Hr]}#Xr(){const[t,e,i,s]=this.#ka,[n,a]=this.#Yr(0);return[t+n,e+a,i-2*n,s-2*a]}#Kr(){const t=this.#ka=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#zr){if(e.length<=12){for(let i=4,s=e.length;i<s;i+=6)Ro.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],s=e[5];for(let n=6,a=e.length;n<a;n+=6){const[a,r,o,l,h,c]=e.subarray(n,n+6);Ro.bezierBoundingBox(i,s,a,r,o,l,h,c,t),i=h,s=c}}const[e,i]=this.#Yr();t[0]=Io(t[0]-e,0,1),t[1]=Io(t[1]-i,0,1),t[2]=Io(t[2]+e,0,1),t[3]=Io(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#ka}updateProperty(t,e){return"stroke-width"===t?this.#gr(e):null}#gr(t){const[e,i]=this.#Yr();this.#ua=t;const[s,n]=this.#Yr(),[a,r]=[s-e,n-i],o=this.#ka;return o[0]-=a,o[1]-=r,o[2]+=2*a,o[3]+=2*r,o}updateParentDimensions([t,e],i){const[s,n]=this.#Yr();this.#Hr=t,this.#$r=e,this.#qr=i;const[a,r]=this.#Yr(),o=a-s,l=r-n,h=this.#ka;return h[0]-=o,h[1]-=l,h[2]+=2*o,h[3]+=2*l,h}updateRotation(t){return this.#Gr=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#ka.map(id.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#ka;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#ka;let i=0,s=0,n=0,a=0,r=0,o=0;switch(this.#Gr){case 90:s=e/t,n=-t/e,r=t;break;case 180:i=-1,a=-1,r=t,o=e;break;case 270:s=-e/t,n=t/e,o=e;break;default:return""}return`matrix(${i} ${s} ${n} ${a} ${id.svgRound(r)} ${id.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,s]){const[n,a]=this.#Yr(),[r,o,l,h]=this.#ka;if(Math.abs(l-n)<=id.PRECISION||Math.abs(h-a)<=id.PRECISION){const n=t+i/2-(r+l/2),a=e+s/2-(o+h/2);return{path:{"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`,transform:`${this.rotationTransform} translate(${n} ${a})`}}}const c=(i-2*n)/(l-2*n),d=(s-2*a)/(h-2*a),u=l/i,p=h/s;return{path:{"transform-origin":`${id.svgRound(r)} ${id.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${id.svgRound(n)} ${id.svgRound(a)}) scale(${c} ${d}) translate(${id.svgRound(-n)} ${id.svgRound(-a)})`}}}getPathResizedSVGProperties([t,e,i,s]){const[n,a]=this.#Yr(),r=this.#ka,[o,l,h,c]=r;if(r[0]=t,r[1]=e,r[2]=i,r[3]=s,Math.abs(h-n)<=id.PRECISION||Math.abs(c-a)<=id.PRECISION){const n=t+i/2-(o+h/2),a=e+s/2-(l+c/2);for(const{line:t,points:e}of this.#zr)id._translate(t,n,a,t),id._translate(e,n,a,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(i-2*n)/(h-2*n),u=(s-2*a)/(c-2*a),p=-d*(o+n)+t+n,g=-u*(l+a)+e+a;if(1!==d||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#zr)id._rescale(t,p,g,d,u,t),id._rescale(e,p,g,d,u,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[s,n]=i,a=this.#ka,r=t-a[0],o=e-a[1];if(this.#Hr===s&&this.#$r===n)for(const{line:t,points:e}of this.#zr)id._translate(t,r,o,t),id._translate(e,r,o,e);else{const t=this.#Hr/s,e=this.#$r/n;this.#Hr=s,this.#$r=n;for(const{line:i,points:s}of this.#zr)id._rescale(i,r,o,t,e,i),id._rescale(s,r,o,t,e,s);a[2]*=t,a[3]*=e}return a[0]=t,a[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#ka;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${id.svgRound(t[0])} ${id.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class fd extends dd{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:dl._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){"stroke-width"===t&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new fd(this._viewParameters);return t.updateAll(this),t}}class _d extends ud{static _type="ink";static _editorType=zr.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){dl.initialize(t,e),this._defaultDrawingOptions=new fd(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return mo(this,"typesMap",new Map([[Vr.INK_THICKNESS,"stroke-width"],[Vr.INK_COLOR,"stroke"],[Vr.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,s,n){return new pd(t,e,i,s,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,s,n,a){return gd.deserialize(t,e,i,s,n,a)}static async deserialize(t,e,i){let s=null;if(t instanceof Gc){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,opacity:o,borderStyle:{rawWidth:l},popupRef:h},parent:{page:{pageNumber:c}}}=t;s=t={annotationType:zr.INK,color:Array.from(r),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:c-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:h}}const n=await super.deserialize(t,e,i);return n.annotationElementId=t.id||null,n._initialData=s,n}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:i}){this._drawingOptions=_d.getDefaultDrawingOptions({stroke:Ro.makeHexColor(...t),"stroke-width":e,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:i,rect:s}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":a,"stroke-width":r}}=this,o={annotationType:zr.INK,color:dl._colorManager.convert(n),opacity:a,thickness:r,paths:{lines:e,points:i},pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?(o.isCopy=!0,o):this.annotationElementId&&!this.#ta(o)?null:(o.id=this.annotationElementId,o)}#ta(t){const{color:e,thickness:i,opacity:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some(((t,i)=>t!==e[i]))||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);return t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e}),null}}class md extends gd{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}class vd{static#Qr={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#Jr(t,e,i,s){return s-=e,0===(i-=t)?s>0?0:4:1===i?s+6:2-s}static#Zr=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#to(t,e,i,s,n,a,r){const o=this.#Jr(i,s,n,a);for(let n=0;n<8;n++){const a=(-n+o-r+16)%8;if(0!==t[(i+this.#Zr[2*a])*e+(s+this.#Zr[2*a+1])])return a}return-1}static#eo(t,e,i,s,n,a,r){const o=this.#Jr(i,s,n,a);for(let n=0;n<8;n++){const a=(n+o+r+16)%8;if(0!==t[(i+this.#Zr[2*a])*e+(s+this.#Zr[2*a+1])])return a}return-1}static#io(t,e,i,s){const n=t.length,a=new Int32Array(n);for(let e=0;e<n;e++)a[e]=t[e]<=s?1:0;for(let t=1;t<i-1;t++)a[t*e]=a[t*e+e-1]=0;for(let t=0;t<e;t++)a[t]=a[e*i-1-t]=0;let r,o=1;const l=[];for(let t=1;t<i-1;t++){r=1;for(let i=1;i<e-1;i++){const s=t*e+i,n=a[s];if(0===n)continue;let h=t,c=i;if(1===n&&0===a[s-1])o+=1,c-=1;else{if(!(n>=1&&0===a[s+1])){1!==n&&(r=Math.abs(n));continue}o+=1,c+=1,n>1&&(r=n)}const d=[i,t],u=c===i+1,p={isHole:u,points:d,id:o,parent:0};let g;l.push(p);for(const t of l)if(t.id===r){g=t;break}g?g.isHole?p.parent=u?g.parent:r:p.parent=u?r:g.parent:p.parent=u?r:0;const f=this.#to(a,e,t,i,h,c,0);if(-1===f){a[s]=-o,1!==a[s]&&(r=Math.abs(a[s]));continue}let _=this.#Zr[2*f],m=this.#Zr[2*f+1];const v=t+_,b=i+m;h=v,c=b;let y=t,w=i;for(;;){const n=this.#eo(a,e,y,w,h,c,1);_=this.#Zr[2*n],m=this.#Zr[2*n+1];const l=y+_,u=w+m;d.push(u,l);const p=y*e+w;if(0===a[p+1]?a[p]=-o:1===a[p]&&(a[p]=o),l===t&&u===i&&y===v&&w===b){1!==a[s]&&(r=Math.abs(a[s]));break}h=y,c=w,y=l,w=u}}}return l}static#so(t,e,i,s){if(i-e<=4){for(let n=e;n<i-2;n+=2)s.push(t[n],t[n+1]);return}const n=t[e],a=t[e+1],r=t[i-4]-n,o=t[i-3]-a,l=Math.hypot(r,o),h=r/l,c=o/l,d=h*a-c*n,u=o/r,p=1/l,g=Math.atan(u),f=Math.cos(g),_=Math.sin(g),m=p*(Math.abs(f)+Math.abs(_)),v=p*(1-m+m**2),b=Math.max(Math.atan(Math.abs(_+f)*v),Math.atan(Math.abs(_-f)*v));let y=0,w=e;for(let s=e+2;s<i-2;s+=2){const e=Math.abs(d-h*t[s+1]+c*t[s]);e>y&&(w=s,y=e)}y>(l*b)**2?(this.#so(t,e,w+2,s),this.#so(t,w,i,s)):s.push(n,a)}static#no(t){const e=[],i=t.length;return this.#so(t,0,i,e),e.push(t[i-2],t[i-1]),e.length<=4?null:e}static#ao(t,e,i,s,n,a){const r=new Float32Array(a**2),o=-2*s**2,l=a>>1;for(let t=0;t<a;t++){const e=(t-l)**2;for(let i=0;i<a;i++)r[t*a+i]=Math.exp((e+(i-l)**2)/o)}const h=new Float32Array(256),c=-2*n**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/c);const d=t.length,u=new Uint8Array(d),p=new Uint32Array(256);for(let s=0;s<i;s++)for(let n=0;n<e;n++){const o=s*e+n,c=t[o];let d=0,g=0;for(let o=0;o<a;o++){const u=s+o-l;if(!(u<0||u>=i))for(let i=0;i<a;i++){const s=n+i-l;if(s<0||s>=e)continue;const p=t[u*e+s],f=r[o*a+i]*h[Math.abs(p-c)];d+=p*f,g+=f}}p[u[o]=Math.round(d/g)]++}return[u,p]}static#ro(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#oo(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let s=-1/0,n=1/0;for(let e=0,a=i.length;e<a;e++){if(0===t[3+(e<<2)]){s=i[e]=255;continue}const a=i[e]=t[e<<2];a>s&&(s=a),a<n&&(n=a)}const a=255/(s-n);for(let t=0;t<e;t++)i[t]=(i[t]-n)*a;return i}static#lo(t){let e,i=-1/0,s=-1/0;const n=t.findIndex((t=>0!==t));let a=n,r=n;for(e=n;e<256;e++){const n=t[e];n>i&&(e-a>s&&(s=e-a,r=e-1),i=n,a=e)}for(e=r-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#ho(t){const e=t,{width:i,height:s}=t,{maxDim:n}=this.#Qr;let a=i,r=s;if(i>n||s>n){let o=i,l=s,h=Math.log2(Math.max(i,s)/n);const c=Math.floor(h);h=h===c?c-1:c;for(let i=0;i<h;i++){a=Math.ceil(o/2),r=Math.ceil(l/2);const i=new OffscreenCanvas(a,r);i.getContext("2d").drawImage(t,0,0,o,l,0,0,a,r),o=a,l=r,t!==e&&t.close(),t=i.transferToImageBitmap()}const d=Math.min(n/a,n/r);a=Math.round(a*d),r=Math.round(r*d)}const o=new OffscreenCanvas(a,r).getContext("2d",{willReadFrequently:!0});o.filter="grayscale(1)",o.drawImage(t,0,0,t.width,t.height,0,0,a,r);const l=o.getImageData(0,0,a,r).data;return[this.#oo(l),a,r]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:s},n,a,r,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1});const c=h.font=`${i} ${s} 200px ${e}`,{actualBoundingBoxLeft:d,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:f,fontBoundingBoxDescent:_,width:m}=h.measureText(t),v=1.5,b=Math.ceil(Math.max(Math.abs(d)+Math.abs(u)||0,m)*v),y=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(f)+Math.abs(_)||200)*v);l=new OffscreenCanvas(b,y),h=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),h.font=c,h.filter="grayscale(1)",h.fillStyle="white",h.fillRect(0,0,b,y),h.fillStyle="black",h.fillText(t,.5*b/2,1.5*y/2);const w=this.#oo(h.getImageData(0,0,b,y).data),x=this.#ro(w),A=this.#lo(x),k=this.#io(w,b,y,A);return this.processDrawnLines({lines:{curves:k,width:b,height:y},pageWidth:n,pageHeight:a,rotation:r,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,s,n){const[a,r,o]=this.#ho(t),[l,h]=this.#ao(a,r,o,Math.hypot(r,o)*this.#Qr.sigmaSFactor,this.#Qr.sigmaR,this.#Qr.kernelSize),c=this.#lo(h),d=this.#io(l,r,o,c);return this.processDrawnLines({lines:{curves:d,width:r,height:o},pageWidth:e,pageHeight:i,rotation:s,innerMargin:n,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:s,innerMargin:n,mustSmooth:a,areContours:r}){s%180!=0&&([e,i]=[i,e]);const{curves:o,width:l,height:h}=t,c=t.thickness??0,d=[],u=Math.min(e/l,i/h),p=u/e,g=u/i,f=[];for(const{points:t}of o){const e=a?this.#no(t):t;if(!e)continue;f.push(e);const i=e.length,s=new Float32Array(i),n=new Float32Array(3*(2===i?2:i-2));if(d.push({line:n,points:s}),2===i){s[0]=e[0]*p,s[1]=e[1]*g,n.set([NaN,NaN,NaN,NaN,s[0],s[1]],0);continue}let[r,o,l,h]=e;r*=p,o*=g,l*=p,h*=g,s.set([r,o,l,h],0),n.set([NaN,NaN,NaN,NaN,r,o],0);for(let t=4;t<i;t+=2){const i=s[t]=e[t]*p,a=s[t+1]=e[t+1]*g;n.set(id.createBezierPoints(r,o,l,h,i,a),3*(t-2)),[r,o,l,h]=[l,h,i,a]}}if(0===d.length)return null;const _=r?new md:new gd;return _.build(d,e,i,1,s,r?0:c,n),{outline:_,newCurves:f,areContours:r,thickness:c,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:s,height:n}){let a,r=1/0,o=-1/0,l=0;for(const e of t){l+=e.length;for(let t=2,i=e.length;t<i;t++){const i=e[t]-e[t-2];r=Math.min(r,i),o=Math.max(o,i)}}a=r>=-128&&o<=127?Int8Array:r>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,c=8+3*h,d=new Uint32Array(c);let u=0;d[u++]=c*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*a.BYTES_PER_ELEMENT,d[u++]=0,d[u++]=s,d[u++]=n,d[u++]=e?0:1,d[u++]=Math.max(0,Math.floor(i??0)),d[u++]=h,d[u++]=a.BYTES_PER_ELEMENT;for(const e of t)d[u++]=e.length-2,d[u++]=e[0],d[u++]=e[1];const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(d);const f=a.prototype.constructor;for(const e of t){const t=new f(e.length-2);for(let i=2,s=e.length;i<s;i++)t[i-2]=e[i]-e[i-2];g.write(t)}g.close();const _=await new Response(p.readable).arrayBuffer();return Oo(new Uint8Array(_))}static async decompressSignature(t){try{const i=(e=t,Uint8Array.fromBase64?Uint8Array.fromBase64(e):So(atob(e))),{readable:s,writable:n}=new DecompressionStream("deflate-raw"),a=n.getWriter();await a.ready,a.write(i).then((async()=>{await a.ready,await a.close()})).catch((()=>{}));let r=null,o=0;for await(const t of s)r||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),r.set(t,o),o+=t.length;const l=new Uint32Array(r.buffer,0,r.length>>2),h=l[1];if(0!==h)throw new Error(`Invalid version: ${h}`);const c=l[2],d=l[3],u=0===l[4],p=l[5],g=l[6],f=l[7],_=[],m=(8+3*g)*Uint32Array.BYTES_PER_ELEMENT;let v;switch(f){case Int8Array.BYTES_PER_ELEMENT:v=new Int8Array(r.buffer,m);break;case Int16Array.BYTES_PER_ELEMENT:v=new Int16Array(r.buffer,m);break;case Int32Array.BYTES_PER_ELEMENT:v=new Int32Array(r.buffer,m)}o=0;for(let t=0;t<g;t++){const e=l[3*t+8],i=new Float32Array(e+2);_.push(i);for(let e=0;e<2;e++)i[e]=l[3*t+8+e+1];for(let t=0;t<e;t++)i[t+2]=i[t]+v[o++]}return{areContours:u,thickness:p,outlines:_,width:c,height:d}}catch(t){return uo(`decompressSignature: ${t}`),null}var e}}class bd extends dd{constructor(){super(),super.updateProperties({fill:dl._defaultLineColor,"stroke-width":0})}clone(){const t=new bd;return t.updateAll(this),t}}class yd extends fd{constructor(t){super(t),super.updateProperties({stroke:dl._defaultLineColor,"stroke-width":1})}clone(){const t=new yd(this._viewParameters);return t.updateAll(this),t}}class wd extends ud{#co=!1;#do=null;#uo=null;#po=null;static _type="signature";static _editorType=zr.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#uo=t.signatureData||null,this.#do=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){dl.initialize(t,e),this._defaultDrawingOptions=new bd,this._defaultDrawnSignatureOptions=new yd(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return mo(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#do}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:i}=this;if(i&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),null===this._drawId)if(this.#uo){const{lines:t,mustSmooth:e,areContours:i,description:s,uuid:n,heightInPage:a}=this.#uo,{rawDims:{pageWidth:r,pageHeight:o},rotation:l}=this.parent.viewport,h=vd.processDrawnLines({lines:t,pageWidth:r,pageHeight:o,rotation:l,innerMargin:wd._INNER_MARGIN,mustSmooth:e,areContours:i});this.addSignature(h,a,s,n)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);return i&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#po=t,this.addEditToolbar()}getUuid(){return this.#po}get description(){return this.#do}set description(t){this.#do=t,super.addEditToolbar().then((e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:i,width:s,height:n}=this.#uo,a=Math.max(s,n);return{areContours:e,outline:vd.processDrawnLines({lines:{curves:t.map((t=>({points:t}))),thickness:i,width:s,height:n},pageWidth:a,pageHeight:a,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.signatureManager&&null!==this.#do&&(await t.addEditSignatureButton(this._uiManager.signatureManager,this.#po,this.#do),t.show()),t):null}addSignature(t,e,i,s){const{x:n,y:a}=this,{outline:r}=this.#uo=t;let o;this.#co=r instanceof md,this.#do=i,this.div.setAttribute("data-l10n-args",JSON.stringify({description:i})),this.#co?o=wd.getDefaultDrawingOptions():(o=wd._defaultDrawnSignatureOptions.clone(),o.updateProperties({"stroke-width":r.thickness})),this._addOutlines({drawOutlines:r,drawingOptions:o});const[l,h]=this.parentDimensions,[,c]=this.pageDimensions;let d=e/c;d=d>=1?.5:d,this.width*=d/this.height,this.width>=1&&(d*=.9/this.width,this.width=.9),this.height=d,this.setDims(l*this.width,h*this.height),this.x=n,this.y=a,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(s),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!s,hasDescription:!!i}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:s}=this.parent.viewport;return vd.process(t,e,i,s,wd._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:s},rotation:n}=this.parent.viewport;return vd.extractContoursFromText(t,e,i,s,n,wd._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:s}=this.parent.viewport;return vd.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:s,innerMargin:wd._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=wd.getDefaultDrawingOptions():(this._drawingOptions=wd._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:i,rect:s}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":n}}=this,a={annotationType:zr.SIGNATURE,isSignature:!0,areContours:this.#co,color:[0,0,0],thickness:this.#co?0:n,pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?(a.paths={lines:e,points:i},a.uuid=this.#po,a.isCopy=!0):a.lines=e,this.#do&&(a.accessibilityData={type:"Figure",alt:this.#do}),a}static deserializeDraw(t,e,i,s,n,a){return a.areContours?md.deserialize(t,e,i,s,n,a):gd.deserialize(t,e,i,s,n,a)}static async deserialize(t,e,i){const s=await super.deserialize(t,e,i);return s.#co=t.areContours,s.#do=t.accessibilityData?.alt||"",s.#po=t.uuid,s}}class xd extends dl{#go=null;#fo=null;#_o=null;#mo=null;#vo=null;#bo="";#yo=null;#wo=!1;#xo=null;#Ao=!1;#ko=!1;static _type="stamp";static _editorType=zr.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#mo=t.bitmapUrl,this.#vo=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){dl.initialize(t,e)}static isHandlingMimeForPasting(t){return Zo.includes(t)}static paste(t,e){e.pasteEditor({mode:zr.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#To(t,e=!1){t?(this.#go=t.bitmap,e||(this.#fo=t.id,this.#Ao=t.isSvg),t.file&&(this.#bo=t.file.name),this.#So()):this.remove()}#Eo(){if(this.#_o=null,this._uiManager.enableWaiting(!1),this.#yo){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#go)return this._editToolbar.hide(),void this._uiManager.editAltText(this,!0);if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#go){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#Co(){if(this.#fo)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#fo).then((t=>this.#To(t,!0))).finally((()=>this.#Eo()));if(this.#mo){const t=this.#mo;return this.#mo=null,this._uiManager.enableWaiting(!0),void(this.#_o=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#To(t))).finally((()=>this.#Eo())))}if(this.#vo){const t=this.#vo;return this.#vo=null,this._uiManager.enableWaiting(!0),void(this.#_o=this._uiManager.imageManager.getFromFile(t).then((t=>this.#To(t))).finally((()=>this.#Eo())))}const t=document.createElement("input");t.type="file",t.accept=Zo.join(",");const e=this._uiManager._signal;this.#_o=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#To(e)}else this.remove();i()}),{signal:e}),t.addEventListener("cancel",(()=>{this.remove(),i()}),{signal:e})})).finally((()=>this.#Eo())),t.click()}remove(){this.#fo&&(this.#go=null,this._uiManager.imageManager.deleteId(this.#fo),this.#yo?.remove(),this.#yo=null,this.#xo&&(clearTimeout(this.#xo),this.#xo=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#fo&&null===this.#yo&&this.#Co(),this.isAttachedToDOM||this.parent.add(this))):this.#fo&&this.#Co()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#_o||this.#go||this.#mo||this.#vo||this.#fo||this.#wo)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#wo||(this.#go?this.#So():this.#Co()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:i,bitmap:s}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(this.#fo=i,s&&(this.#go=s),this.#wo=!1,this.#So())}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#xo&&clearTimeout(this.#xo);this.#xo=setTimeout((()=>{this.#xo=null,this.#Ro()}),200)}#So(){const{div:t}=this;let{width:e,height:i}=this.#go;const[s,n]=this.pageDimensions,a=.75;if(this.width)e=this.width*s,i=this.height*n;else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t,i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n),this._uiManager.enableWaiting(!1);const l=this.#yo=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this.width=e/s,this.height=i/n,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Ro(),this.#ko||(this.parent.addUndoableEditor(this),this.#ko=!0),this._reportTelemetry({action:"inserted_image"}),this.#bo&&this.div.setAttribute("aria-description",this.#bo)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#go,a=new Jo;let r=this.#go,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t),l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Ao||(r=this.#Mo(t,i));const c=h.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(d="#8f8f9d",u="#42414d");const p=15,g=p*a.sx,f=p*a.sy,_=new OffscreenCanvas(2*g,2*f),m=_.getContext("2d");m.fillStyle=d,m.fillRect(0,0,2*g,2*f),m.fillStyle=u,m.fillRect(0,0,g,f),m.fillRect(g,f,g,f),c.fillStyle=c.createPattern(_,"repeat"),c.fillRect(0,0,t,i),c.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let c=null;if(i){let e,i;if(a.symmetric&&r.width<t&&r.height<t)e=r.width,i=r.height;else if(r=this.#go,s>t||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a),i=Math.floor(n*a),this.#Ao||(r=this.#Mo(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i),c={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:c}}#Mo(t,e){const{width:i,height:s}=this.#go;let n=i,a=s,r=this.#go;for(;n>2*t||a>2*e;){const i=n,s=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,i,s,0,0,n,a),r=o.transferToImageBitmap()}return r}#Ro(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new Jo,a=Math.ceil(i*t*n.sx),r=Math.ceil(s*e*n.sy),o=this.#yo;if(!o||o.width===a&&o.height===r)return;o.width=a,o.height=r;const l=this.#Ao?this.#go:this.#Mo(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter,h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}#Po(t){if(t){if(this.#Ao){const t=this._uiManager.imageManager.getSvgUrl(this.#fo);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#go);return t.getContext("2d").drawImage(this.#go,0,0),t.toDataURL()}if(this.#Ao){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*Fo.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*Fo.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);return n.getContext("2d").drawImage(this.#go,0,0,this.#go.width,this.#go.height,0,0,i,s),n.transferToImageBitmap()}return structuredClone(this.#go)}static async deserialize(t,e,i){let s=null,n=!1;if(t instanceof Qc){const{data:{rect:a,rotation:r,id:o,structParent:l,popupRef:h},container:c,parent:{page:{pageNumber:d}},canvas:u}=t;let p,g;u?(delete t.canvas,({id:p,bitmap:g}=i.imageManager.getFromCanvas(c.id,u)),u.remove()):(n=!0,t._hasNoCanvas=!0);const f=(await e._structTree.getAriaAttributes(`${Do}${o}`))?.get("aria-label")||"";s=t={annotationType:zr.STAMP,bitmapId:p,bitmap:g,pageIndex:d-1,rect:a.slice(0),rotation:r,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:f},isSvg:!1,structParent:l,popupRef:h}}const a=await super.deserialize(t,e,i),{rect:r,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:c,accessibilityData:d}=t;n?(i.addMissingCanvas(t.id,a),a.#wo=!0):h&&i.imageManager.isValidId(h)?(a.#fo=h,o&&(a.#go=o)):a.#mo=l,a.#Ao=c;const[u,p]=a.pageDimensions;return a.width=(r[2]-r[0])/u,a.height=(r[3]-r[1])/p,a.annotationElementId=t.id||null,d&&(a.altTextData=d),a._initialData=s,a.#ko=!!s,a}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:zr.STAMP,bitmapId:this.#fo,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Ao,structTreeParentId:this._structTreeParentId};if(t)return i.bitmapUrl=this.#Po(!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;const{decorative:s,altText:n}=this.serializeAltText(!1);if(!s&&n&&(i.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#ta(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,null===e)return i;e.stamps||=new Map;const a=this.#Ao?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#fo)){if(this.#Ao){const t=e.stamps.get(this.#fo);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#Po(!1))}}else e.stamps.set(this.#fo,{area:a,serialized:i}),i.bitmap=this.#Po(!1);return i}#ta(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class Ad{#Fn;#Lo=!1;#Do=null;#Io=null;#Oo=null;#No=new Map;#Fo=!1;#Bo=!1;#jo=!1;#zo=null;#Vo=null;#Uo=null;#Ho=null;#_;static _initialized=!1;static#U=new Map([ed,_d,xd,cd,wd].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const c=[...Ad.#U.values()];if(!Ad._initialized){Ad._initialized=!0;for(const e of c)e.initialize(h,t)}t.registerEditorTypes(c),this.#_=t,this.pageIndex=e,this.div=i,this.#Fn=n,this.#Do=a,this.viewport=l,this.#Uo=o,this.drawLayer=r,this._structTree=s,this.#_.addLayer(this)}get isEmpty(){return 0===this.#No.size}get isInvisible(){return this.isEmpty&&this.#_.getMode()===zr.NONE}updateToolbar(t){this.#_.updateToolbar(t)}updateMode(t=this.#_.getMode()){switch(this.#$o(),t){case zr.NONE:return this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case zr.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case zr.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 i of Ad.#U.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#Uo?.div}setEditingState(t){this.#_.setEditingState(t)}addCommands(t){this.#_.addCommands(t)}cleanUndoStack(t){this.#_.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Do?.div.classList.toggle("disabled",!t)}async enable(){this.#jo=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const e of this.#No.values())e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#_.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));if(!this.#Do)return void(this.#jo=!1);const e=this.#Do.getEditableAnnotations();for(const i of e){if(i.hide(),this.#_.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}this.#jo=!1}disable(){this.#Bo=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#No.values())i.disableEditing(),i.annotationElementId&&(null===i.serialize()?(e.set(i.annotationElementId,i),this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()):t.set(i.annotationElementId,i));if(this.#Do){const i=this.#Do.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#_.isDeletedAnnotationElement(i))continue;let n=e.get(i);n?(n.resetAnnotationElement(s),n.show(!1),s.show()):(n=t.get(i),n&&(this.#_.addChangedExistingAnnotation(n),n.renderAnnotationElement(s)&&n.show(!1)),s.show())}}this.#$o(),this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of Ad.#U.values())i.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#Bo=!1}getEditableAnnotation(t){return this.#Do?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#_.getActive()!==t&&this.#_.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#Uo?.div&&!this.#Ho){this.#Ho=new AbortController;const t=this.#_.combinedSignal(this.#Ho);this.#Uo.div.addEventListener("pointerdown",this.#Wo.bind(this),{signal:t}),this.#Uo.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#Uo?.div&&this.#Ho&&(this.#Ho.abort(),this.#Ho=null,this.#Uo.div.classList.remove("highlighting"))}#Wo(t){this.#_.unselectAll();const{target:e}=t;if(e===this.#Uo.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Uo.div.contains(e)){const{isMac:e}=Eo.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#_.showAllEditors("highlight",!0,!0),this.#Uo.div.classList.add("free"),this.toggleDrawing(),cd.startHighlighting(this,"ltr"===this.#_.direction,{target:this.#Uo.div,x:t.x,y:t.y}),this.#Uo.div.addEventListener("pointerup",(()=>{this.#Uo.div.classList.remove("free"),this.toggleDrawing(!0)}),{once:!0,signal:this.#_._signal}),t.preventDefault()}}enableClick(){if(this.#Io)return;this.#Io=new AbortController;const t=this.#_.combinedSignal(this.#Io);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#Io?.abort(),this.#Io=null}attach(t){this.#No.set(t.id,t);const{annotationElementId:e}=t;e&&this.#_.isDeletedAnnotationElement(e)&&this.#_.removeDeletedAnnotationElement(t)}detach(t){this.#No.delete(t.id),this.#Fn?.removePointerInTextLayer(t.contentDiv),!this.#Bo&&t.annotationElementId&&this.#_.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#_.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#_.addDeletedAnnotationElement(t.annotationElementId),dl.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.#_.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#jo),this.#_.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#Oo&&(t._focusEventsAllowed=!1,this.#Oo=setTimeout((()=>{this.#Oo=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#_._signal}),e.focus())}),0)),t._structTreeParentId=this.#Fn?.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.#_.getId()}get#Go(){return Ad.#U.get(this.#_.getMode())}combinedSignal(t){return this.#_.combinedSignal(t)}#qo(t){const e=this.#Go;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Go?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t),await this.#_.updateMode(t.mode);const{offsetX:i,offsetY:s}=this.#Ko(),n=this.getNextId(),a=this.#qo({parent:this,id:n,x:i,y:s,uiManager:this.#_,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(Ad.#U.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#_))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#qo({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#_,isCentered:e,...i});return n&&this.add(n),n}#Ko(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#Ko(),!0,t)}setSelected(t){this.#_.setSelected(t)}toggleSelected(t){this.#_.toggleSelected(t)}unselect(t){this.#_.unselect(t)}pointerup(t){const{isMac:e}=Eo.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#Fo)return;if(this.#Fo=!1,this.#Go?.isDrawer&&this.#Go.supportMultipleDrawings)return;if(!this.#Lo)return void(this.#Lo=!0);const i=this.#_.getMode();i!==zr.STAMP&&i!==zr.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#_.unselectAll()}pointerdown(t){if(this.#_.getMode()===zr.HIGHLIGHT&&this.enableTextSelection(),this.#Fo)return void(this.#Fo=!1);const{isMac:e}=Eo.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(this.#Fo=!0,this.#Go?.isDrawer)return void this.startDrawingSession(t);const i=this.#_.getActive();this.#Lo=!i||i.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#zo)return void this.#Go.startDrawing(this,this.#_,!1,t);this.#_.setCurrentDrawingSession(this),this.#zo=new AbortController;const e=this.#_.combinedSignal(this.#zo);this.div.addEventListener("blur",(({relatedTarget:t})=>{t&&!this.div.contains(t)&&(this.#Vo=null,this.commitOrRemove())}),{signal:e}),this.#Go.startDrawing(this,this.#_,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#Vo=t)}else this.#Vo&&setTimeout((()=>{this.#Vo?.focus(),this.#Vo=null}),0)}endDrawingSession(t=!1){return this.#zo?(this.#_.setCurrentDrawingSession(null),this.#zo.abort(),this.#zo=null,this.#Vo=null,this.#Go.endDrawing(t)):null}findNewParent(t,e,i){const s=this.#_.findParent(e,i);return null!==s&&s!==this&&(s.changeParent(t),!0)}commitOrRemove(){return!!this.#zo&&(this.endDrawingSession(),!0)}onScaleChanging(){this.#zo&&this.#Go.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#_.getActive()?.parent===this&&(this.#_.commitOrRemove(),this.#_.setActiveEditor(null)),this.#Oo&&(clearTimeout(this.#Oo),this.#Oo=null);for(const t of this.#No.values())this.#Fn?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#No.clear(),this.#_.removeLayer(this)}#$o(){for(const t of this.#No.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,Qo(this.div,t);for(const t of this.#_.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#_.commitOrRemove(),this.#$o();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,Qo(this.div,{rotation:i}),e!==i)for(const t of this.#No.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#_.viewParameters.realScale}}class kd{#fn=null;#Xo=new Map;#Yo=new Map;static#y=0;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#fn){if(this.#fn!==t){if(this.#Xo.size>0)for(const e of this.#Xo.values())e.remove(),t.append(e);this.#fn=t}}else this.#fn=t}static get _svgFactory(){return mo(this,"_svgFactory",new xc)}static#Qo(t,[e,i,s,n]){const{style:a}=t;a.top=100*i+"%",a.left=100*e+"%",a.width=100*s+"%",a.height=100*n+"%"}#Jo(){const t=kd._svgFactory.create(1,1,!0);return this.#fn.append(t),t.setAttribute("aria-hidden",!0),t}#Zo(t,e){const i=kd._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s),i.setAttribute("clipPathUnits","objectBoundingBox");const n=kd._svgFactory.createElement("use");return i.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),s}#tl(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=kd.#y++,n=this.#Jo(),a=kd._svgFactory.createElement("defs");n.append(a);const r=kd._svgFactory.createElement("path");a.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#Yo.set(s,r);const l=i?this.#Zo(a,o):null,h=kd._svgFactory.createElement("use");return n.append(h),h.setAttribute("href",`#${o}`),this.updateProperties(n,t),this.#Xo.set(s,n),{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=kd.#y++,s=this.#Jo(),n=kd._svgFactory.createElement("defs");s.append(n);const a=kd._svgFactory.createElement("path");n.append(a);const r=`path_p${this.pageIndex}_${i}`;let o;if(a.setAttribute("id",r),a.setAttribute("vector-effect","non-scaling-stroke"),e){const t=kd._svgFactory.createElement("mask");n.append(t),o=`mask_p${this.pageIndex}_${i}`,t.setAttribute("id",o),t.setAttribute("maskUnits","objectBoundingBox");const e=kd._svgFactory.createElement("rect");t.append(e),e.setAttribute("width","1"),e.setAttribute("height","1"),e.setAttribute("fill","white");const s=kd._svgFactory.createElement("use");t.append(s),s.setAttribute("href",`#${r}`),s.setAttribute("stroke","none"),s.setAttribute("fill","black"),s.setAttribute("fill-rule","nonzero"),s.classList.add("mask")}const l=kd._svgFactory.createElement("use");s.append(l),l.setAttribute("href",`#${r}`),o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();return s.append(h),l.classList.add("mainOutline"),h.classList.add("secondaryOutline"),this.updateProperties(s,t),this.#Xo.set(i,s),i}finalizeDraw(t,e){this.#Yo.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:a}=e,r="number"==typeof t?this.#Xo.get(t):t;if(r){if(i&&this.#tl(r,i),s&&kd.#Qo(r,s),n){const{classList:t}=r;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(a){const t=r.firstChild.firstChild;this.#tl(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#Xo.get(t);i&&(e.#fn.append(i),this.#Xo.delete(t),e.#Xo.set(t,i))}remove(t){this.#Yo.delete(t),null!==this.#fn&&(this.#Xo.get(t).remove(),this.#Xo.delete(t))}destroy(){this.#fn=null;for(const t of this.#Xo.values())t.remove();this.#Xo.clear(),this.#Yo.clear()}}globalThis._pdfjsTestingUtils={HighlightOutliner:ad},globalThis.pdfjsLib={AbortException:ko,AnnotationEditorLayer:Ad,AnnotationEditorParamsType:Vr,AnnotationEditorType:zr,AnnotationEditorUIManager:ll,AnnotationLayer:Zc,AnnotationMode:jr,AnnotationType:Xr,build:"47ad820d9",ColorPicker:hd,createValidAbsoluteUrl:fo,DOMSVGFactory:xc,DrawLayer:kd,FeatureTest:Eo,fetchData:Bo,getDocument:hc,getFilenameFromUrl:function(t){return[t]=t.split(/[#?]/,1),t.substring(t.lastIndexOf("/")+1)},getPdfFilenameFromUrl:function(t,e="document.pdf"){if("string"!=typeof t)return e;if(Vo(t))return uo('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;const i=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,s=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(t);let n=i.exec(s[1])||i.exec(s[2])||i.exec(s[3]);if(n&&(n=n[0],n.includes("%")))try{n=i.exec(decodeURIComponent(n))[0]}catch{}return n||e},getUuid:Lo,getXfaPageViewport:function(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new jo({viewBox:a,userUnit:1,scale:e,rotation:i})},GlobalWorkerOptions:Lh,ImageKind:Kr,InvalidPDFException:wo,isDataScheme:Vo,isPdfFile:Uo,isValidExplicitDest:kl,MathClamp:Io,noContextMenu:Wo,normalizeUnicode:function(t){return Mo||(Mo=/([\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,Po=new Map([["ſt","ſt"]])),t.replaceAll(Mo,((t,e,i)=>e?e.normalize("NFKC"):Po.get(i)))},OPS:io,OutputScale:Jo,PasswordResponses:{NEED_PASSWORD:1,INCORRECT_PASSWORD:2},PDFDataRangeTransport:dc,PDFDateString:qo,PDFWorker:gc,PermissionFlag:{PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},PixelsPerInch:Fo,RenderingCancelledException:zo,ResponseException:xo,setLayerDimensions:Qo,shadow:mo,SignatureExtractor:vd,stopEvent:Go,SupportedImageMimeTypes:Zo,TextLayer:oc,TouchManager:cl,updateUrlHash:_o,Util:Ro,VerbosityLevel:eo,version:"5.3.31",XfaLayer:Ac};const Td={key:0,class:"loading-screen"},Sd={key:1,class:"image-display-area"},Ed={class:"ocr-container",ref:"containerRef"},Cd=["src"],Rd=["onClick","onMouseover"];var Md=v({__name:"renderOCRResponse",props:{image:{type:null,required:!0},language:{type:String,required:!0}},emits:["close","loadingUpdate"],setup(t,{emit:i}){const s=t;Lh.workerSrc="/tta/pdf.worker.mjs";const{useNotificationsStore:n}=e(),a=n(),h=u(null),g=u([]),f=u(),_=u(),v=u([]),w=u(""),A=u(!1),k=u([]),T=u(1),R=b((()=>v.value.sort().map((t=>{var e;return null==(e=g.value[t])?void 0:e.text})).join(" ")));async function P(t,e,n){if(_.value=t,n)return w.value=n,L(),n;console.log(e),document.addEventListener("click",D),A.value=!0,i("loadingUpdate",!0);const r=new FormData;let o;r.append("image",e);try{const t=await fetch("/tta/ocr?language="+s.language,{method:"POST",body:r});if(!t.ok)throw new Error(`Server error: ${t.status}`);o=await t.text(),w.value=o,L()}catch(t){a.add({title:"Error while using OCR",text:"Please check your console/terminal for the error.",type:"error",dialog:!0}),console.error(t)}return A.value=!1,i("loadingUpdate",!1),o}function L(){const t=f.value,e=t.naturalWidth,i=t.naturalHeight,s=t.clientWidth,n=t.clientHeight,a=[];(new DOMParser).parseFromString(w.value,"text/html").querySelectorAll(".ocrx_word").forEach((t=>{const r=t.getAttribute("title");if(r){const o=r.match(/bbox (\d+) (\d+) (\d+) (\d+)/);if(o){const[r,l,h,c,d]=o.map(Number),u=l/e*s,p=h/i*n,g={x0:u,y0:p,x1:u+(c-l)/e*s,y1:p+(d-h)/i*n};a.push({text:t.textContent.trim(),bbox:g})}else console.warn("Malformed bbox data for span:",t)}else console.warn("Missing title attribute for span:",t)})),g.value=a}function D(){const t=document.activeElement;if(("INPUT"===t.tagName||"TEXTAREA"===t.tagName)&&!t.readOnly&&!t.disabled&&R.value){const e=t.selectionStart,i=t.selectionEnd,s=t.value;t.value=s.slice(0,e)+R.value+s.slice(i),t.selectionStart=t.selectionEnd=e+R.length,v.value=[],t.dispatchEvent(new Event("input",{bubbles:!0}))}}return x((async()=>{const t=await new Promise((t=>{const e=new FileReader;e.onload=e=>{t(e.target.result)},"application/pdf"==s.image.type?e.readAsArrayBuffer(s.image):e.readAsDataURL(s.image)}));if(s.image.type.startsWith("image/"))P(t,s.image);else if("application/pdf"==s.image.type){const e=new Uint8Array(t),i=await hc(e).promise;console.log(i.numPages);for(let t=1;t<=i.numPages;t++){const e=await i.getPage(t),s=e.getViewport({scale:1}),n=document.createElement("canvas"),a=n.getContext("2d");n.width=s.width,n.height=s.height,await e.render({canvasContext:a,viewport:s}).promise;const r=await new Promise((t=>n.toBlob((e=>t(e)),"image/png")));k.value.push({string:n.toDataURL("image/png"),file:new File([r],"page"+t+".png",{type:"image/png"})}),n.remove(),console.log({i:t})}const[s]=k.value;s&&P(s.string,s.file).then((t=>s.response=t))}else i("close"),a.add({title:"Error while using OCR",text:`File type '${s.image.type}' not supported.`,type:"error",dialog:!0})})),y((()=>T.value),(t=>{const e=k.value[t-1];e&&P(e.string,e.file,e.response).then((t=>e.response=t))})),F((()=>{document.removeEventListener("click",D)})),(t,e)=>{const i=r("v-progress-circular"),s=r("VPagination"),n=r("v-input");return o(),p(C,null,[A.value?(o(),p("div",Td,[c(i,{indeterminate:"",class:"c"})])):d("v-if",!0),_.value?(o(),p("div",Sd,[m("div",Ed,[m("img",{src:_.value,onLoad:L,style:{width:"100%","object-fit":"contain"},ref_key:"imageRef",ref:f,onMousedown:e[0]||(e[0]=M((()=>{}),["stop"]))},null,40,Cd),(o(!0),p(C,null,I(g.value,((t,i)=>(o(),p("div",{key:i,class:"text-overlay",style:S({padding:"2px",position:"absolute",left:`${t.bbox.x0}px`,top:`${t.bbox.y0}px`,width:t.bbox.x1-t.bbox.x0+"px",height:t.bbox.y1-t.bbox.y0+"px",border:v.value.includes(i)?"2px solid green":h.value===i?"2px solid blue":"1px solid transparent",cursor:"pointer",backgroundColor:"rgba(255, 255, 0, 0.3)"}),onClick:t=>function(t){const e=v.value.indexOf(t);-1==e?v.value.push(t):v.value.splice(e,1)}(i),onMouseover:t=>h.value=i,onMouseleave:e[1]||(e[1]=t=>h.value=null)},null,44,Rd)))),128))],512),k.value.length>1?(o(),l(s,{key:0,modelValue:T.value,"onUpdate:modelValue":e[2]||(e[2]=t=>T.value=t),length:k.value.length,totalVisible:4,class:"pagination-center"},null,8,["modelValue","length"])):d("v-if",!0),c(n,{modelValue:E(R)},null,8,["modelValue"])])):d("v-if",!0)],64)}}});Zn("\n.image-display-area[data-v-0d65f7ea] {\n position: relative;\n background: white;\n border: 1px solid white;\n color: black;\n border-radius: 8px;\n overflow: hidden;\n margin: auto;\n width: 100%;\n display: flex;\n flex-direction: column;\n}\n.pagination-center[data-v-0d65f7ea] {\n margin: 5px auto;\n}\n.ocr-container[data-v-0d65f7ea] {\n position: relative;\n height: 100%;\n}\n.text-overlay[data-v-0d65f7ea] {\n position: absolute;\n}\n.loading-screen[data-v-0d65f7ea] {\n position: absolute;\n width: 100%;\n height: 100%;\n background-color: rgba(255, 255, 255, 0.4);\n display: flex;\n left: 0;\n top: 0;\n z-index: 1000;\n}\n.loading-screen .c[data-v-0d65f7ea] {\n margin: auto;\n}\n",{}),Md.__scopeId="data-v-0d65f7ea",Md.__file="ocr/OCR-interface/src/renderOCRResponse.vue";var Pd=v({__name:"ocredrag",props:{initialX:{type:Number,required:!0},initialY:{type:Number,required:!0}},emits:["close"],setup(t,{emit:e}){const i=t,s=u(null),n=u(!1),a=B({x:i.initialX||50,y:i.initialY||50}),d=B({x:0,y:0}),p=t=>{n.value=!0,d.x=t.clientX-a.x,d.y=t.clientY-a.y,document.addEventListener("mousemove",g),document.addEventListener("mouseup",f)},g=t=>{n.value&&(a.x=t.clientX-d.x,a.y=t.clientY-d.y)},f=()=>{n.value=!1,document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",f)};return j((()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",f)})),(t,i)=>{const d=r("v-icon"),u=r("VButton");return o(),l(z,{to:"body"},[m("div",{ref_key:"draggableElement",ref:s,style:S({position:"absolute",left:a.x+"px",top:a.y+"px",cursor:n.value?"grabbing":"grab",width:"500px","max-width":"80vw",height:"auto",padding:"20px",backgroundColor:"var(--theme--background)",color:"var(--theme--form--field--label--foreground)",border:"var(--theme--border-color) 2px solid",borderRadius:"4px",userSelect:"none","z-index":100}),onMousedown:p},[V(t.$slots,"default"),c(u,{onClick:i[0]||(i[0]=t=>e("close")),outlined:!1,icon:!0,rounded:!0,class:"close-btn"},{default:h((()=>[c(d,{name:"close"})])),_:1})],36)])}}});Zn("\n.close-btn[data-v-6008a42c] {\n position: absolute;\n right: -10px;\n top: -10px;\n z-index: 1001;\n}\n",{}),Pd.__scopeId="data-v-6008a42c",Pd.__file="ocr/OCR-interface/src/ocredrag.vue";const Ld={class:"ocr-container"};var Dd=v({__name:"interface",props:{language:{type:String,required:!0},collection:{type:String,required:!0}},setup(t){const i=t,{useFieldsStore:s}=e(),n=s(),a=u(!1),f=u(),_=u(!1),v=u(),b=u([]);function y(){f.value.click()}async function A(t){const e=t.target.files[0];e&&(v.value=e)}async function k(t,e){const i=e||T(t.target.parentElement);if(i){const t=await fetch(i).then((t=>t.blob())),e=new File([t],"image.png",{type:t.type}),s=f.value,n=new DataTransfer;n.items.add(e),s.files=n.files,s.dispatchEvent(new Event("change",{bubbles:!0}))}}function T(t){let e=0,i="";for(;e<10;){const s=(t=t.parentElement).querySelector("img");if(s){i=s.src;break}e++}return i.split("?")[0]}function S(){v.value=null,f.value.value=""}return x((()=>{const t=n.getFieldsForCollection(i.collection).filter((t=>{var e;return"file-image"==(null==(e=t.meta)?void 0:e.interface)}));w((()=>{setTimeout((()=>{for(const e of t){const t="[data-collection="+i.collection+"][data-field="+e.field+"]",s=document.querySelector(t);s&&s.addEventListener("mouseover",(e=>{const i=s.querySelector(".image-preview img");if(i){!s.querySelector(".ocr_button")&&T(i)&&b.value.push(t+" .actions")}}))}}),500);const e=n.getFieldsForCollection(i.collection).filter((t=>{var e;return"file"==(null==(e=t.meta)?void 0:e.interface)}));w((()=>{setTimeout((()=>{for(const t of e){const e="[data-collection="+i.collection+"][data-field="+t.field+"]",s=document.querySelector(e);if(s){const t=s.querySelector("input");null==t||t.addEventListener("change",(()=>{var t;null==(t=document.getElementById("_SCAN_OCR"))||t.remove()})),s.addEventListener("click",(()=>{setTimeout((()=>{var t;const e=document.querySelector("a[download]");if(e){const i=e.cloneNode(!0);i.href="#",i.querySelector("i").setAttribute("data-icon","camera_video"),i.id="_SCAN_OCR",i.classList.add("hide-by-default"),i.children[1].innerText="Scan with OCR",i.addEventListener("click",(t=>{t.preventDefault(),k(void 0,e.getAttribute("href"))})),null==(t=e.parentNode)||t.insertBefore(i,e)}}),100)}))}}}))})),a.value=!0}))})),(e,i)=>{const s=r("v-icon"),n=r("VButton"),u=r("v-button");return o(),p(C,null,[(o(!0),p(C,null,I(b.value,(t=>(o(),l(z,{to:t},[c(n,{onClick:k,outlined:!1,icon:!0,rounded:!0,class:"ocr_button"},{default:h((()=>[c(s,{name:"camera_video"})])),_:1})],8,["to"])))),256)),a.value?(o(),l(z,{key:0,to:"#sidebar .v-item-group"},[m("div",Ld,[c(u,{class:"ocr-btn",onClick:y,loading:_.value},{default:h((()=>[g(" Import data with OCR ")])),_:1},8,["loading"]),m("input",{type:"file",onChange:A,class:"ocr-input",ref_key:"inputRef",ref:f,accept:"image/*,application/pdf"},null,544),null!=v.value?(o(),l(Pd,{key:0,onClose:S},{default:h((()=>[c(Md,{image:v.value,onClose:i[0]||(i[0]=()=>S()),language:t.language,onLoadingUpdate:i[1]||(i[1]=t=>_.value=t)},null,8,["image","language"])])),_:1})):d("v-if",!0)])])):d("v-if",!0)],64)}}});Zn("\n.ocr-container {\n display: flex;\n}\n.ocr-container .ocr-btn {\n margin: 10px auto;\n}\n.ocr-container .ocr-input {\n display: none;\n}\n.hide-by-default {\n display: none;\n}\na ~ #_SCAN_OCR {\n display: block;\n}\n",{}),Dd.__file="ocr/OCR-interface/src/interface.vue";const Id=[xr,kr,Er,n({id:"tta-ocr-interface",name:"OCR interface",icon:"camera_video",description:"Use OCR to fill fields. (Text to anything)",hideLabel:!0,hideLoader:!0,component:Dd,types:["alias"],localTypes:["presentation"],options:[{field:"language",name:"Language",type:"dropdown",meta:{interface:"select-dropdown",options:{choices:[{value:"eng",text:"English"},{value:"por",text:"Portuguese"},{value:"fra",text:"French"},{value:"osd",text:"Orientation and Script Detection"},{value:"chi_sim",text:"Chinese (Simplified)"},{value:"spa",text:"Spanish"},{value:"deu",text:"German"},{value:"chi_tra",text:"Chinese (Traditional)"},{value:"heb",text:"Hebrew"},{value:"kor",text:"Korean"},{value:"jpn",text:"Japanese"},{value:"rus",text:"Russian"},{value:"nld",text:"Dutch"},{value:"hin",text:"Hindi"},{value:"ita",text:"Italian"},{value:"jpn_vert",text:"Japanese (Vertical)"},{value:"pol",text:"Polish"},{value:"ron",text:"Romanian"},{value:"mar",text:"Marathi"},{value:"ukr",text:"Ukrainian"},{value:"mal",text:"Malayalam"},{value:"tam",text:"Tamil"},{value:"guj",text:"Gujarati"},{value:"tha",text:"Thai"},{value:"kan",text:"Kannada"},{value:"vie",text:"Vietnamese"},{value:"tel",text:"Telugu"},{value:"swe",text:"Swedish"},{value:"tur",text:"Turkish"},{value:"nor",text:"Norwegian"},{value:"ces",text:"Czech"},{value:"ben",text:"Bengali"},{value:"pan",text:"Punjabi"},{value:"equ",text:"Math / Equation Detection"},{value:"ell",text:"Greek"},{value:"bul",text:"Bulgarian"},{value:"lat",text:"Latin"},{value:"kur",text:"Kurdish"},{value:"ori",text:"Odia"},{value:"kat",text:"Georgian"},{value:"amh",text:"Amharic"},{value:"kaz",text:"Kazakh"},{value:"cat",text:"Catalan"},{value:"nep",text:"Nepali"},{value:"urd",text:"Urdu"},{value:"khm",text:"Khmer"},{value:"dan",text:"Danish"},{value:"chi_sim_vert",text:"Chinese (Simplified, Vertical)"},{value:"uzb",text:"Uzbek (Latin)"},{value:"slv",text:"Slovenian"},{value:"mkd",text:"Macedonian"},{value:"tgl",text:"Tagalog"},{value:"srp",text:"Serbian (Cyrillic)"},{value:"hrv",text:"Croatian"},{value:"tir",text:"Tigrinya"},{value:"syr",text:"Syriac"},{value:"lao",text:"Lao"},{value:"fin",text:"Finnish"},{value:"est",text:"Estonian"},{value:"bos",text:"Bosnian"},{value:"uig",text:"Uyghur"},{value:"sin",text:"Sinhala"},{value:"hye",text:"Armenian"},{value:"eus",text:"Basque"},{value:"sqi",text:"Albanian"},{value:"isl",text:"Icelandic"},{value:"bel",text:"Belarusian"},{value:"aze",text:"Azerbaijani (Latin)"},{value:"pus",text:"Pashto"},{value:"oci",text:"Occitan"},{value:"lit",text:"Lithuanian"},{value:"jav",text:"Javanese"},{value:"hun",text:"Hungarian"},{value:"grc",text:"Ancient Greek"},{value:"gle",text:"Irish"},{value:"frm",text:"Middle French"},{value:"afr",text:"Afrikaans"},{value:"uzb_cyrl",text:"Uzbek (Cyrillic)"},{value:"spa_old",text:"Old Spanish"},{value:"snd",text:"Sindhi"},{value:"mya",text:"Burmese"},{value:"iku",text:"Inuktitut"},{value:"fil",text:"Filipino"},{value:"fas",text:"Persian"},{value:"fao",text:"Faroese"},{value:"dzo",text:"Dzongkha"},{value:"cym",text:"Welsh"},{value:"aze_cyrl",text:"Azerbaijani (Cyrillic)"},{value:"ind",text:"Indonesian"},{value:"ara",text:"Arabic"},{value:"yid",text:"Yiddish"},{value:"ton",text:"Tongan"},{value:"tgk",text:"Tajik"},{value:"srp_latn",text:"Serbian (Latin)"},{value:"slk_frak",text:"Slovak (Fraktur)"},{value:"slk",text:"Slovak"},{value:"san",text:"Sanskrit"},{value:"msa",text:"Malay"},{value:"mri",text:"Maori"},{value:"mlt",text:"Maltese"},{value:"lav",text:"Latvian"},{value:"kur_ara",text:"Kurdish (Arabic)"},{value:"kor_vert",text:"Korean (Vertical)"},{value:"kmr",text:"Kurmanji"},{value:"kir",text:"Kyrgyz"},{value:"hat",text:"Haitian Creole"},{value:"glg",text:"Galician"},{value:"fry",text:"Frisian"},{value:"epo",text:"Esperanto"},{value:"div",text:"Divehi"},{value:"chr",text:"Cherokee"},{value:"bod",text:"Tibetan"},{value:"asm",text:"Assamese"},{value:"yor",text:"Yoruba"},{value:"tat",text:"Tatar"},{value:"sun",text:"Sundanese"},{value:"occ",text:"Occitan (alternative)"},{value:"mon",text:"Mongolian"},{value:"ita_old",text:"Old Italian"},{value:"gla",text:"Scottish Gaelic"},{value:"frk",text:"Frankish"},{value:"enm",text:"Middle English"},{value:"deu_frak",text:"German (Fraktur)"},{value:"dan_frak",text:"Danish (Fraktur)"},{value:"chi_tra_vert",text:"Chinese (Traditional, Vertical)"},{value:"ceb",text:"Cebuano"},{value:"bre",text:"Breton"},{value:"swa",text:"Swahili"},{value:"que",text:"Quechua"},{value:"ltz",text:"Luxembourgish"},{value:"kat_old",text:"Old Georgian"},{value:"cos",text:"Corsican"}]}}}]})],Od=[],Nd=[],Fd=[yr],Bd=[],jd=[H,$,W,G,t({id:"ttaocr",name:"TTA OCR",icon:"camera_video",description:"TTA scan image with OCR",overview:({fileID:t,mode:e,language:i})=>[{label:"Mode",text:e},{label:"Language",text:i},{label:"File ID",text:t}],options:[{field:"fileID",name:"File ID",type:"string",meta:{width:"full",interface:"input"}},{field:"mode",name:"Mode",type:"string",meta:{interface:"select-dropdown",options:{choices:[{text:"Text",value:"text"},{text:"Horc",value:"horc"}]}}},{field:"language",name:"Language",type:"dropdown",meta:{interface:"select-dropdown",options:{choices:[{value:"eng",text:"English"},{value:"por",text:"Portuguese"},{value:"fra",text:"French"},{value:"osd",text:"Orientation and Script Detection"},{value:"chi_sim",text:"Chinese (Simplified)"},{value:"spa",text:"Spanish"},{value:"deu",text:"German"},{value:"chi_tra",text:"Chinese (Traditional)"},{value:"heb",text:"Hebrew"},{value:"kor",text:"Korean"},{value:"jpn",text:"Japanese"},{value:"rus",text:"Russian"},{value:"nld",text:"Dutch"},{value:"hin",text:"Hindi"},{value:"ita",text:"Italian"},{value:"jpn_vert",text:"Japanese (Vertical)"},{value:"pol",text:"Polish"},{value:"ron",text:"Romanian"},{value:"mar",text:"Marathi"},{value:"ukr",text:"Ukrainian"},{value:"mal",text:"Malayalam"},{value:"tam",text:"Tamil"},{value:"guj",text:"Gujarati"},{value:"tha",text:"Thai"},{value:"kan",text:"Kannada"},{value:"vie",text:"Vietnamese"},{value:"tel",text:"Telugu"},{value:"swe",text:"Swedish"},{value:"tur",text:"Turkish"},{value:"nor",text:"Norwegian"},{value:"ces",text:"Czech"},{value:"ben",text:"Bengali"},{value:"pan",text:"Punjabi"},{value:"equ",text:"Math / Equation Detection"},{value:"ell",text:"Greek"},{value:"bul",text:"Bulgarian"},{value:"lat",text:"Latin"},{value:"kur",text:"Kurdish"},{value:"ori",text:"Odia"},{value:"kat",text:"Georgian"},{value:"amh",text:"Amharic"},{value:"kaz",text:"Kazakh"},{value:"cat",text:"Catalan"},{value:"nep",text:"Nepali"},{value:"urd",text:"Urdu"},{value:"khm",text:"Khmer"},{value:"dan",text:"Danish"},{value:"chi_sim_vert",text:"Chinese (Simplified, Vertical)"},{value:"uzb",text:"Uzbek (Latin)"},{value:"slv",text:"Slovenian"},{value:"mkd",text:"Macedonian"},{value:"tgl",text:"Tagalog"},{value:"srp",text:"Serbian (Cyrillic)"},{value:"hrv",text:"Croatian"},{value:"tir",text:"Tigrinya"},{value:"syr",text:"Syriac"},{value:"lao",text:"Lao"},{value:"fin",text:"Finnish"},{value:"est",text:"Estonian"},{value:"bos",text:"Bosnian"},{value:"uig",text:"Uyghur"},{value:"sin",text:"Sinhala"},{value:"hye",text:"Armenian"},{value:"eus",text:"Basque"},{value:"sqi",text:"Albanian"},{value:"isl",text:"Icelandic"},{value:"bel",text:"Belarusian"},{value:"aze",text:"Azerbaijani (Latin)"},{value:"pus",text:"Pashto"},{value:"oci",text:"Occitan"},{value:"lit",text:"Lithuanian"},{value:"jav",text:"Javanese"},{value:"hun",text:"Hungarian"},{value:"grc",text:"Ancient Greek"},{value:"gle",text:"Irish"},{value:"frm",text:"Middle French"},{value:"afr",text:"Afrikaans"},{value:"uzb_cyrl",text:"Uzbek (Cyrillic)"},{value:"spa_old",text:"Old Spanish"},{value:"snd",text:"Sindhi"},{value:"mya",text:"Burmese"},{value:"iku",text:"Inuktitut"},{value:"fil",text:"Filipino"},{value:"fas",text:"Persian"},{value:"fao",text:"Faroese"},{value:"dzo",text:"Dzongkha"},{value:"cym",text:"Welsh"},{value:"aze_cyrl",text:"Azerbaijani (Cyrillic)"},{value:"ind",text:"Indonesian"},{value:"ara",text:"Arabic"},{value:"yid",text:"Yiddish"},{value:"ton",text:"Tongan"},{value:"tgk",text:"Tajik"},{value:"srp_latn",text:"Serbian (Latin)"},{value:"slk_frak",text:"Slovak (Fraktur)"},{value:"slk",text:"Slovak"},{value:"san",text:"Sanskrit"},{value:"msa",text:"Malay"},{value:"mri",text:"Maori"},{value:"mlt",text:"Maltese"},{value:"lav",text:"Latvian"},{value:"kur_ara",text:"Kurdish (Arabic)"},{value:"kor_vert",text:"Korean (Vertical)"},{value:"kmr",text:"Kurmanji"},{value:"kir",text:"Kyrgyz"},{value:"hat",text:"Haitian Creole"},{value:"glg",text:"Galician"},{value:"fry",text:"Frisian"},{value:"epo",text:"Esperanto"},{value:"div",text:"Divehi"},{value:"chr",text:"Cherokee"},{value:"bod",text:"Tibetan"},{value:"asm",text:"Assamese"},{value:"yor",text:"Yoruba"},{value:"tat",text:"Tatar"},{value:"sun",text:"Sundanese"},{value:"occ",text:"Occitan (alternative)"},{value:"mon",text:"Mongolian"},{value:"ita_old",text:"Old Italian"},{value:"gla",text:"Scottish Gaelic"},{value:"frk",text:"Frankish"},{value:"enm",text:"Middle English"},{value:"deu_frak",text:"German (Fraktur)"},{value:"dan_frak",text:"Danish (Fraktur)"},{value:"chi_tra_vert",text:"Chinese (Traditional, Vertical)"},{value:"ceb",text:"Cebuano"},{value:"bre",text:"Breton"},{value:"swa",text:"Swahili"},{value:"que",text:"Quechua"},{value:"ltz",text:"Luxembourgish"},{value:"kat_old",text:"Old Georgian"},{value:"cos",text:"Corsican"}]}}}]})];export{Od as displays,Id as interfaces,Nd as layouts,Fd as modules,jd as operations,Bd as panels};
|
|
22
|
+
*/const Cr=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),Rr=[.001,0,0,.001,0,0],Mr=1.35,Pr=1,Lr=2,Dr=4,Ir=16,Or=32,Nr=64,Fr=128,Br=256,jr={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},zr={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,SIGNATURE:101},Vr={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,DRAW_STEP:41},Ur=0,Hr=1,$r=2,Wr=3,Gr=3,qr=4,Kr={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Xr={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},Yr=1,Qr=2,Jr=3,Zr=4,to=5,eo={ERRORS:0,WARNINGS:1,INFOS:5},io={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},so=0,no=1,ao=2,ro=3;let oo=eo.WARNINGS;function lo(t){Number.isInteger(t)&&(oo=t)}function ho(){return oo}function co(t){oo>=eo.INFOS&&console.log(`Info: ${t}`)}function uo(t){oo>=eo.WARNINGS&&console.log(`Warning: ${t}`)}function po(t){throw new Error(t)}function go(t,e){t||po(e)}function fo(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=decodeURIComponent(escape(t))}catch{}}const s=e?URL.parse(t,e):URL.parse(t);return function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s)?s:null}function _o(t,e,i=!1){const s=URL.parse(t);return s?(s.hash=e,s.href):i&&fo(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function mo(t,e,i,s=!1){return Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1}),i}const vo=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class bo extends vo{constructor(t,e){super(t,"PasswordException"),this.code=e}}class yo extends vo{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class wo extends vo{constructor(t){super(t,"InvalidPDFException")}}class xo extends vo{constructor(t,e,i){super(t,"ResponseException"),this.status=e,this.missing=i}}class Ao extends vo{constructor(t){super(t,"FormatError")}}class ko extends vo{constructor(t){super(t,"AbortException")}}function To(t){"object"==typeof t&&void 0!==t?.length||po("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const s=[];for(let n=0;n<e;n+=i){const a=Math.min(n+i,e),r=t.subarray(n,a);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function So(t){"string"!=typeof t&&po("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let s=0;s<e;++s)i[s]=255&t.charCodeAt(s);return i}class Eo{static get isLittleEndian(){return mo(this,"isLittleEndian",function(){const t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return mo(this,"isEvalSupported",function(){try{return new Function(""),!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return mo(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return mo(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){const{platform:t,userAgent:e}=navigator;return mo(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCSSRoundSupported(){return mo(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const Co=Array.from(Array(256).keys(),(t=>t.toString(16).padStart(2,"0")));class Ro{static makeHexColor(t,e,i){return`#${Co[t]}${Co[e]}${Co[i]}`}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e,i=0){const s=t[i],n=t[i+1];t[i]=s*e[0]+n*e[2]+e[4],t[i+1]=s*e[1]+n*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const s=e[0],n=e[1],a=e[2],r=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],c=t[i+e+1];t[i+e]=h*s+c*a+o,t[i+e+1]=h*n+c*r+l}}static applyInverseTransform(t,e){const i=t[0],s=t[1],n=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-s*e[2]+e[2]*e[5]-e[4]*e[3])/n,t[1]=(-i*e[1]+s*e[0]+e[4]*e[1]-e[5]*e[0])/n}static axialAlignedBoundingBox(t,e,i){const s=e[0],n=e[1],a=e[2],r=e[3],o=e[4],l=e[5],h=t[0],c=t[1],d=t[2],u=t[3];let p=s*h+o,g=p,f=s*d+o,_=f,m=r*c+l,v=m,b=r*u+l,y=b;if(0!==n||0!==a){const t=n*h,e=n*d,i=a*c,s=a*u;p+=i,_+=i,f+=s,g+=s,m+=t,y+=t,b+=e,v+=e}i[0]=Math.min(i[0],p,f,g,_),i[1]=Math.min(i[1],m,b,v,y),i[2]=Math.max(i[2],p,f,g,_),i[3]=Math.max(i[3],m,b,v,y)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const i=t[0],s=t[1],n=t[2],a=t[3],r=i**2+s**2,o=i*n+s*a,l=n**2+a**2,h=(r+l)/2,c=Math.sqrt(h**2-(r*l-o**2));e[0]=Math.sqrt(h+c||1),e[1]=Math.sqrt(h-c||1)}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 i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t),i[1]=Math.min(i[1],e),i[2]=Math.max(i[2],t),i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,s,n){n[0]=Math.min(n[0],t,i),n[1]=Math.min(n[1],e,s),n[2]=Math.max(n[2],t,i),n[3]=Math.max(n[3],e,s)}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const c=1-l,d=l*l,u=d*l,p=c*(c*(c*t+3*l*e)+3*d*i)+u*s,g=c*(c*(c*n+3*l*a)+3*d*r)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,c,d){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-c/h,d));const u=h**2-4*c*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,d),this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,d)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){l[0]=Math.min(l[0],t,r),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,r),l[3]=Math.max(l[3],e,o),this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l),this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l)}}let Mo=null,Po=null;function Lo(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);return crypto.getRandomValues(t),To(t)}const Do="pdfjs_internal_id_";function Io(t,e,i){return Math.min(Math.max(t,e),i)}function Oo(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(To(t))}"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise((i=>{i(t(...e))}))}),"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(t){return t.reduce(((t,e)=>t+e),0)});const No="http://www.w3.org/2000/svg";class Fo{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Bo(t,e="text"){if($o(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{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)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void i(n.response)}i(n.responseText)}},n.send(null)}))}class jo{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t,this.userUnit=e,this.scale=i,this.rotation=s,this.offsetX=n,this.offsetY=a,i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,c,d,u,p,g,f,_;switch((s%=360)<0&&(s+=360),s){case 180:h=-1,c=0,d=0,u=1;break;case 90:h=0,c=1,d=1,u=0;break;case 270:h=0,c=-1,d=-1,u=0;break;case 0:h=1,c=0,d=0,u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}r&&(d=-d,u=-u),0===h?(p=Math.abs(l-t[1])*i+n,g=Math.abs(o-t[0])*i+a,f=(t[3]-t[1])*i,_=(t[2]-t[0])*i):(p=Math.abs(o-t[0])*i+n,g=Math.abs(l-t[1])*i+a,f=(t[2]-t[0])*i,_=(t[3]-t[1])*i),this.transform=[h*i,c*i,d*i,u*i,p-h*i*o-d*i*l,g-c*i*o-u*i*l],this.width=f,this.height=_}get rawDims(){const t=this.viewBox;return mo(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new jo({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){const i=[t,e];return Ro.applyTransform(i,this.transform),i}convertToViewportRectangle(t){const e=[t[0],t[1]];Ro.applyTransform(e,this.transform);const i=[t[2],t[3]];return Ro.applyTransform(i,this.transform),[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){const i=[t,e];return Ro.applyInverseTransform(i,this.transform),i}}class zo extends vo{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Vo(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function Uo(t){return"string"==typeof t&&/\.pdf$/i.test(t)}class Ho{started=Object.create(null);times=[];time(t){t in this.started&&uo(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||uo(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:s,end:n}of this.times)t.push(`${i.padEnd(e)} ${n-s}ms\n`);return t.join("")}}function $o(t,e){const i=e?URL.parse(t,e):URL.parse(t);return"http:"===i?.protocol||"https:"===i?.protocol}function Wo(t){t.preventDefault()}function Go(t){t.preventDefault(),t.stopPropagation()}class qo{static#i;static toDateObject(t){if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#i.exec(t);if(!e)return null;const i=parseInt(e[1],10);let s=parseInt(e[2],10);s=s>=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let c=parseInt(e[9],10)||0;return c=c>=0&&c<=59?c:0,"-"===l?(a+=h,r+=c):"+"===l&&(a-=h,r-=c),new Date(Date.UTC(i,s,n,a,r,o))}}function Ko(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):(uo(`Not a valid color format: "${t}"`),[0,0,0])}function Xo(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function Yo(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function Qo(t,e,i=!1,s=!0){if(e instanceof jo){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=Eo.isCSSRoundSupported,o=`var(--total-scale-factor) * ${s}px`,l=`var(--total-scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x))`:`calc(${o})`,c=r?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;i&&e.rotation%180!=0?(a.width=c,a.height=h):(a.width=h,a.height=c)}s&&t.setAttribute("data-main-rotation",e.rotation)}class Jo{constructor(){const{pixelRatio:t}=Jo;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,i,s,n=-1){let a=1/0,r=1/0,o=1/0;(i=Jo.capPixels(i,n))>0&&(a=Math.sqrt(i/(t*e))),-1!==s&&(r=s/t,o=s/e);const l=Math.min(a,r,o);return(this.sx>l||this.sy>l)&&(this.sx=l,this.sy=l,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}}const Zo=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class tl{#s=null;#n=null;#a;#r=null;#o=null;#l=null;static#h=null;constructor(t){this.#a=t,tl.#h||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",Wo,{signal:e}),t.addEventListener("pointerdown",tl.#c,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons",t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#s}static#c(t){t.stopPropagation()}#u(t){this.#a._focusEventsAllowed=!1,Go(t)}#p(t){this.#a._focusEventsAllowed=!0,Go(t)}#g(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#u.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#p.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Wo,{signal:e})}hide(){this.#s.classList.add("hidden"),this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden"),this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete",i.tabIndex=0,i.setAttribute("data-l10n-id",tl.#h[t]),this.#g(i),i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal}),this.#r.append(i)}get#f(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#g(e),this.#r.prepend(e,this.#f),this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#g(e),this.#r.prepend(e,this.#f)}async addEditSignatureButton(t){const e=this.#l=await t.renderEditButton(this.#a);this.#g(e),this.#r.prepend(e,this.#f)}updateEditSignatureButton(t){this.#l&&(this.#l.title=t)}remove(){this.#s.remove(),this.#n?.destroy(),this.#n=null}}class el{#r=null;#s=null;#_;constructor(t){this.#_=t}#m(){const t=this.#s=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",Wo,{signal:this.#_._signal});const e=this.#r=document.createElement("div");return e.className="buttons",t.append(e),this.#v(),t}#b(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(t<i)continue;const a=n.x+(e?n.width:0);t>i?(s=a,i=t):e?a>s&&(s=a):a<s&&(s=a)}return[e?1-s:s,i]}show(t,e,i){const[s,n]=this.#b(e,i),{style:a}=this.#s||=this.#m();t.append(this.#s),a.insetInlineEnd=100*s+"%",a.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#s.remove()}#v(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const i=this.#_._signal;t.addEventListener("contextmenu",Wo,{signal:i}),t.addEventListener("click",(()=>{this.#_.highlightSelection("floating_button")}),{signal:i}),this.#r.append(t)}}function il(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class sl{#y=0;get id(){return"pdfjs_internal_editor_"+this.#y++}}class nl{#w=Lo();#y=0;#x=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,<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>';return mo(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#A(t,e){this.#x||=new Map;let i=this.#x.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#w}_${this.#y++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await Bo(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=nl._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n,i.isSvg=!0,t()},s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=s.onerror=a}));s.readAsDataURL(t),await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){uo(t),i=null}return this.#x.set(t,i),i&&this.#x.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#A(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#A(t,t)}async getFromBlob(t,e){const i=await e;return this.#A(t,i)}async getFromId(t){this.#x||=new Map;const e=this.#x.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#x||=new Map;let i=this.#x.get(t);if(i?.bitmap)return i.refCounter+=1,i;const s=new OffscreenCanvas(e.width,e.height);return s.getContext("2d").drawImage(e,0,0),i={bitmap:s.transferToImageBitmap(),id:`image_${this.#w}_${this.#y++}`,refCounter:1,isSvg:!1},this.#x.set(t,i),this.#x.set(i.id,i),i}getSvgUrl(t){const e=this.#x.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#x||=new Map;const e=this.#x.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#w}_`)}}class al{#k=[];#T=!1;#S;#E=-1;constructor(t=128){this.#S=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(s&&t(),this.#T)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#E)return this.#k.length>0&&(this.#k.length=0),this.#E=0,void this.#k.push(o);if(a&&this.#k[this.#E].type===n)return r&&(o.undo=this.#k[this.#E].undo),void(this.#k[this.#E]=o);const l=this.#E+1;l===this.#S?this.#k.splice(0,1):(this.#E=l,l<this.#k.length&&this.#k.splice(l)),this.#k.push(o)}undo(){if(-1===this.#E)return;this.#T=!0;const{undo:t,post:e}=this.#k[this.#E];t(),e?.(),this.#T=!1,this.#E-=1}redo(){if(this.#E<this.#k.length-1){this.#E+=1,this.#T=!0;const{cmd:t,post:e}=this.#k[this.#E];t(),e?.(),this.#T=!1}}hasSomethingToUndo(){return-1!==this.#E}hasSomethingToRedo(){return this.#E<this.#k.length-1}cleanType(t){if(-1!==this.#E){for(let e=this.#E;e>=0;e--)if(this.#k[e].type!==t)return this.#k.splice(e+1,this.#E-e),void(this.#E=e);this.#k.length=0,this.#E=-1}}destroy(){this.#k=null}}class rl{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Eo.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");e&&i?(this.callbacks.set(t.slice(4),{callback:s,options:n}),this.allKeys.add(t.split("+").at(-1))):e||i||(this.callbacks.set(t,{callback:s,options:n}),this.allKeys.add(t.split("+").at(-1)))}}#C(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 i=this.callbacks.get(this.#C(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;r&&!r(t,e)||(s.bind(t,...a,e)(),n||Go(e))}}class ol{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",e.style.colorScheme="only light",document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,Ko(s))}e.remove()}(t),mo(this,"_colors",t)}convert(t){const e=Ko(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ol._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Ro.makeHexColor(...e):t}}class ll{#R=new AbortController;#M=null;#P=new Map;#L=new Map;#D=null;#I=null;#O=null;#N=new al;#F=null;#B=null;#j=0;#z=new Set;#V=null;#U=null;#H=new Set;_editorUndoBar=null;#$=!1;#W=!1;#G=!1;#q=null;#K=null;#X=null;#Y=null;#Q=!1;#J=null;#Z=new sl;#tt=!1;#et=!1;#it=null;#st=null;#nt=null;#at=null;#rt=null;#ot=zr.NONE;#lt=new Set;#ht=null;#ct=null;#dt=null;#ut=null;#pt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#gt=[0,0];#ft=null;#_t=null;#mt=null;#vt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=ll.prototype,e=t=>t.#_t.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},s=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return mo(this,"_keyboardManager",new rl([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["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:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#_t.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#_t.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,i,s,n,a,r,o,l,h,c,d,u,p){const g=this._signal=this.#R.signal;this.#_t=t,this.#mt=e,this.#D=i,this.#ct=s,this._eventBus=n,n._on("editingaction",this.onEditingAction.bind(this),{signal:g}),n._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),n._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),n._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),n._on("setpreference",this.onSetPreference.bind(this),{signal:g}),n._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:g}),this.#bt(),this.#yt(),this.#wt(),this.#I=a.annotationStorage,this.#q=a.filterFactory,this.#dt=r,this.#Y=o||null,this.#$=l,this.#W=h,this.#G=c,this.#rt=d||null,this.viewParameters={realScale:Fo.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=u||null,this._supportsPinchToZoom=!1!==p}destroy(){this.#vt?.resolve(),this.#vt=null,this.#R?.abort(),this.#R=null,this._signal=null;for(const t of this.#L.values())t.destroy();this.#L.clear(),this.#P.clear(),this.#H.clear(),this.#at?.clear(),this.#M=null,this.#lt.clear(),this.#N.destroy(),this.#D?.destroy(),this.#ct?.destroy(),this.#J?.hide(),this.#J=null,this.#nt?.destroy(),this.#nt=null,this.#K&&(clearTimeout(this.#K),this.#K=null),this.#ft&&(clearTimeout(this.#ft),this.#ft=null),this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#rt}get useNewAltTextFlow(){return this.#W}get useNewAltTextWhenAddingImage(){return this.#G}get hcmFilter(){return mo(this,"hcmFilter",this.#dt?this.#q.addHCMFilter(this.#dt.foreground,this.#dt.background):"none")}get direction(){return mo(this,"direction",getComputedStyle(this.#_t).direction)}get highlightColors(){return mo(this,"highlightColors",this.#Y?new Map(this.#Y.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return mo(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#B=t}setMainHighlightColorPicker(t){this.#nt=t}editAltText(t,e=!1){this.#D?.editAltText(this,t,e)}getSignature(t){this.#ct?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#ct}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#G=e}onPageChanging({pageNumber:t}){this.#j=t-1}focusMainContainer(){this.#_t.focus()}findParent(t,e){for(const i of this.#L.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#mt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#H.add(t)}removeShouldRescale(t){this.#H.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Fo.PDF_TO_CSS_UNITS;for(const t of this.#H)t.onScaleChanging();this.#B?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#xt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#At(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#L.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#xt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#At(o),c=this.#ot===zr.NONE,d=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r}),c&&this.showAllEditors("highlight",!0,!0)};c?this.switchToMode(zr.HIGHLIGHT,d):d()}#kt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#xt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#J||=new el(this),this.#J.show(e,i,"ltr"===this.direction))}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#Tt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#ht&&(this.#J?.hide(),this.#ht=null,this.#St({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#ht)return;const i=this.#xt(t).closest(".textLayer");if(i){if(this.#J?.hide(),this.#ht=e,this.#St({hasSelectedText:!0}),(this.#ot===zr.HIGHLIGHT||this.#ot===zr.NONE)&&(this.#ot===zr.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#Q=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#ot===zr.HIGHLIGHT?this.#At(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),n=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#Et("main_toolbar"))};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}}else this.#ht&&(this.#J?.hide(),this.#ht=null,this.#St({hasSelectedText:!1}))}#Et(t=""){this.#ot===zr.HIGHLIGHT?this.highlightSelection(t):this.#$&&this.#kt()}#bt(){document.addEventListener("selectionchange",this.#Tt.bind(this),{signal:this._signal})}#Ct(){if(this.#X)return;this.#X=new AbortController;const t=this.combinedSignal(this.#X);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Rt(){this.#X?.abort(),this.#X=null}blur(){if(this.isShiftKeyDown=!1,this.#Q&&(this.#Q=!1,this.#Et("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#lt)if(e.div.contains(t)){this.#st=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#st)return;const[t,e]=this.#st;this.#st=null,e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal}),e.focus()}#wt(){if(this.#it)return;this.#it=new AbortController;const t=this.combinedSignal(this.#it);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Mt(){this.#it?.abort(),this.#it=null}#Pt(){if(this.#F)return;this.#F=new AbortController;const t=this.combinedSignal(this.#F);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Lt(){this.#F?.abort(),this.#F=null}#yt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#wt(),this.#Pt()}removeEditListeners(){this.#Mt(),this.#Lt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#M?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#lt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#U)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void uo(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#Dt(e);this.#It(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){uo(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#ot===zr.NONE||this.isEditorHandlingKeyboard||ll._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#Q&&(this.#Q=!1,this.#Et("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#St(t){Object.entries(t).some((([t,e])=>this.#pt[t]!==e))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#pt,t)}),this.#ot===zr.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Ot([[Vr.HIGHLIGHT_FREE,!0]]))}#Ot(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Ct(),this.#Pt(),this.#St({isEditing:this.#ot!==zr.NONE,isEmpty:this.#Nt(),hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:this.#N.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Rt(),this.#Lt(),this.#St({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#U){this.#U=t;for(const t of this.#U)this.#Ot(t.defaultPropertiesToUpdate)}}getId(){return this.#Z.id}get currentLayer(){return this.#L.get(this.#j)}getLayer(t){return this.#L.get(t)}get currentPageIndex(){return this.#j}addLayer(t){this.#L.set(t.pageIndex,t),this.#tt?t.enable():t.disable()}removeLayer(t){this.#L.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#ot!==t&&(!this.#vt||(await this.#vt.promise,this.#vt))){if(this.#vt=Promise.withResolvers(),this.#B?.commitOrRemove(),this.#ot=t,t===zr.NONE)return this.setEditingState(!1),this.#Ft(),this._editorUndoBar?.hide(),void this.#vt.resolve();t===zr.SIGNATURE&&await(this.#ct?.loadSignatures()),this.setEditingState(!0),await this.#Bt(),this.unselectAll();for(const e of this.#L.values())e.updateMode(t);if(!e)return i&&this.addNewEditorFromKeyboard(),void this.#vt.resolve();for(const t of this.#P.values())t.annotationElementId===e||t.id===e?(this.setSelected(t),t.enterInEditMode()):t.unselect();this.#vt.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#ot&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#U){switch(t){case Vr.CREATE:return void this.currentLayer.addNewEditor(e);case Vr.HIGHLIGHT_DEFAULT_COLOR:this.#nt?.updateColor(e);break;case Vr.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#ut||=new Map).set(t,e),this.showAllEditors("highlight",e)}for(const i of this.#lt)i.updateParams(t,e);for(const i of this.#U)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#P.values())i.editorType===t&&i.show(e);(this.#ut?.get(Vr.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Ot([[Vr.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#et!==t){this.#et=t;for(const e of this.#L.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Bt(){if(!this.#tt){this.#tt=!0;const t=[];for(const e of this.#L.values())t.push(e.enable());await Promise.all(t);for(const t of this.#P.values())t.enable()}}#Ft(){if(this.unselectAll(),this.#tt){this.#tt=!1;for(const t of this.#L.values())t.disable();for(const t of this.#P.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#P.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#P.get(t)}addEditor(t){this.#P.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#K&&clearTimeout(this.#K),this.#K=setTimeout((()=>{this.focusMainContainer(),this.#K=null}),0)),this.#P.delete(t.id),t.annotationElementId&&this.#at?.delete(t.annotationElementId),this.unselect(t),t.annotationElementId&&this.#z.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#z.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#z.has(t)}removeDeletedAnnotationElement(t){this.#z.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#Dt(t){const e=this.#L.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#M!==t&&(this.#M=t,t&&this.#Ot(t.propertiesToUpdate))}get#jt(){let t=null;for(t of this.#lt);return t}updateUI(t){this.#jt===t&&this.#Ot(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Ot(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#lt.has(t))return this.#lt.delete(t),t.unselect(),void this.#St({hasSelectedEditor:this.hasSelection});this.#lt.add(t),t.select(),this.#Ot(t.propertiesToUpdate),this.#St({hasSelectedEditor:!0})}setSelected(t){this.#B?.commitOrRemove();for(const e of this.#lt)e!==t&&e.unselect();this.#lt.clear(),this.#lt.add(t),t.select(),this.#Ot(t.propertiesToUpdate),this.#St({hasSelectedEditor:!0})}isSelected(t){return this.#lt.has(t)}get firstSelectedEditor(){return this.#lt.values().next().value}unselect(t){t.unselect(),this.#lt.delete(t),this.#St({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#lt.size}get isEnterHandled(){return 1===this.#lt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#N.undo(),this.#St({hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Nt()}),this._editorUndoBar?.hide()}redo(){this.#N.redo(),this.#St({hasSomethingToUndo:!0,hasSomethingToRedo:this.#N.hasSomethingToRedo(),isEmpty:this.#Nt()})}addCommands(t){this.#N.add(t),this.#St({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Nt()})}cleanUndoStack(t){this.#N.cleanType(t)}#Nt(){if(0===this.#P.size)return!0;if(1===this.#P.size)for(const t of this.#P.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#lt],i=()=>{for(const t of e)this.#Dt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo:i,mustExec:!0})}commitOrRemove(){this.#M?.commitOrRemove()}hasSomethingToControl(){return this.#M||this.hasSelection}#It(t){for(const t of this.#lt)t.unselect();this.#lt.clear();for(const e of t)e.isEmpty()||(this.#lt.add(e),e.select());this.#St({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#lt)t.commit();this.#It(this.#P.values())}unselectAll(){if((!this.#M||(this.#M.commitOrRemove(),this.#ot===zr.NONE))&&!this.#B?.commitOrRemove()&&this.hasSelection){for(const t of this.#lt)t.unselect();this.#lt.clear(),this.#St({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#gt[0]+=t,this.#gt[1]+=e;const[s,n]=this.#gt,a=[...this.#lt];this.#ft&&clearTimeout(this.#ft),this.#ft=setTimeout((()=>{this.#ft=null,this.#gt[0]=this.#gt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#P.has(t.id)&&(t.translateInPage(s,n),t.translationDone())},undo:()=>{for(const t of a)this.#P.has(t.id)&&(t.translateInPage(-s,-n),t.translationDone())},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e),i.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#V=new Map;for(const t of this.#lt)this.#V.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#V)return!1;this.disableUserSelect(!1);const t=this.#V;this.#V=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t)a.newX=i,a.newY=s,a.newPageIndex=n,e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex;if(!e)return!1;const i=(t,e,i,s)=>{if(this.#P.has(t.id)){const n=this.#L.get(s);n?t._setParentAndPosition(n,e,i):(t.pageIndex=s,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:s,newY:n,newPageIndex:a}]of t)i(e,s,n,a)},undo:()=>{for(const[e,{savedX:s,savedY:n,savedPageIndex:a}]of t)i(e,s,n,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#V)for(const i of this.#V.keys())i.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.#lt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#M===t}getActive(){return this.#M}getMode(){return this.#ot}get imageManager(){return mo(this,"imageManager",new nl)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i<s;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;const{x:i,y:s,width:n,height:a}=t.getBoundingClientRect();let r;switch(t.getAttribute("data-main-rotation")){case"90":r=(t,e,r,o)=>({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;t<i;t++){const i=e.getRangeAt(t);if(!i.collapsed)for(const{x:t,y:e,width:s,height:n}of i.getClientRects())0!==s&&0!==n&&o.push(r(t,e,s,n))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#O||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#O?.delete(t)}renderAnnotationElement(t){const e=this.#O?.get(t.data.id);if(!e)return;const i=this.#I.getRawValue(e);i&&(this.#ot!==zr.NONE||i.hasBeenModified)&&i.renderAnnotationElement(t)}setMissingCanvas(t,e,i){const s=this.#at?.get(t);s&&(s.setCanvas(e,i),this.#at.delete(t))}addMissingCanvas(t,e){(this.#at||=new Map).set(t,e)}}class hl{#o=null;#zt=!1;#Vt=null;#Ut=null;#Ht=null;#$t=null;#Wt=!1;#Gt=null;#a=null;#qt=null;#Kt=null;#Xt=!1;static#Yt=null;static _l10n=null;constructor(t){this.#a=t,this.#Xt=t._uiManager.useNewAltTextFlow,hl.#Yt||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){hl._l10n??=t}async render(){const t=this.#Vt=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#Ut=document.createElement("span");t.append(e),this.#Xt?(t.classList.add("new"),t.setAttribute("data-l10n-id",hl.#Yt.missing),e.setAttribute("data-l10n-id",hl.#Yt["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const i=this.#a._uiManager._signal;t.addEventListener("contextmenu",Wo,{signal:i}),t.addEventListener("pointerdown",(t=>t.stopPropagation()),{signal:i});const s=t=>{t.preventDefault(),this.#a._uiManager.editAltText(this.#a),this.#Xt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Qt}})};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",(e=>{e.target===t&&"Enter"===e.key&&(this.#Wt=!0,s(e))}),{signal:i}),await this.#Jt(),t}get#Qt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){this.#Vt&&(this.#Vt.focus({focusVisible:this.#Wt}),this.#Wt=!1)}isEmpty(){return this.#Xt?null===this.#o:!this.#o&&!this.#zt}hasData(){return this.#Xt?null!==this.#o||!!this.#qt:this.isEmpty()}get guessedText(){return this.#qt}async setGuessedText(t){null===this.#o&&(this.#qt=t,this.#Kt=await hl._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#Jt())}toggleAltTextBadge(t=!1){if(!this.#Xt||this.#o)return this.#Gt?.remove(),void(this.#Gt=null);if(!this.#Gt){const t=this.#Gt=document.createElement("div");t.className="noAltTextBadge",this.#a.div.append(t)}this.#Gt.classList.toggle("hidden",!t)}serialize(t){let e=this.#o;return t||this.#qt!==e||(e=this.#Kt),{altText:e,decorative:this.#zt,guessedText:this.#qt,textWithDisclaimer:this.#Kt}}get data(){return{altText:this.#o,decorative:this.#zt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){i&&(this.#qt=i,this.#Kt=s),this.#o===t&&this.#zt===e||(n||(this.#o=t,this.#zt=e),this.#Jt())}toggle(t=!1){this.#Vt&&(!t&&this.#$t&&(clearTimeout(this.#$t),this.#$t=null),this.#Vt.disabled=!t)}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Qt}})}destroy(){this.#Vt?.remove(),this.#Vt=null,this.#Ut=null,this.#Ht=null,this.#Gt?.remove(),this.#Gt=null}async#Jt(){const t=this.#Vt;if(!t)return;if(this.#Xt){if(t.classList.toggle("done",!!this.#o),t.setAttribute("data-l10n-id",hl.#Yt[this.#Qt]),this.#Ut?.setAttribute("data-l10n-id",hl.#Yt[`${this.#Qt}-label`]),!this.#o)return void this.#Ht?.remove()}else{if(!this.#o&&!this.#zt)return t.classList.remove("done"),void this.#Ht?.remove();t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#Ht;if(!e){this.#Ht=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#$t),this.#$t=null}),{once:!0}),t.addEventListener("mouseenter",(()=>{this.#$t=setTimeout((()=>{this.#$t=null,this.#Ht.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s}),t.addEventListener("mouseleave",(()=>{this.#$t&&(clearTimeout(this.#$t),this.#$t=null),this.#Ht?.classList.remove("show")}),{signal:s})}this.#zt?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#o),e.parentNode||t.append(e);const i=this.#a.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class cl{#_t;#Zt=!1;#te=null;#ee;#ie;#se;#ne;#ae=null;#re;#oe=null;#le;#he=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#_t=t,this.#te=i,this.#ee=e,this.#ie=s,this.#se=n,this.#ne=a,this.#le=new AbortController,this.#re=AbortSignal.any([r,this.#le.signal]),t.addEventListener("touchstart",this.#ce.bind(this),{passive:!1,signal:this.#re})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Jo.pixelRatio}#ce(t){if(this.#ee?.())return;if(1===t.touches.length){if(this.#ae)return;const t=this.#ae=new AbortController,e=AbortSignal.any([this.#re,t.signal]),i=this.#_t,s={capture:!0,signal:e,passive:!1},n=t=>{"touch"===t.pointerType&&(this.#ae?.abort(),this.#ae=null)};return i.addEventListener("pointerdown",(t=>{"touch"===t.pointerType&&(Go(t),n(t))}),s),i.addEventListener("pointerup",n,s),void i.addEventListener("pointercancel",n,s)}if(!this.#he){this.#he=new AbortController;const t=AbortSignal.any([this.#re,this.#he.signal]),e=this.#_t,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#de.bind(this),i);const s=this.#ue.bind(this);e.addEventListener("touchend",s,i),e.addEventListener("touchcancel",s,i),i.capture=!0,e.addEventListener("pointerdown",Go,i),e.addEventListener("pointermove",Go,i),e.addEventListener("pointercancel",Go,i),e.addEventListener("pointerup",Go,i),this.#ie?.()}if(Go(t),2!==t.touches.length||this.#te?.())return void(this.#oe=null);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]),this.#oe={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#de(t){if(!this.#oe||2!==t.touches.length)return;Go(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:a,screenY:r}=i,o=this.#oe,{touch0X:l,touch0Y:h,touch1X:c,touch1Y:d}=o,u=c-l,p=d-h,g=a-s,f=r-n,_=Math.hypot(g,f)||1,m=Math.hypot(u,p)||1;if(!this.#Zt&&Math.abs(m-_)<=cl.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(o.touch0X=s,o.touch0Y=n,o.touch1X=a,o.touch1Y=r,!this.#Zt)return void(this.#Zt=!0);const v=[(s+a)/2,(n+r)/2];this.#se?.(v,m,_)}#ue(t){t.touches.length>=2||(this.#he&&(this.#he.abort(),this.#he=null,this.#ne?.()),this.#oe&&(Go(t),this.#oe=null,this.#Zt=!1))}destroy(){this.#le?.abort(),this.#le=null,this.#ae?.abort(),this.#ae=null}}class dl{#pe=null;#ge=null;#o=null;#fe=!1;#_e=null;#me="";#ve=!1;#be=null;#ye=null;#we=null;#xe=null;#Ae="";#ke=!1;#Te=null;#Se=!1;#Ee=!1;#Ce=!1;#Re=null;#Me=0;#Pe=0;#Le=null;#De=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#Ie=!1;#Oe=dl._zIndex++;static _borderLineWidth=-1;static _colorManager=new ol;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=dl.prototype._resizeWithKeyboard,e=ll.TRANSLATE_SMALL,i=ll.TRANSLATE_BIG;return mo(this,"_resizerKeyboardManager",new rl([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],dl.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,s],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 isDrawer(){return!1}static get _defaultLineColor(){return mo(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new ul({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(dl._l10n??=t,dl._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),-1!==dl._borderLineWidth)return;const i=getComputedStyle(document.documentElement);dl._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){po("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#Ie}set _isDraggable(t){this.#Ie=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.#Oe}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#Ne(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ke?this.#ke=!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,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s),this.x=(t+i)/n,this.y=(e+s)/a,this.fixAndSetPosition()}_moveAfterPaste(t,e){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s),this._onTranslated()}#Fe([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s),this.x+=i/t,this.y+=s/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#Fe(this.parentDimensions,t,e)}translateInPage(t,e){this.#Te||=[this.x,this.y,this.width,this.height],this.#Fe(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Te||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;if(this.x+=t/s,this.y+=e/n,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:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o,r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`,h.top=`${(100*r).toFixed(2)}%`,this._onTranslating(a,r),i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Te&&(this.#Te[0]!==this.x||this.#Te[1]!==this.y)}get _hasBeenResized(){return!!this.#Te&&(this.#Te[2]!==this.width||this.#Te[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=dl,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:a,width:r,height:o}=this;if(r*=i,o*=s,n*=i,a*=s,this._mustFixPosition)switch(t){case 0:n=Io(n,0,i-r),a=Io(a,0,s-o);break;case 90:n=Io(n,0,i-o),a=Io(a,r,s);break;case 180:n=Io(n,r,i),a=Io(a,o,s);break;case 270:n=Io(n,o,i),a=Io(a,0,s-r)}this.x=n/=i,this.y=a/=s;const[l,h]=this.getBaseTranslation();n+=l,a+=h,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#Be(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return dl.#Be(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return dl.#Be(t,e,360-this.parentRotation)}#je(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/i).toFixed(2)}%`,this.#ve||(n.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#ve&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`),this.#ve||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#ze(){if(this.#be)return;this.#be=document.createElement("div"),this.#be.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#be.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#Ve.bind(this,i),{signal:e}),t.addEventListener("contextmenu",Wo,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#be)}#Ve(t,e){e.preventDefault();const{isMac:i}=Eo.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1,this.#ye=[e.screenX,e.screenY];const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#Ue.bind(this,t),{passive:!0,capture:!0,signal:a}),window.addEventListener("touchmove",Go,{passive:!1,signal:a}),window.addEventListener("contextmenu",Wo,{signal:a}),this.#we={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#o?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=r,this.div.style.cursor=o,this.#He()};window.addEventListener("pointerup",l,{signal:a}),window.addEventListener("blur",l,{signal:a})}#$e(t,e,i,s){this.width=i,this.height=s,this.x=t,this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s),this.fixAndSetPosition(),this._onResized()}_onResized(){}#He(){if(!this.#we)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#we;this.#we=null;const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:this.#$e.bind(this,n,a,r,o),undo:this.#$e.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Ue(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=dl.MIN_SIZE/i,h=dl.MIN_SIZE/s,c=this.#je(this.rotation),d=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],u=this.#je(360-this.rotation);let p,g,f=!1,_=!1;switch(t){case"topLeft":f=!0,p=(t,e)=>[0,0],g=(t,e)=>[t,e];break;case"topMiddle":p=(t,e)=>[t/2,0],g=(t,e)=>[t/2,e];break;case"topRight":f=!0,p=(t,e)=>[t,0],g=(t,e)=>[0,e];break;case"middleRight":_=!0,p=(t,e)=>[t,e/2],g=(t,e)=>[0,e/2];break;case"bottomRight":f=!0,p=(t,e)=>[t,e],g=(t,e)=>[0,0];break;case"bottomMiddle":p=(t,e)=>[t/2,e],g=(t,e)=>[t/2,0];break;case"bottomLeft":f=!0,p=(t,e)=>[0,e],g=(t,e)=>[t,0];break;case"middleLeft":_=!0,p=(t,e)=>[0,e/2],g=(t,e)=>[t,e/2]}const m=p(r,o),v=g(r,o);let b=d(...v);const y=dl._round(n+b[0]),w=dl._round(a+b[1]);let x,A,k=1,T=1;if(e.fromKeyboard)({deltaX:x,deltaY:A}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#ye;[x,A]=this.screenToPageTranslation(t-s,i-n),this.#ye[0]=t,this.#ye[1]=i}if([x,A]=((t,e)=>[u[0]*t+u[2]*e,u[1]*t+u[3]*e])(x/i,A/s),f){const t=Math.hypot(r,o);k=T=Math.max(Math.min(Math.hypot(v[0]-m[0]-x,v[1]-m[1]-A)/t,1/r,1/o),l/r,h/o)}else _?k=Io(Math.abs(v[0]-m[0]-x),l,1)/r:T=Io(Math.abs(v[1]-m[1]-A),h,1)/o;const S=dl._round(r*k),E=dl._round(o*T);b=d(...g(S,E));const C=y-b[0],R=w-b[1];this.#Te||=[this.x,this.y,this.width,this.height],this.width=S,this.height=E,this.x=C,this.y=R,this.setDims(i*S,s*E),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){return this._editToolbar||this.#Ee||(this._editToolbar=new tl(this),this.div.append(this._editToolbar.render()),this.#o&&await this._editToolbar.addAltText(this.#o)),this._editToolbar}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#o?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#o||(hl.initialize(dl._l10n),this.#o=new hl(this),this.#pe&&(this.#o.data=this.#pe,this.#pe=null),await this.addEditToolbar())}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#fe?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#We();const[e,i]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*i/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/i).toFixed(2)}%`);const[s,n]=this.getInitialTranslation();return this.translate(s,n),il(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#De||=new cl({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ge.bind(this),onPinching:this.#qe.bind(this),onPinchEnd:this.#Ke.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),t}#Ge(){this.#we={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#o?.toggle(!1),this.parent.togglePointerEvents(!1)}#qe(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#je(this.rotation),a=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[r,o]=this.parentDimensions,l=this.x,h=this.y,c=this.width,d=this.height,u=dl.MIN_SIZE/r,p=dl.MIN_SIZE/o;s=Math.max(Math.min(s,1/c,1/d),u/c,p/d);const g=dl._round(c*s),f=dl._round(d*s);if(g===c&&f===d)return;this.#Te||=[l,h,c,d];const _=a(c/2,d/2),m=dl._round(l+_[0]),v=dl._round(h+_[1]),b=a(g/2,f/2);this.x=m-b[0],this.y=v-b[1],this.width=g,this.height=f,this.setDims(r*g,o*f),this.fixAndSetPosition(),this._onResizing()}#Ke(){this.#o?.toggle(!0),this.parent.togglePointerEvents(!0),this.#He()}pointerdown(t){const{isMac:e}=Eo.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#ke=!0,this._isDraggable?this.#Xe(t):this.#Ye(t))}#Ye(t){const{isMac:e}=Eo.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#Xe(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),a={capture:!0,passive:!1,signal:n},r=t=>{s.abort(),this.#_e=null,this.#ke=!1,this._uiManager.endDragSession()||this.#Ye(t),i&&this._onStopDragging()};e&&(this.#Me=t.clientX,this.#Pe=t.clientY,this.#_e=t.pointerId,this.#me=t.pointerType,window.addEventListener("pointermove",(t=>{i||(i=!0,this._onStartDragging());const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#_e)return void Go(t);const[a,r]=this.screenToPageTranslation(e-this.#Me,s-this.#Pe);this.#Me=e,this.#Pe=s,this._uiManager.dragSelectedEditors(a,r)}),a),window.addEventListener("touchmove",Go,a),window.addEventListener("pointerdown",(t=>{t.pointerType===this.#me&&(this.#De||t.isPrimary)&&r(t),Go(t)}),a));const o=t=>{this.#_e&&this.#_e!==t.pointerId?Go(t):r(t)};window.addEventListener("pointerup",o,{signal:n}),window.addEventListener("blur",o,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Re&&clearTimeout(this.#Re),this.#Re=setTimeout((()=>{this.#Re=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,c=this.x*n,d=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[c+l+r,a-d-h-p+o,c+l+u+r,a-d-h+o];case 90:return[c+h+r,a-d+l+o,c+h+p+r,a-d+l+u+o];case 180:return[c-l-u+r,a-d+h+o,c-l+r,a-d+h+p+o];case 270:return[c-h-p+r,a-d-l-u+o,c-h+r,a-d-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#Ee=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#Ee=!1,!0)}isInEditMode(){return this.#Ee}shouldGetKeyboardEvents(){return this.#Ce}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:a}=window;return e<a&&s>0&&t<n&&i>0}#We(){if(this.#xe||!this.div)return;this.#xe=new AbortController;const t=this._uiManager.combinedSignal(this.#xe);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#We()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){po("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation,s.#pe=t.accessibilityData,s._isCopy=t.isCopy||!1;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);return s.x=r/n,s.y=o/a,s.width=l/n,s.height=h/a,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#xe?.abort(),this.#xe=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#Re&&(clearTimeout(this.#Re),this.#Re=null),this.#Ne(),this.removeEditToolbar(),this.#Le){for(const t of this.#Le.values())clearTimeout(t);this.#Le=null}this.parent=null,this.#De?.destroy(),this.#De=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#ze(),this.#be.classList.remove("hidden"))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#we={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#be.children;if(!this.#ge){this.#ge=Array.from(e);const t=this.#Qe.bind(this),i=this.#Je.bind(this),s=this._uiManager._signal;for(const e of this.#ge){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:s}),e.addEventListener("blur",i,{signal:s}),e.addEventListener("focus",this.#Ze.bind(this,n),{signal:s}),e.setAttribute("data-l10n-id",dl._l10nResizer[n])}}const i=this.#ge[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#ge.length/4);if(n!==s){if(n<s)for(let t=0;t<s-n;t++)this.#be.append(this.#be.firstChild);else if(n>s)for(let t=0;t<n-s;t++)this.#be.firstChild.before(this.#be.lastChild);let t=0;for(const i of e){const e=this.#ge[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",dl._l10nResizer[e])}}this.#ti(0),this.#Ce=!0,this.#be.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#Qe(t){dl._resizerKeyboardManager.exec(this,t)}#Je(t){this.#Ce&&t.relatedTarget?.parentNode!==this.#be&&this.#Ne()}#Ze(t){this.#Ae=this.#Ce?t:""}#ti(t){if(this.#ge)for(const e of this.#ge)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#Ce&&this.#Ue(this.#Ae,{deltaX:t,deltaY:e,fromKeyboard:!0})}#Ne(){this.#Ce=!1,this.#ti(-1),this.#He()}_stopResizingWithKeyboard(){this.#Ne(),this.div.focus()}select(){this.isSelected&&this._editToolbar||(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),this._editToolbar?(this._editToolbar?.show(),this.#o?.toggleAltTextBadge(!1)):this.addEditToolbar().then((()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()})))}unselect(){this.isSelected&&(this.isSelected=!1,this.#be?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#o?.toggleAltTextBadge(!0))}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.id})}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#Se}set isEditing(t){this.#Se=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#ve=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i,s.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.#Le||=new Map;const{action:e}=t;let i=this.#Le.get(e);return i&&clearTimeout(i),i=setTimeout((()=>{this._reportTelemetry(t),this.#Le.delete(e),0===this.#Le.size&&(this.#Le=null)}),dl._telemetryTimeout),void this.#Le.set(e,i)}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.#fe=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#fe=!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 ul extends dl{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const pl=3285377520,gl=4294901760,fl=65535;class _l{constructor(t){this.h1=t?4294967295&t:pl,this.h2=t?4294967295&t:pl}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let s=0,n=t.length;s<n;s++){const n=t.charCodeAt(s);n<=255?e[i++]=n:(e[i++]=n>>>8,e[i++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let t=0;t<s;t++)1&t?(r=a[t],r=r*c&gl|r*u&fl,r=r<<15|r>>>17,r=r*d&gl|r*p&fl,l^=r,l=l<<13|l>>>19,l=5*l+3864292196):(o=a[t],o=o*c&gl|o*u&fl,o=o<<15|o>>>17,o=o*d&gl|o*p&fl,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(r=0,n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s],r=r*c&gl|r*u&fl,r=r<<15|r>>>17,r=r*d&gl|r*p&fl,1&s?l^=r:h^=r}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&gl|36045*t&fl,e=4283543511*e&gl|(2950163797*(e<<16|t>>>16)&gl)>>>16,t^=e>>>1,t=444984403*t&gl|60499*t&fl,e=3301882366*e&gl|(3120437893*(e<<16|t>>>16)&gl)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const ml=Object.freeze({map:null,hash:"",transfer:void 0});class vl{#ei=!1;#ii=null;#si=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const i=this.#si.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#si.get(t)}remove(t){if(this.#si.delete(t),0===this.#si.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor){for(const t of this.#si.values())if(t instanceof dl)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#si.get(t);let s=!1;if(void 0!==i)for(const[t,n]of Object.entries(e))i[t]!==n&&(s=!0,i[t]=n);else s=!0,this.#si.set(t,e);s&&this.#ni(),e instanceof dl&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#si.has(t)}get size(){return this.#si.size}#ni(){this.#ei||(this.#ei=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#ei&&(this.#ei=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new bl(this)}get serializable(){if(0===this.#si.size)return ml;const t=new Map,e=new _l,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#si){const r=a instanceof dl?a.serialize(!1,s):a;r&&(t.set(i,r),e.update(`${i}:${JSON.stringify(r)}`),n||=!!r.bitmap)}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:ml}get editorStats(){let t=null;const e=new Map;for(const i of this.#si.values()){if(!(i instanceof dl))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor),t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);i||(i=new Map,a.set(t,i));const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#ii=null}get modifiedIds(){if(this.#ii)return this.#ii;const t=[];for(const e of this.#si.values())e instanceof dl&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#ii={ids:new Set(t),hash:t.join(",")}}[Symbol.iterator](){return this.#si.entries()}}class bl extends vl{#ai;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#ai={map:n,hash:i,transfer:s}}get print(){po("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ai}get modifiedIds(){return mo(this,"modifiedIds",{ids:new Set,hash:""})}}class yl{#ri=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.#ri.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#ri.has(t.loadedName))if(go(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:e,src:s,style:n}=t,a=new FontFace(e,s,n);this.addNativeFontFace(a);try{await a.load(),this.#ri.add(e),i?.(t)}catch{uo(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}}else po("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(i){throw uo(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return mo(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return mo(this,"isSyncFontLoadingSupported",Cr||Eo.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(go(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return mo(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function s(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=s(c,976,h.length,h);const d=1482184792;let u=i(c,16);for(n=0,a=h.length-3;n<a;n+=4)u=u-d+i(h,n)|0;var p;n<h.length&&(u=u-d+i(h+"XXX",n)|0),c=s(c,16,4,(p=u,String.fromCharCode(p>>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${h}";src:${`url(data:font/opentype;base64,${btoa(c)});`}}`;this.insertRule(g);const f=this._document.createElement("div");f.style.visibility="hidden",f.style.width=f.style.height="10px",f.style.position="absolute",f.style.top=f.style.left="0px";for(const e of[t.loadedName,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,f.append(t)}this._document.body.append(f),function t(e,i){if(++l>30)return uo("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,(()=>{f.remove(),e.complete()}))}}class wl{constructor(t,e=null){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this._inspectFont=e}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=`url(data:${this.mimetype};base64,${Oo(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){uo(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");return this.fontExtraProperties||t.delete(i),this.compiledGlyphs[e]=n}}function xl(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const Al=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,kl=function(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[s,n,...a]=i;if(!t(s)&&!Number.isInteger(s))return!1;if(!e(n))return!1;const r=a.length;let o=!0;switch(n.name){case"XYZ":if(r<2||r>3)return!1;break;case"Fit":case"FitB":return 0===r;case"FitH":case"FitBH":case"FitV":case"FitBV":if(r>1)return!1;break;case"FitR":if(4!==r)return!1;o=!1;break;default:return!1}for(const t of a)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,Al,(t=>"object"==typeof t&&"string"==typeof t?.name));class Tl{#oi=new Map;#li=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#li.then((()=>{for(const[t]of this.#oi)t.call(this,i)}))}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted)return void uo("LoopbackPort - cannot use an `aborted` signal.");const a=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",a),n.addEventListener("abort",a)}this.#oi.set(e,s)}removeEventListener(t,e){const i=this.#oi.get(e);i?.(),this.#oi.delete(e)}terminate(){for(const[,t]of this.#oi)t?.();this.#oi.clear()}}const Sl=1,El=2,Cl=1,Rl=2,Ml=3,Pl=4,Ll=5,Dl=6,Il=7,Ol=8;function Nl(){}function Fl(t){if(t instanceof ko||t instanceof wo||t instanceof bo||t instanceof xo||t instanceof yo)return t;switch(t instanceof Error||"object"==typeof t&&null!==t||po('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new ko(t.message);case"InvalidPDFException":return new wo(t.message);case"PasswordException":return new bo(t.message,t.code);case"ResponseException":return new xo(t.message,t.status,t.missing);case"UnknownErrorException":return new yo(t.message,t.details)}return new yo(t.message,t.toString())}class Bl{#hi=new AbortController;constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),i.addEventListener("message",this.#ci.bind(this),{signal:this.#hi.signal})}#ci({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#di(t);if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===Sl)i.resolve(t.data);else{if(t.callback!==El)throw new Error("Unexpected callback case");i.reject(Fl(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:i,targetName:s,callback:Sl,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:i,targetName:s,callback:El,callbackId:t.callbackId,reason:Fl(e)})}))}else t.streamId?this.#ui(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:Dl,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{go(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:Cl,streamId:n,reason:Fl(t)}),e.promise}},i)}#ui(t){const e=t.streamId,i=this.sourceName,s=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:i,targetName:s,stream:Pl,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:Ml,streamId:e}),delete a.streamSinks[e])},error(t){go(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:Ll,streamId:e,reason:Fl(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,Promise.try(r,t.data,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:Ol,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:Ol,streamId:e,reason:Fl(t)})}))}#di(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case Ol:t.success?a.startCall.resolve():a.startCall.reject(Fl(t.reason));break;case Il:t.success?a.pullCall.resolve():a.pullCall.reject(Fl(t.reason));break;case Dl:if(!r){n.postMessage({sourceName:i,targetName:s,stream:Il,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,Promise.try(r.onPull||Nl).then((function(){n.postMessage({sourceName:i,targetName:s,stream:Il,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:Il,streamId:e,reason:Fl(t)})}));break;case Pl:if(go(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case Ml:if(go(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#pi(a,e);break;case Ll:go(a,"error should have stream controller"),a.controller.error(Fl(t.reason)),this.#pi(a,e);break;case Rl:t.success?a.cancelCall.resolve():a.cancelCall.reject(Fl(t.reason)),this.#pi(a,e);break;case Cl:if(!r)break;const o=Fl(t.reason);Promise.try(r.onCancel||Nl,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:Rl,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:Rl,streamId:e,reason:Fl(t)})})),r.sinkCapability.reject(o),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#pi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#hi?.abort(),this.#hi=null}}class jl{#gi=!1;constructor({enableHWA:t=!1}){this.#gi=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#gi})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){po("Abstract method `_createCanvas` called.")}}class zl extends jl{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}}class Vl{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){po("Abstract method `_fetch` called.")}}class Ul extends Vl{async _fetch(t){const e=await Bo(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):So(e)}}class Hl{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class $l extends Hl{#fi;#_i;#mi;#vi;#bi;#yi;#y=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#vi=t,this.#bi=e}get#x(){return this.#_i||=new Map}get#wi(){return this.#yi||=new Map}get#xi(){if(!this.#mi){const t=this.#bi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#bi.createElementNS(No,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#mi=this.#bi.createElementNS(No,"defs"),t.append(i),i.append(this.#mi),this.#bi.body.append(t)}return this.#mi}#Ai(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++)n[t]=e[t]/255,a[t]=i[t]/255,r[t]=s[t]/255;return[n.join(","),a.join(","),r.join(",")]}#ki(t){if(void 0===this.#fi){this.#fi="";const t=this.#bi.URL;t!==this.#bi.baseURI&&(Vo(t)?uo('#createUrl: ignore "data:"-URL for performance reasons.'):this.#fi=_o(t,""))}return`url(${this.#fi}#${t})`}addFilter(t){if(!t)return"none";let e=this.#x.get(t);if(e)return e;const[i,s,n]=this.#Ai(t),a=1===t.length?i:`${i}${s}${n}`;if(e=this.#x.get(a),e)return this.#x.set(t,e),e;const r=`g_${this.#vi}_transfer_map_${this.#y++}`,o=this.#ki(r);this.#x.set(t,o),this.#x.set(a,o);const l=this.#Ti(r);return this.#Si(i,s,n,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#wi.get(s);if(n?.key===i)return n.url;if(n?(n.filter?.remove(),n.key=i,n.url="none",n.filter=null):(n={key:i,url:"none",filter:null},this.#wi.set(s,n)),!t||!e)return n.url;const a=this.#Ei(t);t=Ro.makeHexColor(...a);const r=this.#Ei(e);if(e=Ro.makeHexColor(...r),this.#xi.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 l=o.join(","),h=`g_${this.#vi}_hcm_filter`,c=n.filter=this.#Ti(h);this.#Si(l,l,l,c),this.#Ci(c);const d=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};return this.#Si(d(0,5),d(1,5),d(2,5),c),n.url=this.#ki(h),n.url}addAlphaFilter(t){let e=this.#x.get(t);if(e)return e;const[i]=this.#Ai([t]),s=`alpha_${i}`;if(e=this.#x.get(s),e)return this.#x.set(t,e),e;const n=`g_${this.#vi}_alpha_map_${this.#y++}`,a=this.#ki(n);this.#x.set(t,a),this.#x.set(s,a);const r=this.#Ti(n);return this.#Ri(i,r),a}addLuminosityFilter(t){let e,i,s=this.#x.get(t||"luminosity");if(s)return s;if(t?([e]=this.#Ai([t]),i=`luminosity_${e}`):i="luminosity",s=this.#x.get(i),s)return this.#x.set(t,s),s;const n=`g_${this.#vi}_luminosity_map_${this.#y++}`,a=this.#ki(n);this.#x.set(t,a),this.#x.set(i,a);const r=this.#Ti(n);return this.#Mi(r),t&&this.#Ri(e,r),a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#wi.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.#wi.set(t,r)),!e||!i)return r.url;const[o,l]=[e,i].map(this.#Ei.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,u]=[s,n].map(this.#Ei.bind(this));c<h&&([h,c,d,u]=[c,h,u,d]),this.#xi.style.color="";const p=(t,e,i)=>{const s=new Array(256),n=(c-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},g=`g_${this.#vi}_hcm_${t}_filter`,f=r.filter=this.#Ti(g);return this.#Ci(f),this.#Si(p(d[0],u[0],5),p(d[1],u[1],5),p(d[2],u[2],5),f),r.url=this.#ki(g),r.url}destroy(t=!1){t&&this.#yi?.size||(this.#mi?.parentNode.parentNode.remove(),this.#mi=null,this.#_i?.clear(),this.#_i=null,this.#yi?.clear(),this.#yi=null,this.#y=0)}#Mi(t){const e=this.#bi.createElementNS(No,"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)}#Ci(t){const e=this.#bi.createElementNS(No,"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)}#Ti(t){const e=this.#bi.createElementNS(No,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#xi.append(e),e}#Pi(t,e,i){const s=this.#bi.createElementNS(No,e);s.setAttribute("type","discrete"),s.setAttribute("tableValues",i),t.append(s)}#Si(t,e,i,s){const n=this.#bi.createElementNS(No,"feComponentTransfer");s.append(n),this.#Pi(n,"feFuncR",t),this.#Pi(n,"feFuncG",e),this.#Pi(n,"feFuncB",i)}#Ri(t,e){const i=this.#bi.createElementNS(No,"feComponentTransfer");e.append(i),this.#Pi(i,"feFuncA",t)}#Ei(t){return this.#xi.style.color=t,Ko(getComputedStyle(this.#xi).getPropertyValue("color"))}}class Wl{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){po("Abstract method `_fetch` called.")}}class Gl extends Wl{async _fetch(t){const e=await Bo(t,"arraybuffer");return new Uint8Array(e)}}class ql{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!t)throw new Error("Wasm filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load wasm data at: ${e}`)}))}async _fetch(t){po("Abstract method `_fetch` called.")}}class Kl extends ql{async _fetch(t){const e=await Bo(t,"arraybuffer");return new Uint8Array(e)}}async function Xl(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}Cr&&uo("Please use the `legacy` build in Node.js environments.");class Yl extends Hl{}class Ql extends jl{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class Jl extends Vl{async _fetch(t){return Xl(t)}}class Zl extends Wl{async _fetch(t){return Xl(t)}}class th extends ql{async _fetch(t){return Xl(t)}}const eh="Fill",ih="Stroke",sh="Shading";function nh(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s),t.clip(n)}class ah{isModifyingCurrentTransform(){return!1}getPattern(){po("Abstract method `getPattern` called.")}}class rh extends ah{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,i,s){let n;if(s===ih||s===eh){const a=e.current.getClippedPathBoundingBox(s,Xo(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-a[0],-a[1]),i=Ro.transform(i,[1,0,0,1,a[0],a[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),nh(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),n=t.createPattern(l.canvas,"no-repeat");const c=new DOMMatrix(i);n.setTransform(c)}else nh(t,this._bbox),n=this._createGradient(t);return n}}function oh(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,c=t.data,d=4*t.width;let u;l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u),l[s+1]>l[n+1]&&(u=s,s=n,n=u,u=r,r=o,o=u),l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u);const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,f=(l[s]+e.offsetX)*e.scaleX,_=(l[s+1]+e.offsetY)*e.scaleY,m=(l[n]+e.offsetX)*e.scaleX,v=(l[n+1]+e.offsetY)*e.scaleY;if(g>=v)return;const b=h[a],y=h[a+1],w=h[a+2],x=h[r],A=h[r+1],k=h[r+2],T=h[o],S=h[o+1],E=h[o+2],C=Math.round(g),R=Math.round(v);let M,P,L,D,I,O,N,F;for(let t=C;t<=R;t++){if(t<_){const e=t<g?0:(g-t)/(g-_);M=p-(p-f)*e,P=b-(b-x)*e,L=y-(y-A)*e,D=w-(w-k)*e}else{let e;e=t>v?1:_===v?0:(_-t)/(_-v),M=f-(f-m)*e,P=x-(x-T)*e,L=A-(A-S)*e,D=k-(k-E)*e}let e;e=t<g?0:t>v?1:(g-t)/(g-v),I=p-(p-m)*e,O=b-(b-T)*e,N=y-(y-S)*e,F=w-(w-E)*e;const i=Math.round(Math.min(M,I)),s=Math.round(Math.max(M,I));let n=d*t+4*i;for(let t=i;t<=s;t++)e=(M-t)/(M-I),e<0?e=0:e>1&&(e=1),c[n++]=P-(P-O)*e|0,c[n++]=L-(L-N)*e|0,c[n++]=D-(D-F)*e|0,c[n++]=255}}function lh(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a<l;a++){let e=a*o;for(let a=0;a<h;a++,e++)oh(t,i,s[e],s[e+1],s[e+o],n[e],n[e+1],n[e+o]),oh(t,i,s[e+o+1],s[e+1],s[e+o],n[e+o+1],n[e+1],n[e+o])}break;case"triangles":for(a=0,r=s.length;a<r;a+=3)oh(t,i,s[a],s[a+1],s[a+2],n[a],n[a+1],n[a+2]);break;default:throw new Error("illegal figure")}}class hh extends ah{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null}_createMeshCanvas(t,e,i){const s=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),a=Math.ceil(this._bounds[2])-s,r=Math.ceil(this._bounds[3])-n,o=Math.min(Math.ceil(Math.abs(a*t[0]*1.1)),3e3),l=Math.min(Math.ceil(Math.abs(r*t[1]*1.1)),3e3),h=a/o,c=r/l,d={coords:this._coords,colors:this._colors,offsetX:-s,offsetY:-n,scaleX:1/h,scaleY:1/c},u=o+4,p=l+4,g=i.getCanvas("mesh",u,p),f=g.context,_=f.createImageData(o,l);if(e){const t=_.data;for(let i=0,s=t.length;i<s;i+=4)t[i]=e[0],t[i+1]=e[1],t[i+2]=e[2],t[i+3]=255}for(const t of this._figures)lh(_,t,d);f.putImageData(_,2,2);return{canvas:g.canvas,offsetX:s-2*h,offsetY:n-2*c,scaleX:h,scaleY:c}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,s){nh(t,this._bbox);const n=new Float32Array(2);if(s===sh)Ro.singularValueDecompose2dScale(Xo(t),n);else if(this.matrix){Ro.singularValueDecompose2dScale(this.matrix,n);const[t,i]=n;Ro.singularValueDecompose2dScale(e.baseTransform,n),n[0]*=t,n[1]*=i}else Ro.singularValueDecompose2dScale(e.baseTransform,n);const a=this._createMeshCanvas(n,s===sh?null:this._background,e.cachedCanvases);return s!==sh&&(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 ch extends ah{getPattern(){return"hotpink"}}const dh=1,uh=2;class ph{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,s){this.color=t[1],this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.ctx=e,this.canvasGraphicsFactory=i,this.baseTransform=s}createPatternCanvas(t){const{bbox:e,operatorList:i,paintType:s,tilingType:n,color:a,canvasGraphicsFactory:r}=this;let{xstep:o,ystep:l}=this;o=Math.abs(o),l=Math.abs(l),co("TilingType: "+n);const h=e[0],c=e[1],d=e[2],u=e[3],p=d-h,g=u-c,f=new Float32Array(2);Ro.singularValueDecompose2dScale(this.matrix,f);const[_,m]=f;Ro.singularValueDecompose2dScale(this.baseTransform,f);const v=_*f[0],b=m*f[1];let y=p,w=g,x=!1,A=!1;const k=Math.ceil(o*v),T=Math.ceil(l*b);k>=Math.ceil(p*v)?y=o:x=!0,T>=Math.ceil(g*b)?w=l:A=!0;const S=this.getSizeAndScale(y,this.ctx.canvas.width,v),E=this.getSizeAndScale(w,this.ctx.canvas.height,b),C=t.cachedCanvases.getCanvas("pattern",S.size,E.size),R=C.context,M=r.createCanvasGraphics(R);if(M.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(M,s,a),R.translate(-S.scale*h,-E.scale*c),M.transform(S.scale,0,0,E.scale,0,0),R.save(),this.clipBbox(M,h,c,d,u),M.baseTransform=Xo(M.ctx),M.executeOperatorList(i),M.endDrawing(),R.restore(),x||A){const e=C.canvas;x&&(y=o),A&&(w=l);const i=this.getSizeAndScale(y,this.ctx.canvas.width,v),s=this.getSizeAndScale(w,this.ctx.canvas.height,b),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),d=r.context,u=x?Math.floor(p/o):0,f=A?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=f;i++)d.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:c}}return{canvas:C.canvas,scaleX:S.scale,scaleY:E.scale,offsetX:h,offsetY:c}}getSizeAndScale(t,e,i){const s=Math.max(ph.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);return n>=s?n=s:i=n/t,{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r),Ro.axialAlignedBoundingBox([e,i,s,n],Xo(t.ctx),t.current.minMax),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case dh:const{fillStyle:t,strokeStyle:a}=this.ctx;s.fillStyle=n.fillColor=t,s.strokeStyle=n.strokeColor=a;break;case uh:s.fillStyle=s.strokeStyle=i,n.fillColor=n.strokeColor=i;break;default:throw new Ao(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,s){let n=i;s!==sh&&(n=Ro.transform(n,e.baseTransform),this.matrix&&(n=Ro.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 gh({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=Eo.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],c=s>>3,d=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s<n;s++){for(const s=e+c;e<s;e++){const s=e<u?t[e]:255;i[p++]=128&s?h:l,i[p++]=64&s?h:l,i[p++]=32&s?h:l,i[p++]=16&s?h:l,i[p++]=8&s?h:l,i[p++]=4&s?h:l,i[p++]=2&s?h:l,i[p++]=1&s?h:l}if(0===d)continue;const s=e<u?t[e++]:255;for(let t=0;t<d;t++)i[p++]=s&1<<7-t?h:l}return{srcPos:e,destPos:p}}const fh=16,_h=new DOMMatrix,mh=new Float32Array(2),vh=new Float32Array([1/0,1/0,-1/0,-1/0]);class bh{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,i){let s;return void 0!==this.cache[t]?(s=this.cache[t],this.canvasFactory.reset(s,e,i)):(s=this.canvasFactory.create(e,i),this.cache[t]=s),s}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 yh(t,e,i,s,n,a,r,o,l,h){const[c,d,u,p,g,f]=Xo(t);if(0===d&&0===u){const _=r*c+g,m=Math.round(_),v=o*p+f,b=Math.round(v),y=(r+l)*c+g,w=Math.abs(Math.round(y)-m)||1,x=(o+h)*p+f,A=Math.abs(Math.round(x)-b)||1;return t.setTransform(Math.sign(c),0,0,Math.sign(p),m,b),t.drawImage(e,i,s,n,a,0,0,w,A),t.setTransform(c,d,u,p,g,f),[w,A]}if(0===c&&0===p){const _=o*u+g,m=Math.round(_),v=r*d+f,b=Math.round(v),y=(o+h)*u+g,w=Math.abs(Math.round(y)-m)||1,x=(r+l)*d+f,A=Math.abs(Math.round(x)-b)||1;return t.setTransform(0,Math.sign(d),Math.sign(u),0,m,b),t.drawImage(e,i,s,n,a,0,0,A,w),t.setTransform(c,d,u,p,g,f),[A,w]}t.drawImage(e,i,s,n,a,r,o,l,h);return[Math.hypot(c,d)*l,Math.hypot(u,p)*h]}class wh{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=Rr;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=Ur;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(t,e){this.clipBox=new Float32Array([0,0,t,e]),this.minMax=vh.slice()}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t}getPathBoundingBox(t=eh,e=null){const i=this.minMax.slice();if(t===ih){e||po("Stroke bounding box must include transform."),Ro.singularValueDecompose2dScale(e,mh);const t=mh[0]*this.lineWidth/2,s=mh[1]*this.lineWidth/2;i[0]-=t,i[1]-=s,i[2]+=t,i[3]+=s}return i}updateClipFromPath(){const t=Ro.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(vh,0)}getClippedPathBoundingBox(t=eh,e=null){return Ro.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function xh(t,e){if(e instanceof ImageData)return void t.putImageData(e,0,0);const i=e.height,s=e.width,n=i%fh,a=(i-n)/fh,r=0===n?a:a+1,o=t.createImageData(s,fh);let l,h=0;const c=e.data,d=o.data;let u,p,g,f;if(e.kind===Kr.GRAYSCALE_1BPP){const e=c.byteLength,i=new Uint32Array(d.buffer,0,d.byteLength>>2),f=i.length,_=s+7>>3,m=4294967295,v=Eo.isLittleEndian?4278190080:255;for(u=0;u<r;u++){for(g=u<a?fh:n,l=0,p=0;p<g;p++){const t=e-h;let n=0;const a=t>_?s:8*t-7,r=-8&a;let o=0,d=0;for(;n<r;n+=8)d=c[h++],i[l++]=128&d?m:v,i[l++]=64&d?m:v,i[l++]=32&d?m:v,i[l++]=16&d?m:v,i[l++]=8&d?m:v,i[l++]=4&d?m:v,i[l++]=2&d?m:v,i[l++]=1&d?m:v;for(;n<a;n++)0===o&&(d=c[h++],o=128),i[l++]=d&o?m:v,o>>=1}for(;l<f;)i[l++]=0;t.putImageData(o,0,u*fh)}}else if(e.kind===Kr.RGBA_32BPP){for(p=0,f=s*fh*4,u=0;u<a;u++)d.set(c.subarray(h,h+f)),h+=f,t.putImageData(o,0,p),p+=fh;u<r&&(f=s*n*4,d.set(c.subarray(h,h+f)),t.putImageData(o,0,p))}else{if(e.kind!==Kr.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=fh,f=s*g,u=0;u<r;u++){for(u>=a&&(g=n,f=s*g),l=0,p=f;p--;)d[l++]=c[h++],d[l++]=c[h++],d[l++]=c[h++],d[l++]=255;t.putImageData(o,0,u*fh)}}}function Ah(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,s=e.width,n=i%fh,a=(i-n)/fh,r=0===n?a:a+1,o=t.createImageData(s,fh);let l=0;const h=e.data,c=o.data;for(let e=0;e<r;e++){const i=e<a?fh:n;({srcPos:l}=gh({src:h,srcPos:l,dest:c,width:s,height:i,nonBlackColor:0})),t.putImageData(o,0,e*fh)}}function kh(t,e){const i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of i)void 0!==t[s]&&(e[s]=t[s]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function Th(t){t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0);const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function Sh(t,e){if(e)return!0;Ro.singularValueDecompose2dScale(t,mh);const i=Math.fround(Jo.pixelRatio*Fo.PDF_TO_CSS_UNITS);return mh[0]<=i&&mh[1]<=i}const Eh=["butt","round","square"],Ch=["miter","round","bevel"],Rh={},Mh={};class Ph{constructor(t,e,i,s,n,{optionalContentConfig:a,markedContentStack:r=null},o,l){this.ctx=t,this.current=new wh(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=i,this.canvasFactory=s,this.filterFactory=n,this.groupStack=[],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 bh(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return"string"==typeof t?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:s=null}){const n=this.ctx.canvas.width,a=this.ctx.canvas.height,r=this.ctx.fillStyle;if(this.ctx.fillStyle=s||"#ffffff",this.ctx.fillRect(0,0,n,a),this.ctx.fillStyle=r,i){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(...Xo(this.compositeCtx))}this.ctx.save(),Th(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=Xo(this.ctx)}executeOperatorList(t,e,i,s){const n=t.argsArray,a=t.fnArray;let r=e||0;const o=n.length;if(o===r)return r;const l=o-r>10&&"function"==typeof i,h=l?Date.now()+15:0;let c=0;const d=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint)return s.breakIt(r,i),r;if(p=a[r],p!==io.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,i),r}if(r++,r===o)return r;if(l&&++c>10){if(Date.now()>h)return i(),r;c=0}}}#Li(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#Li(),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.#Di()}#Di(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,s=t.height??t.displayHeight;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,c="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;r>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),r/=l/e),o>2&&h>1&&(i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/i),n=this.cachedCanvases.getCanvas(c,e,i),a=n.context,a.clearRect(0,0,e,i),a.drawImage(t,0,0,l,h,0,0,e,i),t=n.canvas,l=e,h=i,c="prescale1"===c?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=Xo(e);let o,l,h,c;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]),o=this._cachedBitmapsMap.get(e),o||(o=new Map,this._cachedBitmapsMap.set(e,o));const i=o.get(l);if(i&&!a){return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])}}h=i}h||(c=this.cachedCanvases.getCanvas("maskCanvas",i,s),Ah(c.context,t));let d=Ro.transform(r,[1/i,0,0,-1/s,0,0]);d=Ro.transform(d,[1,0,0,1,0,-s]);const u=vh.slice();Ro.axialAlignedBoundingBox([0,0,i,s],d,u);const[p,g,f,_]=u,m=Math.round(f-p)||1,v=Math.round(_-g)||1,b=this.cachedCanvases.getCanvas("fillCanvas",m,v),y=b.context,w=p,x=g;y.translate(-w,-x),y.transform(...d),h||(h=this._scaleImage(c.canvas,Yo(y)),h=h.img,o&&a&&o.set(l,h)),y.imageSmoothingEnabled=Sh(Xo(y),t.interpolate),yh(y,h,0,0,h.width,h.height,0,0,i,s),y.globalCompositeOperation="source-in";const A=Ro.transform(Yo(y),[1,0,0,1,-w,-x]);return y.fillStyle=a?n.getPattern(e,this,A,eh):n,y.fillRect(0,0,i,s),o&&!a&&(this.cachedCanvases.delete("fillCanvas"),o.set(l,b.canvas)),{canvas:b.canvas,offsetX:Math.round(w),offsetY:Math.round(x)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=Eh[t]}setLineJoin(t){this.ctx.lineJoin=Ch[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(t),i.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.ctx.globalAlpha=this.current.fillAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}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,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;const n=this.ctx=s.context;n.setTransform(this.suspendedCtx.getTransform()),kh(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,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,s,n,a,r){e.transform(t,i,s,n,a,r),this.__originalTransform(t,i,s,n,a,r)},t.setTransform=function(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r),this.__originalSetTransform(t,i,s,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,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r),this.__originalBezierCurveTo(t,i,s,n,a,r)},t.rect=function(t,i,s,n){e.rect(t,i,s,n),this.__originalRect(t,i,s,n)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(n,this.suspendedCtx),this.setGState([["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),kh(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,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;0!==r&&0!==o&&(this.genericComposeSMask(e.context,i,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(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,c){let d=t.canvas,u=o-h,p=l-c;if(a)if(u<0||p<0||u+i>d.width||p+s>d.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),e=t.context;e.drawImage(d,-u,-p),e.globalCompositeOperation="destination-atop",e.fillStyle=a,e.fillRect(0,0,i,s),e.globalCompositeOperation="source-over",d=t.canvas,u=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,s),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=a,t.fillRect(u,p,i,s),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,l,i,s),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(d,u,p,i,s,o,l,i,s),e.restore()}save(){this.inSMaskMode&&kh(this.ctx,this.suspendedCtx),this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){0!==this.stateStack.length?(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&kh(this.suspendedCtx,this.ctx),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){let[s]=e;if(!i)return s||=e[0]=new Path2D,void this[t](s);if(!(s instanceof Path2D)){const t=e[0]=new Path2D;for(let e=0,i=s.length;e<i;)switch(s[e++]){case so:t.moveTo(s[e++],s[e++]);break;case no:t.lineTo(s[e++],s[e++]);break;case ao:t.bezierCurveTo(s[e++],s[e++],s[e++],s[e++],s[e++],s[e++]);break;case ro:t.closePath();break;default:uo(`Unrecognized drawing path operator: ${s[e-1]}`)}s=t}Ro.axialAlignedBoundingBox(i,Xo(this.ctx),this.current.minMax),this[t](s)}closePath(){this.ctx.closePath()}stroke(t,e=!0){const i=this.ctx,s=this.current.strokeColor;if(i.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof s&&s?.getPattern){const e=s.isModifyingCurrentTransform()?i.getTransform():null;if(i.save(),i.strokeStyle=s.getPattern(i,this,Yo(i),ih),e){const s=new Path2D;s.addPath(t,i.getTransform().invertSelf().multiplySelf(e)),t=s}this.rescaleAndStroke(t,!1),i.restore()}else this.rescaleAndStroke(t,!0);e&&this.consumePath(t,this.current.getClippedPathBoundingBox(ih,Xo(this.ctx))),i.globalAlpha=this.current.fillAlpha}closeStroke(t){this.stroke(t)}fill(t,e=!0){const i=this.ctx,s=this.current.fillColor;let n=!1;if(this.current.patternFill){const e=s.isModifyingCurrentTransform()?i.getTransform():null;if(i.save(),i.fillStyle=s.getPattern(i,this,Yo(i),eh),e){const s=new Path2D;s.addPath(t,i.getTransform().invertSelf().multiplySelf(e)),t=s}n=!0}const a=this.current.getClippedPathBoundingBox();this.contentVisible&&null!==a&&(this.pendingEOFill?(i.fill(t,"evenodd"),this.pendingEOFill=!1):i.fill(t)),n&&i.restore(),e&&this.consumePath(t,a)}eoFill(t){this.pendingEOFill=!0,this.fill(t)}fillStroke(t){this.fill(t,!1),this.stroke(t,!1),this.consumePath(t)}eoFillStroke(t){this.pendingEOFill=!0,this.fillStroke(t)}closeFillStroke(t){this.fillStroke(t)}closeEOFillStroke(t){this.pendingEOFill=!0,this.fillStroke(t)}endPath(t){this.consumePath(t)}rawFillPath(t){this.ctx.fill(t)}clip(){this.pendingClip=Rh}eoClip(){this.pendingClip=Mh}beginText(){this.current.textMatrix=null,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)return;const i=new Path2D,s=e.getTransform().invertSelf();for(const{transform:e,x:n,y:a,fontSize:r,path:o}of t)i.addPath(o,new DOMMatrix(e).preMultiplySelf(s).translate(n,a).scale(r,-r));e.clip(i),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const i=this.commonObjs.get(t),s=this.current;if(!i)throw new Error(`Can't find font for ${t}`);if(s.fontMatrix=i.fontMatrix||Rr,0!==s.fontMatrix[0]&&0!==s.fontMatrix[3]||uo("Invalid font matrix for font "+t),e<0?(e=-e,s.fontDirection=-1):s.fontDirection=1,this.current.font=i,this.current.fontSize=e,i.isType3Font)return;const n=i.loadedName||"sans-serif",a=i.systemFontInfo?.css||`"${n}", ${i.fallbackName}`;let r="normal";i.black?r="900":i.bold&&(r="bold");const o=i.italic?"italic":"normal";let l=e;e<16?l=16:e>100&&(l=100),this.current.fontSizeScale=e/l,this.ctx.font=`${o} ${r} ${l}px ${a}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t){const{current:e}=this;e.textMatrix=t,e.textMatrixScale=Math.hypot(t[0],t[1]),e.x=e.lineX=0,e.y=e.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#Ii(t,e,i){const s=new Path2D;return s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e)),s}paintChar(t,e,i,s,n){const a=this.ctx,r=this.current,o=r.font,l=r.textRenderingMode,h=r.fontSize/r.fontSizeScale,c=l&Gr,d=!!(l&qr),u=r.patternFill&&!o.missingFile,p=r.patternStroke&&!o.missingFile;let g;if((o.disableFontFace||d||u||p)&&(g=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||u||p){let t;if(a.save(),a.translate(e,i),a.scale(h,-h),c!==Ur&&c!==$r||(s?(t=a.getTransform(),a.setTransform(...s),a.fill(this.#Ii(g,t,s))):a.fill(g)),c===Hr||c===$r)if(n){t||=a.getTransform(),a.setTransform(...n);const{a:e,b:i,c:s,d:r}=t,o=Ro.inverseTransform(n),l=Ro.transform([e,i,s,r,0,0],o);Ro.singularValueDecompose2dScale(l,mh),a.lineWidth*=Math.max(mh[0],mh[1])/h,a.stroke(this.#Ii(g,t,n))}else a.lineWidth/=h,a.stroke(g);a.restore()}else c!==Ur&&c!==$r||a.fillText(t,e,i),c!==Hr&&c!==$r||a.strokeText(t,e,i);if(d){(this.pendingTextPaths||=[]).push({transform:Xo(a),x:e,y:i,fontSize:h,path:g})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){i=!0;break}return mo(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,c=t.length,d=i.vertical,u=d?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],f=e.textRenderingMode===Ur&&!i.disableFontFace&&!e.patternFill;let _,m;if(n.save(),e.textMatrix&&n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(h,-1):n.scale(h,1),e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,Yo(n),eh);_=Xo(n),n.restore(),n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,Yo(n),ih);m=Xo(n),n.restore(),n.strokeStyle=t}let v=e.lineWidth;const b=e.textMatrixScale;if(0===b||0===v){const t=e.textRenderingMode&Gr;t!==Hr&&t!==$r||(v=this.getSinglePixelWidth())}else v/=b;if(1!==a&&(n.scale(a,a),v/=a),n.lineWidth=v,i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t)i.push(e.unicode),s+=e.width;return n.fillText(i.join(""),0,0),e.x+=s*g*h,n.restore(),void this.compose()}let y,w=0;for(y=0;y<c;++y){const e=t[y];if("number"==typeof e){w+=u*e*s/1e3;continue}let h=!1;const c=(e.isSpace?o:0)+r,v=e.fontChar,b=e.accent;let x,A,k=e.width;if(d){const t=e.vmetric||p,i=-(e.vmetric?t[1]:.5*k)*g,s=t[2]*g;k=t?-t[0]:k,x=i/a,A=(w+s)/a}else x=w/a,A=0;if(i.remeasure&&k>0){const t=1e3*n.measureText(v).width/s*a;if(k<t&&this.isFontSubpixelAAEnabled){const e=k/t;h=!0,n.save(),n.scale(e,1),x/=e}else k!==t&&(x+=(k-t)/2e3*s/a)}if(this.contentVisible&&(e.isInFont||i.missingFile))if(f&&!b)n.fillText(v,x,A);else if(this.paintChar(v,x,A,_,m),b){const t=x+s*b.offset.x/a,e=A-s*b.offset.y/a;this.paintChar(b.fontChar,t,e,_,m)}w+=d?k*g-c*l:k*g+c*l,h&&n.restore()}d?e.y-=w:e.x+=w*h,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,i=this.current,s=i.font,n=i.fontSize,a=i.fontDirection,r=s.vertical?1:-1,o=i.charSpacing,l=i.wordSpacing,h=i.textHScale*a,c=i.fontMatrix||Rr,d=t.length;let u,p,g,f;if(!(i.textRenderingMode===Wr)&&0!==n){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),i.textMatrix&&e.transform(...i.textMatrix),e.translate(i.x,i.y+i.textRise),e.scale(h,a),u=0;u<d;++u){if(p=t[u],"number"==typeof p){f=r*p*n/1e3,this.ctx.translate(f,0),i.x+=f*h;continue}const a=(p.isSpace?l:0)+o,d=s.charProcOperatorList[p.operatorListId];d?this.contentVisible&&(this.save(),e.scale(n,n),e.transform(...c),this.executeOperatorList(d),this.restore()):uo(`Type3 character "${p.operatorListId}" is not available.`);const _=[p.width,0];Ro.applyTransform(_,c),g=_[0]*n+a,e.translate(g,0),i.x+=g*h}e.restore()}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,i,s,n,a){const r=new Path2D;r.rect(i,s,n-i,a-s),this.ctx.clip(r),this.endPath()}getColorN_Pattern(t){let e;if("TilingPattern"===t[0]){const i=this.baseTransform||Xo(this.ctx),s={createCanvasGraphics:t=>new Ph(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new ph(t,this.ctx,s,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t){this.ctx.strokeStyle=this.current.strokeColor=t,this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t){this.ctx.fillStyle=this.current.fillColor=t,this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=function(t){switch(t[0]){case"RadialAxial":return new rh(t);case"Mesh":return new hh(t);case"Dummy":return new ch}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t)),this.cachedPatterns.set(t,i)),e&&(i.matrix=e),i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,Yo(e),sh);const s=Yo(e);if(s){const{width:t,height:i}=e.canvas,n=vh.slice();Ro.axialAlignedBoundingBox([0,0,t,i],s,n);const[a,r,o,l]=n;this.ctx.fillRect(a,r,o-a,l-r)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){po("Should not call beginInlineImage")}beginImageData(){po("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=Xo(this.ctx),e)){Ro.axialAlignedBoundingBox(e,this.baseTransform,this.current.minMax);const[t,i,s,n]=e,a=new Path2D;a.rect(t,i,s-t,n-i),this.ctx.clip(a),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||co("TODO: Support non-isolated groups."),t.knockout&&uo("Knockout groups not supported.");const i=Xo(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let s=vh.slice();Ro.axialAlignedBoundingBox(t.bbox,Xo(e),s);const n=[0,0,e.canvas.width,e.canvas.height];s=Ro.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const c=this.cachedCanvases.getCanvas(h,o,l),d=c.context;d.translate(-a,-r),d.transform(...i);let u=new Path2D;const[p,g,f,_]=t.bbox;if(u.rect(p,g,f-p,_-g),t.matrix){const e=new Path2D;e.addPath(u,new DOMMatrix(t.matrix)),u=e}d.clip(u),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()),kh(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,i=this.groupStack.pop();if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const t=Xo(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...t);const i=vh.slice();Ro.axialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t,i),this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,e,i,s,n){if(this.#Li(),Th(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0],i[5]-=e[1],(e=e.slice())[0]=e[1]=0,e[2]=s,e[3]=a,Ro.singularValueDecompose2dScale(Xo(this.ctx),mh);const{viewportScale:n}=this,r=Math.ceil(s*this.outputScaleX*n),o=Math.ceil(a*this.outputScaleY*n);this.annotationCanvas=this.canvasFactory.create(r,o);const{canvas:l,context:h}=this.annotationCanvas;this.annotationCanvasMap.set(t,l),this.annotationCanvas.savedCtx=this.ctx,this.ctx=h,this.ctx.save(),this.ctx.setTransform(mh[0],0,0,-mh[1],0,a*mh[1]),Th(this.ctx)}else{Th(this.ctx),this.endPath();const t=new Path2D;t.rect(e[0],e[1],s,a),this.ctx.clip(t)}}this.current=new wh(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...i),this.transform(...s)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#Di(),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 i=this.ctx,s=this._createMaskCanvas(t),n=s.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(n,s.offsetX,s.offsetY),i.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=Xo(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;t<h;t+=2){const h=Ro.transform(o,[e,i,s,n,a[t],a[t+1]]);r.drawImage(l.canvas,h[4],h[5])}r.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,i=this.current.fillColor,s=this.current.patternFill;for(const n of t){const{data:t,width:a,height:r,transform:o}=n,l=this.cachedCanvases.getCanvas("maskCanvas",a,r),h=l.context;h.save();Ah(h,this.getObject(t,n)),h.globalCompositeOperation="source-in",h.fillStyle=s?i.getPattern(h,this,Yo(e),eh):i,h.fillRect(0,0,a,r),h.restore(),e.save(),e.transform(...o),e.scale(1,-1),yh(e,l.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):uo("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,i,s){if(!this.contentVisible)return;const n=this.getObject(t);if(!n)return void uo("Dependent image isn't ready yet");const a=n.width,r=n.height,o=[];for(let t=0,n=s.length;t<n;t+=2)o.push({transform:[e,0,0,i,s[t],s[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:i,height:s}=t,n=this.cachedCanvases.getCanvas("inlineImage",i,s),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,i=t.height,s=this.ctx;this.save();const{filter:n}=s;let a;if("none"!==n&&""!==n&&(s.filter="none"),s.scale(1/e,-1/i),t.bitmap)a=this.applyTransferMapsToBitmap(t);else if("function"==typeof HTMLElement&&t instanceof HTMLElement||!t.data)a=t;else{const s=this.cachedCanvases.getCanvas("inlineImage",e,i).context;xh(s,t),a=this.applyTransferMapsToCanvas(s)}const r=this._scaleImage(a,Yo(s));s.imageSmoothingEnabled=Sh(Xo(s),t.interpolate),yh(s,r.img,0,0,r.paintWidth,r.paintHeight,0,-i,e,i),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.ctx;let s;if(t.bitmap)s=t.bitmap;else{const e=t.width,i=t.height,n=this.cachedCanvases.getCanvas("inlineImage",e,i).context;xh(n,t),s=this.applyTransferMapsToCanvas(n)}for(const t of e)i.save(),i.transform(...t.transform),i.scale(1,-1),yh(i,s,t.x,t.y,t.w,t.h,0,-1,1,1),i.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,e){const i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(e);const s=this.ctx;this.pendingClip&&(i||(this.pendingClip===Mh?s.clip(t,"evenodd"):s.clip(t)),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Xo(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]),i=Math.hypot(t[0],t[2]),s=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,s)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:i,c:s,d:n}=this.ctx.getTransform();let a,r;if(0===i&&0===s){const i=Math.abs(e),s=Math.abs(n);if(i===s)if(0===t)a=r=1/i;else{const e=i*t;a=r=e<1?1/e:1}else if(0===t)a=1/i,r=1/s;else{const e=i*t,n=s*t;a=e<1?1/e:1,r=n<1?1/n:1}}else{const o=Math.abs(e*n-i*s),l=Math.hypot(e,i),h=Math.hypot(s,n);if(0===t)a=h/o,r=l/o;else{const e=t*o;a=h>e?h/e:1,r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:s}}=this,[n,a]=this.getScaleForStroking();if(n===a)return i.lineWidth=(s||1)*n,void i.stroke(t);const r=i.getLineDash();e&&i.save(),i.scale(n,a),_h.a=1/n,_h.d=1/a;const o=new Path2D;if(o.addPath(t,_h),r.length>0){const t=Math.max(n,a);i.setLineDash(r.map((e=>e/t))),i.lineDashOffset/=t}i.lineWidth=s||1,i.stroke(o),e&&i.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in io)void 0!==Ph.prototype[t]&&(Ph.prototype[io[t]]=Ph.prototype[t]);class Lh{static#Oi=null;static#Ni="";static get workerPort(){return this.#Oi}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Oi=t}static get workerSrc(){return this.#Ni}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Ni=t}}class Dh{#Fi;#Bi;constructor({parsedData:t,rawData:e}){this.#Fi=t,this.#Bi=e}getRaw(){return this.#Bi}get(t){return this.#Fi.get(t)??null}[Symbol.iterator](){return this.#Fi.entries()}}const Ih=Symbol("INTERNAL");class Oh{#ji=!1;#zi=!1;#Vi=!1;#Ui=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#ji=!!(t&Lr),this.#zi=!!(t&Dr),this.name=e,this.intent=i,this.usage=s,this.rbGroups=n}get visible(){if(this.#Vi)return this.#Ui;if(!this.#Ui)return!1;const{print:t,view:e}=this.usage;return this.#ji?"OFF"!==e?.viewState:!this.#zi||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Ih&&po("Internal method `_setVisible` called."),this.#Vi=i,this.#Ui=e}}class Nh{#Hi=null;#$i=new Map;#Wi=null;#Gi=null;constructor(t,e=Lr){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Gi=t.order;for(const i of t.groups)this.#$i.set(i.id,new Oh(e,i));if("OFF"===t.baseState)for(const t of this.#$i.values())t._setVisible(Ih,!1);for(const e of t.on)this.#$i.get(e)._setVisible(Ih,!0);for(const e of t.off)this.#$i.get(e)._setVisible(Ih,!1);this.#Wi=this.getHash()}}#qi(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s<e;s++){const e=t[s];let n;if(Array.isArray(e))n=this.#qi(e);else{if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;n=this.#$i.get(e).visible}switch(i){case"And":if(!n)return!1;break;case"Or":if(n)return!0;break;case"Not":return!n;default:return!0}}return"And"===i}isVisible(t){if(0===this.#$i.size)return!0;if(!t)return co("Optional content group not defined."),!0;if("OCG"===t.type)return this.#$i.has(t.id)?this.#$i.get(t.id).visible:(uo(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#qi(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;if(this.#$i.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;if(!this.#$i.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;if(!this.#$i.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#$i.has(e))return uo(`Optional content group not found: ${e}`),!0;if(this.#$i.get(e).visible)return!1}return!0}return uo(`Unknown optional content policy ${t.policy}.`),!0}return uo(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,i=!0){const s=this.#$i.get(t);if(s){if(i&&e&&s.rbGroups.length)for(const e of s.rbGroups)for(const i of e)i!==t&&this.#$i.get(i)?._setVisible(Ih,!1,!0);s._setVisible(Ih,!!e,!0),this.#Hi=null}else uo(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(const s of t){switch(s){case"ON":case"OFF":case"Toggle":i=s;continue}const t=this.#$i.get(s);if(t)switch(i){case"ON":this.setVisibility(s,!0,e);break;case"OFF":this.setVisibility(s,!1,e);break;case"Toggle":this.setVisibility(s,!t.visible,e)}}this.#Hi=null}get hasInitialVisibility(){return null===this.#Wi||this.getHash()===this.#Wi}getOrder(){return this.#$i.size?this.#Gi?this.#Gi.slice():[...this.#$i.keys()]:null}getGroup(t){return this.#$i.get(t)||null}getHash(){if(null!==this.#Hi)return this.#Hi;const t=new _l;for(const[e,i]of this.#$i)t.update(`${e}:${i.visible}`);return this.#Hi=t.hexdigest()}[Symbol.iterator](){return this.#$i.entries()}}class Fh{constructor(t,{disableRange:e=!1,disableStream:i=!1}){go(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,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=!i,this._isRangeSupported=!e,this._contentLength=s,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 i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{go(this._rangeReaders.some((function(e){return e._begin===t&&(e._enqueue(i),!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(){go(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Bh(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new jh(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class Bh{constructor(t,e,i=!1,s=null){this._stream=t,this._done=i||!1,this._filename=Uo(s)?s: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){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}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 jh{constructor(t,e,i){this._stream=t,this._begin=e,this._end=i,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 zh(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function Vh(t){return URL.parse(t)?.origin??null}function Uh({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return n;if(n.suggestedLength=a,a<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;return"identity"!==(t.get("Content-Encoding")||"identity")||(n.allowRangeRequests=!0),n}function Hh(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=s("filename\\*","i").exec(t);if(i){i=i[1];let t=r(i);return t=unescape(t),t=o(t),t=l(t),a(t)}if(i=function(t){const e=[];let i;const n=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,s,n]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[s,n]}const a=[];for(let t=0;t<e.length&&t in e;++t){let[i,s]=e[t];s=r(s),i&&(s=unescape(s),0===t&&(s=o(s))),a.push(s)}return a.join("")}(t),i)return a(l(i));if(i=s("filename","i").exec(t),i){i=i[1];let t=r(i);return t=l(t),a(t)}function s(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function n(t,i){if(t){if(!/^[\x00-\xFF]+$/.test(i))return i;try{const s=new TextDecoder(t,{fatal:!0}),n=So(i);i=s.decode(n),e=!1}catch{}}return i}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 i=e[t].indexOf('"');-1!==i&&(e[t]=e[t].slice(0,i),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 l(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(t,e,i,s){if("q"===i||"Q"===i)return n(e,s=(s=s.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(t,e){return String.fromCharCode(parseInt(e,16))})));try{s=atob(s)}catch{}return n(e,s)}))}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(Uo(t))return t}return null}function $h(t,e){return new xo(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t,404===t||0===t&&e.startsWith("file:"))}function Wh(t){return 200===t||206===t}function Gh(t,e,i){return{method:"GET",headers:t,signal:i.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function qh(t){return t instanceof Uint8Array?t.buffer:t instanceof ArrayBuffer?t:(uo(`getArrayBuffer - unexpected data format: ${t}`),new Uint8Array(t).buffer)}class Kh{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=zh(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return go(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new Xh(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new Yh(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Xh{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const i=new Headers(t.headers),s=e.url;fetch(s,Gh(i,this._withCredentials,this._abortController)).then((e=>{if(t._responseOrigin=Vh(e.url),!Wh(e.status))throw $h(e.status,s);this._reader=e.body.getReader(),this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=Uh({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n,this._contentLength=a||this._contentLength,this._filename=Hh(i),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ko("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:qh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Yh{constructor(t,e,i){this._stream=t,this._reader=null,this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!s.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,Gh(n,this._withCredentials,this._abortController)).then((e=>{const i=Vh(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!Wh(e.status))throw $h(e.status,a);this._readCapability.resolve(),this._reader=e.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:qh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Qh{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=zh(this.isHttp,e),this.withCredentials=i||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.expectedStatus=206):s.expectedStatus=200,e.responseType="arraybuffer",go(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,i),e.onprogress=this.onProgress.bind(this,i),s.onHeadersReceived=t.onHeadersReceived,s.onDone=t.onDone,s.onError=t.onError,s.onProgress=t.onProgress,e.send(null),i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==s.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===s.status&&this.isHttp)return void i.onError(s.status);const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus)return void i.onError(s.status);const a=function(t){const e=t.response;return"string"!=typeof e?e:So(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);e?i.onDone({begin:parseInt(e[1],10),chunk:a}):(uo('Missing or invalid "Content-Range" header.'),i.onError(0))}else a?i.onDone({begin:0,chunk:a}):i.onError(s.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 Jh{constructor(t){this._source=t,this._manager=new Qh(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return go(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Zh(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const i=new tc(this._manager,t,e);return i.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Zh{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=Vh(e.responseURL);const i=e.getAllResponseHeaders(),s=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]})):[]),{allowRangeRequests:n,suggestedLength:a}=Uh({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=a||this._contentLength,this._filename=Hh(s),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);if(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=$h(t,this._url),this._headersCapability.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._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);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 tc{constructor(t,e,i){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){const t=Vh(this._manager.getRequestXhr(this._requestId)?.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else 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??=$h(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 ec=/^[a-z][a-z0-9\-+.]+:/i;class ic{constructor(t){this.source=t,this.url=function(t){if(ec.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url),go("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return go(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new sc(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new nc(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class sc{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();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then((t=>{this._contentLength=t.size,this._setReadableStream(i.createReadStream(this._url)),this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=$h(0,this._url.href)),this._storedError=t,this._headersCapability.reject(t)}))}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();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{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 ko("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class nc{constructor(t,e,i){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const s=t.source;this._isStreamingSupported=!s.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:i-1}))}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();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded});return{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)}}const ac=Symbol("INITIAL_DATA");class rc{#Ki=Object.create(null);#Xi(t){return this.#Ki[t]||={...Promise.withResolvers(),data:ac}}get(t,e=null){if(e){const i=this.#Xi(t);return i.promise.then((()=>e(i.data))),null}const i=this.#Ki[t];if(!i||i.data===ac)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Ki[t];return!!e&&e.data!==ac}delete(t){const e=this.#Ki[t];return!(!e||e.data===ac)&&(delete this.#Ki[t],!0)}resolve(t,e=null){const i=this.#Xi(t);i.data=e,i.resolve()}clear(){for(const t in this.#Ki){const{data:e}=this.#Ki[t];e?.bitmap?.close()}this.#Ki=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Ki){const{data:e}=this.#Ki[t];e!==ac&&(yield[t,e])}}}class oc{#Yi=Promise.withResolvers();#_t=null;#Qi=!1;#Ji=!!globalThis.FontInspector?.enabled;#Zi=null;#ts=null;#es=0;#is=0;#ss=null;#ns=null;#as=0;#rs=0;#os=Object.create(null);#ls=[];#hs=null;#cs=[];#ds=new WeakMap;#us=null;static#ps=new Map;static#gs=new Map;static#fs=new WeakMap;static#_s=null;static#ms=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#hs=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#hs=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#_t=this.#ns=e,this.#rs=i.scale*Jo.pixelRatio,this.#as=i.rotation,this.#ts={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#us=[1,0,0,-1,-a,r+n],this.#is=s,this.#es=n,oc.#vs(),Qo(e,i),this.#Yi.promise.finally((()=>{oc.#ms.delete(this),this.#ts=null,this.#os=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Eo.platform;return mo(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const t=()=>{this.#ss.read().then((({value:e,done:i})=>{i?this.#Yi.resolve():(this.#Zi??=e.lang,Object.assign(this.#os,e.styles),this.#bs(e.items),t())}),this.#Yi.reject)};return this.#ss=this.#hs.getReader(),oc.#ms.add(this),t(),this.#Yi.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*Jo.pixelRatio,s=t.rotation;if(s!==this.#as&&(e?.(),this.#as=s,Qo(this.#ns,{rotation:s})),i!==this.#rs){e?.(),this.#rs=i;const t={div:null,properties:null,ctx:oc.#ys(this.#Zi)};for(const e of this.#cs)t.properties=this.#ds.get(e),t.div=e,this.#ws(t)}}cancel(){const t=new ko("TextLayer task cancelled.");this.#ss?.cancel(t).catch((()=>{})),this.#ss=null,this.#Yi.reject(t)}get textDivs(){return this.#cs}get textContentItemsStr(){return this.#ls}#bs(t){if(this.#Qi)return;this.#ts.ctx??=oc.#ys(this.#Zi);const e=this.#cs,i=this.#ls;for(const s of t){if(e.length>1e5)return uo("Ignoring additional textDivs for performance reasons."),void(this.#Qi=!0);if(void 0!==s.str)i.push(s.str),this.#xs(s);else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#_t;this.#_t=document.createElement("span"),this.#_t.classList.add("markedContent"),null!==s.id&&this.#_t.setAttribute("id",`${s.id}`),t.append(this.#_t)}else"endMarkedContent"===s.type&&(this.#_t=this.#_t.parentNode)}}#xs(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#cs.push(e);const s=Ro.transform(this.#us,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#os[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Ji&&a.fontSubstitution||a.fontFamily;r=oc.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*oc.#As(r,a,this.#Zi);let h,c;0===n?(h=s[4],c=s[5]-l):(h=s[4]+l*Math.sin(n),c=s[5]-l*Math.cos(n));const d="calc(var(--total-scale-factor) *",u=e.style;this.#_t===this.#ns?(u.left=`${(100*h/this.#is).toFixed(2)}%`,u.top=`${(100*c/this.#es).toFixed(2)}%`):(u.left=`${d}${h.toFixed(2)}px)`,u.top=`${d}${c.toFixed(2)}px)`),u.fontSize=`${d}${(oc.#_s*o).toFixed(2)}px)`,u.fontFamily=r,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#Ji&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==n&&(i.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]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}if(p&&(i.canvasWidth=a.vertical?t.height:t.width),this.#ds.set(e,i),this.#ts.div=e,this.#ts.properties=i,this.#ws(this.#ts),i.hasText&&this.#_t.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#_t.append(t)}}#ws(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";if(oc.#_s>1&&(a=`scale(${1/oc.#_s})`),0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;oc.#ks(s,o*this.#rs,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#rs/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`),a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#ms.size>0)){this.#ps.clear();for(const{canvas:t}of this.#gs.values())t.remove();this.#gs.clear()}}static#ys(t=null){let e=this.#gs.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#gs.set(t,e),this.#fs.set(e,{size:0,family:""})}return e}static#ks(t,e,i){const s=this.#fs.get(t);e===s.size&&i===s.family||(t.font=`${e}px ${i}`,s.size=e,s.family=i)}static#vs(){if(null!==this.#_s)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#_s=t.getBoundingClientRect().height,t.remove()}static#As(t,e,i){const s=this.#ps.get(t);if(s)return s;const n=this.#ys(i);n.canvas.width=n.canvas.height=30,this.#ks(n,30,t);const a=n.measureText(""),r=a.fontBoundingBoxAscent,o=Math.abs(a.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let l=.8;return r?l=r/(r+o):(Eo.platform.isFirefox&&uo("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)),this.#ps.set(t,l),l}}class lc{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let s=null;const n=i.name;if("#text"===n)s=i.value;else{if(!lc.shouldBuildText(n))return;i?.attributes?.textContent?s=i.attributes.textContent:i.value&&(s=i.value)}if(null!==s&&e.push({str:s}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}function hc(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new cc,{docId:i}=e,s=t.url?function(t){if(t instanceof URL)return t.href;if("string"==typeof t){if(Cr)return t;const e=URL.parse(t,window.location);if(e)return e.href}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(Cr&&"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 So(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,l=t.range instanceof dc?t.range:null,h=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let c=t.worker instanceof gc?t.worker:null;const d=t.verbosity,u="string"!=typeof t.docBaseUrl||Vo(t.docBaseUrl)?null:t.docBaseUrl,p=xl(t.cMapUrl),g=!1!==t.cMapPacked,f=t.CMapReaderFactory||(Cr?Jl:Ul),_=xl(t.iccUrl),m=xl(t.standardFontDataUrl),v=t.StandardFontDataFactory||(Cr?Zl:Gl),b=xl(t.wasmUrl),y=t.WasmFactory||(Cr?th:Kl),w=!0!==t.stopAtErrors,x=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,A=!1!==t.isEvalSupported,k="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!Cr,T="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!Cr&&(Eo.platform.isFirefox||!globalThis.chrome),S=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,E="boolean"==typeof t.disableFontFace?t.disableFontFace:Cr,C=!0===t.fontExtraProperties,R=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,P=!0===t.disableRange,L=!0===t.disableStream,D=!0===t.disableAutoFetch,I=!0===t.pdfBug,O=t.CanvasFactory||(Cr?Ql:zl),N=t.FilterFactory||(Cr?Yl:$l),F=!0===t.enableHWA,B=!1!==t.useWasm,j=l?l.length:t.length??NaN,z="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!Cr&&!E,V="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:!!(f===Ul&&v===Gl&&y===Kl&&p&&m&&b&&$o(p,document.baseURI)&&$o(m,document.baseURI)&&$o(b,document.baseURI));lo(d);const U={canvasFactory:new O({ownerDocument:M,enableHWA:F}),filterFactory:new N({docId:i,ownerDocument:M}),cMapReaderFactory:V?null:new f({baseUrl:p,isCompressed:g}),standardFontDataFactory:V?null:new v({baseUrl:m}),wasmFactory:V?null:new y({baseUrl:b})};c||(c=gc.create({verbosity:d,port:Lh.workerPort}),e._worker=c);const H={docId:i,apiVersion:"5.3.31",data:n,password:o,disableAutoFetch:D,rangeChunkSize:h,length:j,docBaseUrl:u,enableXfa:R,evaluatorOptions:{maxImageSize:x,disableFontFace:E,ignoreErrors:w,isEvalSupported:A,isOffscreenCanvasSupported:k,isImageDecoderSupported:T,canvasMaxAreaInBytes:S,fontExtraProperties:C,useSystemFonts:z,useWasm:B,useWorkerFetch:V,cMapUrl:p,iccUrl:_,standardFontDataUrl:m,wasmUrl:b}},$={ownerDocument:M,pdfBug:I,styleElement:null,loadingParams:{disableAutoFetch:D,enableXfa:R}};return c.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",H,n?[n.buffer]:null);let o;if(l)o=new Fh(l,{disableRange:P,disableStream:L});else if(!n){if(!s)throw new Error("getDocument - no `url` parameter provided.");const t=$o(s)?Kh:Cr?ic:Jh;o=new t({url:s,length:j,httpHeaders:a,withCredentials:r,rangeChunkSize:h,disableRange:P,disableStream:L})}return t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const s=new Bl(i,t,c.port),n=new fc(s,e,o,$,U);e._transport=n,s.send("Ready",null)}))})).catch(e._capability.reject),e}class cc{static#vi=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+cc.#vi++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class dc{#Yi=Promise.withResolvers();#Ts=[];#Ss=[];#Es=[];#Cs=[];constructor(t,e,i=!1,s=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=s}addRangeListener(t){this.#Cs.push(t)}addProgressListener(t){this.#Es.push(t)}addProgressiveReadListener(t){this.#Ss.push(t)}addProgressiveDoneListener(t){this.#Ts.push(t)}onDataRange(t,e){for(const i of this.#Cs)i(t,e)}onDataProgress(t,e){this.#Yi.promise.then((()=>{for(const i of this.#Es)i(t,e)}))}onDataProgressiveRead(t){this.#Yi.promise.then((()=>{for(const e of this.#Ss)e(t)}))}onDataProgressiveDone(){this.#Yi.promise.then((()=>{for(const t of this.#Ts)t()}))}transportReady(){this.#Yi.resolve()}requestDataRange(t,e){po("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class uc{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return mo(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 pc{#Rs=!1;constructor(t,e,i,s=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=s?new Ho:null,this._pdfBug=s,this.commonObjs=i.commonObjs,this.objs=new rc,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:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new jo({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return mo(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=jr.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:l=null,printAnnotationStorage:h=null,isEditing:c=!1}){this._stats?.time("Overall");const d=this._transport.getRenderingIntent(i,s,h,c),{renderingIntent:u,cacheKey:p}=d;this.#Rs=!1,r||=this._transport.getOptionalContentConfig(u);let g=this._intentStates.get(p);g||(g=Object.create(null),this._intentStates.set(p,g)),g.streamReaderCancelTimeout&&(clearTimeout(g.streamReaderCancelTimeout),g.streamReaderCancelTimeout=null);const f=!!(u&Dr);g.displayReadyCapability||(g.displayReadyCapability=Promise.withResolvers(),g.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(d));const _=t=>{g.renderTasks.delete(m),f&&(this.#Rs=!0),this.#Ms(),t?(m.capability.reject(t),this._abortOperatorList({intentState:g,reason:t instanceof Error?t:new Error(t)})):m.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},m=new mc({callback:_,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:!f,pdfBug:this._pdfBug,pageColors:l});(g.renderTasks||=new Set).add(m);const v=m.task;return Promise.all([g.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)_();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&u))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");m.initializeGraphics({transparency:t,optionalContentConfig:e}),m.operatorListChanged()}})).catch(_),v}getOperatorList({intent:t="display",annotationMode:e=jr.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);return r||(r=Object.create(null),this._intentStates.set(n.cacheKey,r)),r.opListReadCapability||(a=Object.create(null),a.operatorListChanged=function(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(a))},r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(a),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),r.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=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>lc.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function e(){s.read().then((function({value:i,done:s}){s?t(n):(n.lang??=i.lang,Object.assign(n.styles,i.styles),n.items.push(...i.items),e())}),i)}()}))}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 i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#Rs=!1,Promise.all(t)}cleanup(t=!1){this.#Rs=!0;const e=this.#Ms();return t&&e&&(this._stats&&=new Ho),e}#Ms(){if(!this.#Rs||this.destroyed)return!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.#Rs=!1,!0}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,s=t.length;i<s;i++)e.operatorList.fnArray.push(t.fnArray[i]),e.operatorList.argsArray.push(t.argsArray[i]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#Ms()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:s}){const{map:n,transfer:a}=i,r=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:s},a).getReader(),o=this._intentStates.get(e);o.streamReader=r;const l=()=>{r.read().then((({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())}),(t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#Ms()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof zo){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})}),i))}}if(t.streamReader.cancel(new ko(e.message)).catch((()=>{})),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class gc{#Yi=Promise.withResolvers();#Ps=null;#Oi=null;#Ls=null;static#Ds=0;static#Is=!1;static#Os=new WeakMap;static{Cr&&(this.#Is=!0,Lh.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const s=new URL(e,i);return i.origin===s.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))},this.fromPort=t=>{var e;if(e="`PDFWorker.fromPort` - please use `PDFWorker.create` instead.",console.log("Deprecated API usage: "+e),!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.create(t)}}constructor({name:t=null,port:e=null,verbosity:i=ho()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,e){if(gc.#Os.has(e))throw new Error("Cannot use more than one PDFWorker per port.");gc.#Os.set(e,this),this.#Ns(e)}else this.#Fs()}get promise(){return this.#Yi.promise}#Bs(){this.#Yi.resolve(),this.#Ps.send("configure",{verbosity:this.verbosity})}get port(){return this.#Oi}get messageHandler(){return this.#Ps}#Ns(t){this.#Oi=t,this.#Ps=new Bl("main","worker",t),this.#Ps.on("ready",(()=>{})),this.#Bs()}#Fs(){if(gc.#Is||gc.#js)return void this.#zs();let{workerSrc:t}=gc;try{gc._isSameOrigin(window.location,t)||(t=gc._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new Bl("main","worker",e),s=()=>{n.abort(),i.destroy(),e.terminate(),this.destroyed?this.#Yi.reject(new Error("Worker was destroyed")):this.#zs()},n=new AbortController;e.addEventListener("error",(()=>{this.#Ls||s()}),{signal:n.signal}),i.on("test",(t=>{n.abort(),!this.destroyed&&t?(this.#Ps=i,this.#Oi=e,this.#Ls=e,this.#Bs()):s()})),i.on("ready",(t=>{if(n.abort(),this.destroyed)s();else try{a()}catch{this.#zs()}}));const a=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void a()}catch{co("The worker has been disabled.")}this.#zs()}#zs(){gc.#Is||(uo("Setting up fake worker."),gc.#Is=!0),gc._setupFakeWorkerGlobal.then((t=>{if(this.destroyed)return void this.#Yi.reject(new Error("Worker was destroyed"));const e=new Tl;this.#Oi=e;const i="fake"+gc.#Ds++,s=new Bl(i+"_worker",i,e);t.setup(s,e),this.#Ps=new Bl(i,i+"_worker",e),this.#Bs()})).catch((t=>{this.#Yi.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0,this.#Ls?.terminate(),this.#Ls=null,gc.#Os.delete(this.#Oi),this.#Oi=null,this.#Ps?.destroy(),this.#Ps=null}static create(t){const e=this.#Os.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new gc(t)}static get workerSrc(){if(Lh.workerSrc)return Lh.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#js(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return mo(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#js)return this.#js;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class fc{#Vs=new Map;#Us=new Map;#Hs=new Map;#$s=new Map;#Ws=null;constructor(t,e,i,s,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new rc,this.fontLoader=new yl({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.wasmFactory=n.wasmFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=i,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#Gs(t,e=null){const i=this.#Vs.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);return this.#Vs.set(t,s),s}get annotationStorage(){return mo(this,"annotationStorage",new vl)}getRenderingIntent(t,e=jr.ENABLE,i=null,s=!1,n=!1){let a=Lr,r=ml;switch(t){case"any":a=Pr;break;case"display":break;case"print":a=Dr;break;default:uo(`getRenderingIntent - invalid intent: ${t}`)}const o=a&Dr&&i instanceof bl?i:this.annotationStorage;switch(e){case jr.DISABLE:a+=Nr;break;case jr.ENABLE:break;case jr.ENABLE_FORMS:a+=Ir;break;case jr.ENABLE_STORAGE:a+=Or,r=o.serializable;break;default:uo(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(a+=Fr),n&&(a+=Br);const{ids:l,hash:h}=o.modifiedIds;return{renderingIntent:a,cacheKey:[a,r.hash,h].join("_"),annotationStorageSerializable:r,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#Ws?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Us.values())t.push(e._destroy());this.#Us.clear(),this.#Hs.clear(),this.#$s.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.#Vs.clear(),this.filterFactory.destroy(),oc.cleanup(),this._networkStream?.cancelAllRequests(new ko("Worker was terminated.")),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)=>{go(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:i}){i?e.close():(go(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",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:s,contentLength:n}=this._fullReader;return i&&s||(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),{isStreamingSupported:i,isRangeSupported:s,contentLength:n}})),t.on("GetRangeReader",((t,e)=>{go(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then((function({value:t,done:i}){i?e.close():(go(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{i.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}):e.close()})),t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new uc(t,this))})),t.on("DocException",(t=>{e._capability.reject(Fl(t))})),t.on("PasswordRequest",(t=>{this.#Ws=Promise.withResolvers();try{if(!e.onPassword)throw Fl(t);const i=t=>{t instanceof Error?this.#Ws.reject(t):this.#Ws.resolve({password:t})};e.onPassword(i,t.code)}catch(t){this.#Ws.reject(t)}return this.#Ws.promise})),t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)})),t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#Us.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)})),t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in s){const t=s.error;uo(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const n=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new wl(s,n);this.fontLoader.bind(a).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a.fontExtraProperties&&a.data&&(a.data=null),this.commonObjs.resolve(e,a)}));break;case"CopyLocalImage":const{imageRef:r}=s;go(r,"The imageRef must be defined.");for(const t of this.#Us.values())for(const[,i]of t.objs)if(i?.ref===r)return i.dataLen?(this.commonObjs.resolve(e,structuredClone(i)),i.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null})),t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#Us.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()})),t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})})),t.on("FetchBinaryData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");const e=this[t.type];if(!e)throw new Error(`${t.type} not initialized, see the \`useWorkerFetch\` parameter.`);return e.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&uo("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,i=this.#Hs.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#$s.set(i.refStr,t);const s=new pc(e,i,this,this._params.pdfBug);return this.#Us.set(e,s),s}));return this.#Hs.set(e,s),s}getPageIndex(t){return Al(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.#Gs("GetFieldObjects")}hasJSActions(){return this.#Gs("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.#Gs("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.#Gs("GetOptionalContentConfig").then((e=>new Nh(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Vs.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Dh(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#Vs.set(t,i),i}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.#Us.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear(),t||this.fontLoader.clear(),this.#Vs.clear(),this.filterFactory.destroy(!0),oc.cleanup()}}cachedPageNumber(t){if(!Al(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#$s.get(e)??null}}class _c{#qs=null;onContinue=null;onError=null;constructor(t){this.#qs=t}get promise(){return this.#qs.capability.promise}cancel(t=0){this.#qs.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#qs.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#qs;return t.form||t.canvas&&e?.size>0}}class mc{#Ks=null;static#Xs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:c=!1,pageColors:d=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=s,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=c,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new _c(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(mc.#Xs.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.");mc.#Xs.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:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new Ph(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#Ks&&(window.cancelAnimationFrame(this.#Ks),this.#Ks=null),mc.#Xs.delete(this._canvas),t||=new zo(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}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?this.#Ks=window.requestAnimationFrame((()=>{this.#Ks=null,this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),mc.#Xs.delete(this._canvas),this.callback())))}}function vc(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function bc(t){return Math.max(0,Math.min(255,255*t))}class yc{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=bc(t),t,t]}static G_HTML([t]){const e=vc(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(bc)}static RGB_HTML(t){return`#${t.map(vc).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[bc(1-Math.min(1,t+s)),bc(1-Math.min(1,i+s)),bc(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class wc{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");return s.setAttribute("version","1.1"),i||(s.setAttribute("width",`${t}px`),s.setAttribute("height",`${e}px`)),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){po("Abstract method `_createSVG` called.")}}class xc extends wc{_createSVG(t){return document.createElementNS(No,t)}}class Ac{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",(t=>{s.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=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow),i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});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 l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t),r&&lc.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);l.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:i}),o.children?.length>0)h.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);r&&lc.shouldBuildText(c)&&l.push(t),d.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const kc=1e3,Tc=new WeakSet;class Sc{static create(t){switch(t.data.annotationType){case Xr.LINK:return new Cc(t);case Xr.TEXT:return new Rc(t);case Xr.WIDGET:switch(t.data.fieldType){case"Tx":return new Pc(t);case"Btn":return t.data.radioButton?new Ic(t):t.data.checkBox?new Dc(t):new Oc(t);case"Ch":return new Nc(t);case"Sig":return new Lc(t)}return new Mc(t);case Xr.POPUP:return new Fc(t);case Xr.FREETEXT:return new jc(t);case Xr.LINE:return new zc(t);case Xr.SQUARE:return new Vc(t);case Xr.CIRCLE:return new Uc(t);case Xr.POLYLINE:return new Hc(t);case Xr.CARET:return new Wc(t);case Xr.INK:return new Gc(t);case Xr.POLYGON:return new $c(t);case Xr.HIGHLIGHT:return new qc(t);case Xr.UNDERLINE:return new Kc(t);case Xr.SQUIGGLY:return new Xc(t);case Xr.STRIKEOUT:return new Yc(t);case Xr.STAMP:return new Qc(t);case Xr.FILEATTACHMENT:return new Jc(t);default:return new Ec(t)}}}class Ec{#Ys=null;#Qs=!1;#Js=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(i)),s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ec._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Ys||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#Zs(e),this.#Js?.popup.updateEdited(t)}resetEdited(){this.#Ys&&(this.#Zs(this.#Ys.rect),this.#Js?.popup.resetEdited(),this.#Ys=null)}#Zs(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t),e.left=100*(t[0]-r)/n+"%",e.top=100*(a-t[3]+o)/a+"%",0===s?(e.width=100*(t[2]-t[0])/n+"%",e.height=100*(t[3]-t[1])/a+"%"):this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Mc||(n.tabIndex=kc);const{style:a}=n;if(a.zIndex=this.parent.zIndex++,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Fc){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:r,height:o}=this;if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;a.borderRadius=e}else if(this instanceof Ic){const t=`calc(${r}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case Yr:a.borderStyle="solid";break;case Qr:a.borderStyle="dashed";break;case Jr:uo("Unimplemented border style: beveled");break;case Zr:uo("Unimplemented border style: inset");break;case to:a.borderBottomStyle="solid"}const s=e.borderColor||null;s?(this.#Qs=!0,a.borderColor=Ro.makeHexColor(0|s[0],0|s[1],0|s[2])):a.borderWidth=0}const l=Ro.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:c,pageX:d,pageY:u}=s.rawDims;a.left=100*(l[0]-d)/h+"%",a.top=100*(l[1]-u)/c+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/h+"%",a.height=100*o/c+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims;let{width:n,height:a}=this;t%180!=0&&([n,a]=[a,n]),e.style.width=100*n/i+"%",e.style.height=100*a/s+"%",e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=yc[`${n}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:yc[`${n}_rgb`](a)})};return mo(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor: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 i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];if(a){a({detail:{[s]:n},target:t}),delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#Qs){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=s-e,l=n-i,{svgFactory:h}=this,c=h.createElement("svg");c.classList.add("quadrilateralsContainer"),c.setAttribute("width",0),c.setAttribute("height",0);const d=h.createElement("defs");c.append(d);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),d.append(u);for(let i=2,s=t.length;i<s;i+=8){const s=t[i],a=t[i+1],c=t[i+2],d=t[i+3],p=h.createElement("rect"),g=(c-e)/o,f=(n-a)/l,_=(s-c)/o,m=(a-d)/l;p.setAttribute("x",g),p.setAttribute("y",f),p.setAttribute("width",_),p.setAttribute("height",m),u.append(p),r?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${f}" width="${_}" height="${m}"/>`)}this.#Qs&&(r.push("</g></svg>')"),a.backgroundImage=r.join("")),this.container.append(c),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#Js=new Fc({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){po("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Tc.has(r)?i.push({id:n,exportValue:s,domElement:r}):uo(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Tc.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class Cc extends Ec{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),s=!0):t.action?(this._bindNamedAction(i,t.action),s=!0):t.attachment?(this.#tn(i,t.attachment,t.attachmentDest),s=!0):t.setOCGState?(this.#en(i,t.setOCGState),s=!0):t.dest?(this._bindLink(i,t.dest),s=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),s=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),s=!0):this.isTooltipOnly&&!s&&(this._bindLink(i,""),s=!0)),this.container.classList.add("linkAnnotation"),s&&this.container.append(i),this.container}#in(){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.#in()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#in()}#tn(t,e,i=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#in()}#en(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#in()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}}),!1))}t.onclick||(t.onclick=()=>!1),this.#in()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#in(),!this._fieldObjects)return uo('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}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 i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Tc.has(i)?i.dispatchEvent(new Event("resetform")):uo(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class Rc extends Ec{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 Mc extends Ec{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Eo.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,n,a,s),"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":Ro.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,n=t.style;let a;const r=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(Mr*s))||1);a=Math.min(s,r(e/Mr))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(s,r(t/Mr))}n.fontSize=`calc(${a}px * var(--total-scale-factor))`,n.color=Ro.makeHexColor(i[0],i[1],i[2]),null!==this.data.textAlignment&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class Pc extends Mc{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=i),n.setValue(a.id,{[s]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.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?(i=document.createElement("textarea"),i.textContent=r??n,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type=this.data.password?"password":"text",i.setAttribute("value",r??n),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),Tc.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=kc,this._setRequired(i,this.data.required),a&&(i.maxLength=a),i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value}),this.setPropertyOnSiblings(i,"value",s.target.value,"value"),o.formattedValue=null})),i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null}));let l=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue),o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)})),i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s,null!=s&&i.target!==document.activeElement&&(i.target.value=s),t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",s);let a=o.userValue;!a||a.length<=s||(a=a.slice(0,s),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(s,i)})),i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:s}=t.target;o.lastCommittedValue!==s&&(o.lastCommittedValue=s,o.userValue=s,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))}));const s=l;l=null,i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i,o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),s(t)})),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})})),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}if(l&&i.addEventListener("blur",l),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--total-scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Lc extends Mc{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Dc extends Mc{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof s&&(s="Off"!==s,t.setValue(i,{value:s})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return Tc.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=kc,n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i),t.setValue(s.id,{value:i})}t.setValue(i,{value:a})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue})),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Ic extends Mc{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s&&(s=s!==e.buttonValue,t.setValue(i,{value:s})),s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");if(Tc.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.tabIndex=kc,n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue})),this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e),t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Oc extends Cc{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 Nc extends Mc{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Tc.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=kc;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(s.size=this.data.options.length,this.data.multiSelect&&(s.multiple=!0)),s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),n=!1),s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),s.prepend(t),a=()=>{t.remove(),s.removeEventListener("input",a),a=null},s.addEventListener("input",a)}const r=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let o=r(!1);const l=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};return this.enableScripting&&this.hasJSActions?(s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,l=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=l.has(t.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;if(n[a].selected=!1,s.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:l(i)}),o=r(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(i){const{index:n,displayValue:a,exportValue:h}=i.detail.insert,c=s.children[n],d=document.createElement("option");d.textContent=a,d.value=h,c?c.before(d):s.append(d),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e,n.value=i,s.append(n)}s.options.length>0&&(s.options[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)})),s.addEventListener("input",(i=>{const s=r(!0),n=r(!1);t.setValue(e,{value:s}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))):s.addEventListener("input",(function(i){t.setValue(e,{value:r(!0)})})),this.data.combo&&this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Fc extends Ec{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:Ec._hasPopupData(e)}),this.elements=i,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Bc({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 i of this.elements)i.popup=t,i.container.ariaHasPopup="dialog",e.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",e.map((t=>`${Do}${t}`)).join(",")),this.container}}class Bc{#sn=this.#nn.bind(this);#an=this.#rn.bind(this);#on=this.#ln.bind(this);#hn=this.#cn.bind(this);#dn=null;#_t=null;#un=null;#pn=null;#gn=null;#fn=null;#_n=null;#mn=!1;#vn=null;#E=null;#bn=null;#yn=null;#wn=null;#Ys=null;#xn=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:c}){this.#_t=t,this.#wn=s,this.#un=a,this.#yn=r,this.#fn=o,this.#dn=e,this.#bn=l,this.#_n=h,this.#gn=i,this.#pn=qo.toDateObject(n),this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger)t.addEventListener("click",this.#hn),t.addEventListener("mouseenter",this.#on),t.addEventListener("mouseleave",this.#an),t.classList.add("popupTriggerArea");for(const t of i)t.container?.addEventListener("keydown",this.#sn);this.#_t.hidden=!0,c&&this.#cn()}render(){if(this.#vn)return;const t=this.#vn=document.createElement("div");if(t.className="popup",this.#dn){const e=t.style.outlineColor=Ro.makeHexColor(...this.#dn);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");if(e.append(i),({dir:i.dir,str:i.textContent}=this.#wn),t.append(e),this.#pn){const t=document.createElement("span");t.classList.add("popupDate"),t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#pn.valueOf()})),e.append(t)}const s=this.#An;if(s)Ac.render({xfaHtml:s,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const e=this._formatContents(this.#un);t.append(e)}this.#_t.append(t)}get#An(){const t=this.#yn,e=this.#un;return!t?.str||e?.str&&e.str!==t.str?null:this.#yn.html||null}get#kn(){return this.#An?.attributes?.style?.fontSize||0}get#Tn(){return this.#An?.attributes?.style?.color||null}#Sn(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#Tn,fontSize:this.#kn?`calc(${this.#kn}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent"),i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t<e;++t){const n=s[t];i.append(document.createTextNode(n)),t<e-1&&i.append(document.createElement("br"))}return i}#nn(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#mn)&&this.#cn()}updateEdited({rect:t,popupContent:e}){this.#Ys||={contentsObj:this.#un,richText:this.#yn},t&&(this.#E=null),e&&(this.#yn=this.#Sn(e),this.#un=null),this.#vn?.remove(),this.#vn=null}resetEdited(){this.#Ys&&(({contentsObj:this.#un,richText:this.#yn}=this.#Ys),this.#Ys=null,this.#vn?.remove(),this.#vn=null,this.#E=null)}#En(){if(null!==this.#E)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:s,pageY:n}}}=this.#fn;let a=!!this.#_n,r=a?this.#_n:this.#bn;for(const t of this.#gn)if(!r||null!==Ro.intersect(t.data.rect,r)){r=t.data.rect,a=!0;break}const o=Ro.normalizeRect([r[0],t[3]-r[1]+t[1],r[2],t[3]-r[3]+t[1]]),l=a?r[2]-r[0]+5:0,h=o[0]+l,c=o[1];this.#E=[100*(h-s)/e,100*(c-n)/i];const{style:d}=this.#_t;d.left=`${this.#E[0]}%`,d.top=`${this.#E[1]}%`}#cn(){this.#mn=!this.#mn,this.#mn?(this.#ln(),this.#_t.addEventListener("click",this.#hn),this.#_t.addEventListener("keydown",this.#sn)):(this.#rn(),this.#_t.removeEventListener("click",this.#hn),this.#_t.removeEventListener("keydown",this.#sn))}#ln(){this.#vn||this.render(),this.isVisible?this.#mn&&this.#_t.classList.add("focused"):(this.#En(),this.#_t.hidden=!1,this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex)+1e3)}#rn(){this.#_t.classList.remove("focused"),!this.#mn&&this.isVisible&&(this.#_t.hidden=!0,this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex)-1e3)}forceHide(){this.#xn=this.isVisible,this.#xn&&(this.#_t.hidden=!0)}maybeShow(){this.#xn&&(this.#vn||this.#ln(),this.#xn=!1,this.#_t.hidden=!1)}get isVisible(){return!1===this.#_t.hidden}}class jc extends Ec{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=zr.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 i=document.createElement("span");i.textContent=e,t.append(i)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class zc extends Ec{#Cn=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=this.#Cn=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"),s.append(n),this.container.append(s),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Cn}addHighlightArea(){this.container.classList.add("highlightArea")}}class Vc extends Ec{#Rn=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=t.borderStyle.width,a=this.#Rn=this.svgFactory.createElement("svg:rect");return a.setAttribute("x",n/2),a.setAttribute("y",n/2),a.setAttribute("width",e-n),a.setAttribute("height",i-n),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),s.append(a),this.container.append(s),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Rn}addHighlightArea(){this.container.classList.add("highlightArea")}}class Uc extends Ec{#Mn=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=t.borderStyle.width,a=this.#Mn=this.svgFactory.createElement("svg:ellipse");return a.setAttribute("cx",e/2),a.setAttribute("cy",i/2),a.setAttribute("rx",e/2-n/2),a.setAttribute("ry",i/2-n/2),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),s.append(a),this.container.append(s),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Mn}addHighlightArea(){this.container.classList.add("highlightArea")}}class Hc extends Ec{#Pn=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:i,popupRef:s},width:n,height:a}=this;if(!e)return this.container;const r=this.svgFactory.create(n,a,!0);let o=[];for(let i=0,s=e.length;i<s;i+=2){const s=e[i]-t[0],n=t[3]-e[i+1];o.push(`${s},${n}`)}o=o.join(" ");const l=this.#Pn=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",o),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),r.append(l),this.container.append(r),!s&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Pn}addHighlightArea(){this.container.classList.add("highlightArea")}}class $c extends Hc{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Wc extends Ec{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 Gc extends Ec{#Ln=null;#Dn=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?zr.HIGHLIGHT:zr.INK}#In(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:i,borderStyle:s,popupRef:n}}=this,{transform:a,width:r,height:o}=this.#In(e,t),l=this.svgFactory.create(r,o,!0),h=this.#Ln=this.svgFactory.createElement("svg:g");l.append(h),h.setAttribute("stroke-width",s.width||1),h.setAttribute("stroke-linecap","round"),h.setAttribute("stroke-linejoin","round"),h.setAttribute("stroke-miterlimit",10),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),h.setAttribute("transform",a);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#Dn.push(e),e.setAttribute("points",i[t].join(",")),h.append(e)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:s}=t,n=this.#Ln;if(e>=0&&n.setAttribute("stroke-width",e||1),i)for(let t=0,e=this.#Dn.length;t<e;t++)this.#Dn[t].setAttribute("points",i[t].join(","));if(s){const{transform:t,width:e,height:i}=this.#In(this.data.rotation,s);n.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`),n.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#Dn}addHighlightArea(){this.container.classList.add("highlightArea")}}class qc extends Ec{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=zr.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class Kc extends Ec{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 Xc extends Ec{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 Yc extends Ec{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 Qc extends Ec{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=zr.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Jc extends Ec{#On=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 i;e.hasAppearance||0===e.fillAlpha?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)),i.addEventListener("dblclick",this.#Nn.bind(this)),this.#On=i;const{isMac:s}=Eo.platform;return t.addEventListener("keydown",(t=>{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Nn()})),!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#On}addHighlightArea(){this.container.classList.add("highlightArea")}#Nn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Zc{#Fn=null;#Bn=null;#jn=new Map;#zn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t,this.#Fn=e,this.#Bn=i,this.#zn=r||null,this.page=n,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#jn.size>0}async#Vn(t,e){const i=t.firstChild||t,s=i.id=`${Do}${e}`,n=await(this.#zn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t),this.#Fn?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;Qo(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new xc,annotationStorage:t.annotationStorage||new vl,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===Xr.POPUP;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;n.data=t;const i=Sc.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden"),await this.#Vn(a,t.id),i._isEditable&&(this.#jn.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}this.#Un()}async addLinkAnnotations(t,e){const i={data:null,layer:this.div,linkService:e,svgFactory:new xc,parent:this};for(const e of t){e.borderStyle||=Zc._defaultBorderStyle,i.data=e;const t=Sc.create(i);if(!t.isRenderable)continue;const s=t.render();await this.#Vn(s,e.id)}}update({viewport:t}){const e=this.div;this.viewport=t,Qo(e,{rotation:t.rotation}),this.#Un(),e.hidden=!1}#Un(){if(!this.#Bn)return;const t=this.div;for(const[e,i]of this.#Bn){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i);const a=this.#jn.get(e);a&&(a._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(e,s.id,i),a._hasNoCanvas=!1):a.canvas=i)}this.#Bn.clear()}getEditableAnnotations(){return Array.from(this.#jn.values())}getEditableAnnotation(t){return this.#jn.get(t)}static get _defaultBorderStyle(){return mo(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:Yr,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const td=/\r\n?|\n/g;class ed extends dl{#dn;#Hn="";#$n=`${this.id}-editor`;#Wn=null;#kn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=ed.prototype,e=t=>t.isEmpty(),i=ll.TRANSLATE_SMALL,s=ll.TRANSLATE_BIG;return mo(this,"_keyboardManager",new rl([[["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:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}]]))}static _type="freetext";static _editorType=zr.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#dn=t.color||ed._defaultColor||dl._defaultLineColor,this.#kn=t.fontSize||ed._defaultFontSize}static initialize(t,e){dl.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case Vr.FREETEXT_SIZE:ed._defaultFontSize=e;break;case Vr.FREETEXT_COLOR:ed._defaultColor=e}}updateParams(t,e){switch(t){case Vr.FREETEXT_SIZE:this.#Gn(e);break;case Vr.FREETEXT_COLOR:this.#qn(e)}}static get defaultPropertiesToUpdate(){return[[Vr.FREETEXT_SIZE,ed._defaultFontSize],[Vr.FREETEXT_COLOR,ed._defaultColor||dl._defaultLineColor]]}get propertiesToUpdate(){return[[Vr.FREETEXT_SIZE,this.#kn],[Vr.FREETEXT_COLOR,this.#dn]]}#Gn(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#kn)*this.parentScale),this.#kn=t,this.#Kn()},i=this.#kn;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Vr.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#qn(t){const e=t=>{this.#dn=this.editorDiv.style.color=t},i=this.#dn;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Vr.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-ed._internalPadding*t,-(ed._internalPadding+this.#kn)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#Wn=new AbortController;const t=this._uiManager.combinedSignal(this.#Wn);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return!!super.disableEditMode()&&(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#$n),this._isDraggable=!0,this.#Wn?.abort(),this.#Wn=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0)}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#Xn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(ed.#Yn(i)),e=i);return t.join("\n")}#Kn(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=s,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#Hn,e=this.#Hn=this.#Xn().trimEnd();if(t===e)return;const i=t=>{this.#Hn=t,t?(this.#Qn(),this._uiManager.rebuild(this),this.#Kn()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#Kn()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){ed._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(this._isCopy||this.annotationElementId)&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#$n),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#kn}px * var(--total-scale-factor))`,i.color=this.#dn,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(n[0]-h)/o,u=e+this.height-(n[1]-c)/l;break;case 90:d=t+(n[0]-h)/o,u=e-(n[1]-c)/l,[a,r]=[r,-a];break;case 180:d=t-this.width+(n[0]-h)/o,u=e-(n[1]-c)/l,[a,r]=[-a,-r];break;case 270:d=t+(n[0]-h-this.height*l)/o,u=e+(n[1]-c-this.width*o)/l,[a,r]=[-r,a]}this.setAt(d*i,u*s,a,r)}else this._moveAfterPaste(t,e);this.#Qn(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#Yn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(td,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=ed.#Jn(e.getData("text")||"").replaceAll(td,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n"))return a.insertNode(document.createTextNode(s)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(h.push(r.nodeValue.slice(o).replaceAll(td,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(ed.#Yn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(td,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(ed.#Yn(i))}this.#Hn=`${l.join("\n")}${s}${h.join("\n")}`,this.#Qn();const c=new Range;let d=Math.sumPrecise(l.map((t=>t.length)));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(d<=e){c.setStart(t,d),c.setEnd(t,d);break}d-=e}n.removeAllRanges(),n.addRange(c)}#Qn(){if(this.editorDiv.replaceChildren(),this.#Hn)for(const t of this.#Hn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#Zn(){return this.#Hn.replaceAll(" "," ")}static#Jn(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof jc){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:c}}}=t;if(!l||0===l.length)return null;s=t={annotationType:zr.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);return n.#kn=t.fontSize,n.#dn=Ro.makeHexColor(...t.color),n.#Hn=ed.#Jn(t.value),n.annotationElementId=t.id||null,n._initialData=s,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=ed._internalPadding*this.parentScale,i=this.getRect(e,e),s=dl._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#dn),n={annotationType:zr.FREETEXT,color:s,fontSize:this.#kn,value:this.#Zn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?(n.isCopy=!0,n):this.annotationElementId&&!this.#ta(n)?null:(n.id=this.annotationElementId,n)}#ta(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#kn}px * var(--total-scale-factor))`,i.color=this.#dn,e.replaceChildren();for(const t of this.#Hn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}const s=ed._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(s,s),popupContent:this.#Hn}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class id{static PRECISION=1e-4;toSVGPath(){po("Abstract method `toSVGPath` must be implemented.")}get box(){po("Abstract getter `box` must be implemented.")}serialize(t,e){po("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r]*s,a[r+1]=i+t[r+1]*n;return a}static _rescaleAndSwap(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r+1]*s,a[r+1]=i+t[r]*n;return a}static _translate(t,e,i,s){s||=new Float32Array(t.length);for(let n=0,a=t.length;n<a;n+=2)s[n]=e+t[n],s[n+1]=i+t[n+1];return s}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,s,n){switch(n){case 90:return[1-e/i,t/s];case 180:return[1-t/i,1-e/s];case 270:return[e/i,1-t/s];default:return[t/i,e/s]}}static _normalizePagePoint(t,e,i){switch(i){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,i,s,n,a){return[(t+5*i)/6,(e+5*s)/6,(5*i+n)/6,(5*s+a)/6,(i+n)/2,(s+a)/2]}}class sd{#ea;#ia=[];#sa;#na;#aa=[];#ra=new Float32Array(18);#oa;#la;#ha;#ca;#da;#ua;#pa=[];static#ga=8;static#fa=2;static#_a=sd.#ga+sd.#fa;constructor({x:t,y:e},i,s,n,a,r=0){this.#ea=i,this.#ua=n*s,this.#na=a,this.#ra.set([NaN,NaN,NaN,NaN,t,e],6),this.#sa=r,this.#ca=sd.#ga*s,this.#ha=sd.#_a*s,this.#da=s,this.#pa.push(t,e)}isEmpty(){return isNaN(this.#ra[8])}#ma(){const t=this.#ra.subarray(4,6),e=this.#ra.subarray(16,18),[i,s,n,a]=this.#ea;return[(this.#oa+(t[0]-e[0])/2-i)/n,(this.#la+(t[1]-e[1])/2-s)/a,(this.#oa+(e[0]-t[0])/2-i)/n,(this.#la+(e[1]-t[1])/2-s)/a]}add({x:t,y:e}){this.#oa=t,this.#la=e;const[i,s,n,a]=this.#ea;let[r,o,l,h]=this.#ra.subarray(8,12);const c=t-l,d=e-h,u=Math.hypot(c,d);if(u<this.#ha)return!1;const p=u-this.#ca,g=p/u,f=g*c,_=g*d;let m=r,v=o;r=l,o=h,l+=f,h+=_,this.#pa?.push(t,e);const b=f/p,y=-_/p*this.#ua,w=b*this.#ua;if(this.#ra.set(this.#ra.subarray(2,8),0),this.#ra.set([l+y,h+w],4),this.#ra.set(this.#ra.subarray(14,18),12),this.#ra.set([l-y,h-w],16),isNaN(this.#ra[6]))return 0===this.#aa.length&&(this.#ra.set([r+y,o+w],2),this.#aa.push(NaN,NaN,NaN,NaN,(r+y-i)/n,(o+w-s)/a),this.#ra.set([r-y,o-w],14),this.#ia.push(NaN,NaN,NaN,NaN,(r-y-i)/n,(o-w-s)/a)),this.#ra.set([m,v,r,o,l,h],6),!this.isEmpty();this.#ra.set([m,v,r,o,l,h],6);return Math.abs(Math.atan2(v-o,m-r)-Math.atan2(_,f))<Math.PI/2?([r,o,l,h]=this.#ra.subarray(2,6),this.#aa.push(NaN,NaN,NaN,NaN,((r+l)/2-i)/n,((o+h)/2-s)/a),[r,o,m,v]=this.#ra.subarray(14,18),this.#ia.push(NaN,NaN,NaN,NaN,((m+r)/2-i)/n,((v+o)/2-s)/a),!0):([m,v,r,o,l,h]=this.#ra.subarray(0,6),this.#aa.push(((m+5*r)/6-i)/n,((v+5*o)/6-s)/a,((5*r+l)/6-i)/n,((5*o+h)/6-s)/a,((r+l)/2-i)/n,((o+h)/2-s)/a),[l,h,r,o,m,v]=this.#ra.subarray(12,18),this.#ia.push(((m+5*r)/6-i)/n,((v+5*o)/6-s)/a,((5*r+l)/6-i)/n,((5*o+h)/6-s)/a,((r+l)/2-i)/n,((o+h)/2-s)/a),!0)}toSVGPath(){if(this.isEmpty())return"";const t=this.#aa,e=this.#ia;if(isNaN(this.#ra[6])&&!this.isEmpty())return this.#va();const i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#ba(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return this.#ya(i),i.join(" ")}#va(){const[t,e,i,s]=this.#ea,[n,a,r,o]=this.#ma();return`M${(this.#ra[2]-t)/i} ${(this.#ra[3]-e)/s} L${(this.#ra[4]-t)/i} ${(this.#ra[5]-e)/s} L${n} ${a} L${r} ${o} L${(this.#ra[16]-t)/i} ${(this.#ra[17]-e)/s} L${(this.#ra[14]-t)/i} ${(this.#ra[15]-e)/s} Z`}#ya(t){const e=this.#ia;t.push(`L${e[4]} ${e[5]} Z`)}#ba(t){const[e,i,s,n]=this.#ea,a=this.#ra.subarray(4,6),r=this.#ra.subarray(16,18),[o,l,h,c]=this.#ma();t.push(`L${(a[0]-e)/s} ${(a[1]-i)/n} L${o} ${l} L${h} ${c} L${(r[0]-e)/s} ${(r[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,a){return new nd(t,e,i,s,n,a)}getOutlines(){const t=this.#aa,e=this.#ia,i=this.#ra,[s,n,a,r]=this.#ea,o=new Float32Array((this.#pa?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2)o[t]=(this.#pa[t]-s)/a,o[t+1]=(this.#pa[t+1]-n)/r;if(o[o.length-2]=(this.#oa-s)/a,o[o.length-1]=(this.#la-n)/r,isNaN(i[6])&&!this.isEmpty())return this.#wa(o);const l=new Float32Array(this.#aa.length+24+this.#ia.length);let h=t.length;for(let e=0;e<h;e+=2)isNaN(t[e])?l[e]=l[e+1]=NaN:(l[e]=t[e],l[e+1]=t[e+1]);h=this.#xa(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(l[h]=l[h+1]=NaN,h+=2):(l[h]=e[t+i],l[h+1]=e[t+i+1],h+=2);return this.#Aa(l,h),this.newFreeDrawOutline(l,o,this.#ea,this.#da,this.#sa,this.#na)}#wa(t){const e=this.#ra,[i,s,n,a]=this.#ea,[r,o,l,h]=this.#ma(),c=new Float32Array(36);return c.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/a,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/a,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/a],0),this.newFreeDrawOutline(c,t,this.#ea,this.#da,this.#sa,this.#na)}#Aa(t,e){const i=this.#ia;return t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e),e+6}#xa(t,e){const i=this.#ra.subarray(4,6),s=this.#ra.subarray(16,18),[n,a,r,o]=this.#ea,[l,h,c,d]=this.#ma();return t.set([NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o],e),e+24}}class nd extends id{#ea;#ka=new Float32Array(4);#sa;#na;#pa;#da;#Ta;constructor(t,e,i,s,n,a){super(),this.#Ta=t,this.#pa=e,this.#ea=i,this.#da=s,this.#sa=n,this.#na=a,this.lastPoint=[NaN,NaN],this.#Sa(a);const[r,o,l,h]=this.#ka;for(let e=0,i=t.length;e<i;e+=2)t[e]=(t[e]-r)/l,t[e+1]=(t[e+1]-o)/h;for(let t=0,i=e.length;t<i;t+=2)e[t]=(e[t]-r)/l,e[t+1]=(e[t+1]-o)/h}toSVGPath(){const t=[`M${this.#Ta[4]} ${this.#Ta[5]}`];for(let e=6,i=this.#Ta.length;e<i;e+=6)isNaN(this.#Ta[e])?t.push(`L${this.#Ta[e+4]} ${this.#Ta[e+5]}`):t.push(`C${this.#Ta[e]} ${this.#Ta[e+1]} ${this.#Ta[e+2]} ${this.#Ta[e+3]} ${this.#Ta[e+4]} ${this.#Ta[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,i,s],n){const a=i-t,r=s-e;let o,l;switch(n){case 0:o=id._rescale(this.#Ta,t,s,a,-r),l=id._rescale(this.#pa,t,s,a,-r);break;case 90:o=id._rescaleAndSwap(this.#Ta,t,e,a,r),l=id._rescaleAndSwap(this.#pa,t,e,a,r);break;case 180:o=id._rescale(this.#Ta,i,e,-a,r),l=id._rescale(this.#pa,i,e,-a,r);break;case 270:o=id._rescaleAndSwap(this.#Ta,i,s,-a,-r),l=id._rescaleAndSwap(this.#pa,i,s,-a,-r)}return{outline:Array.from(o),points:[Array.from(l)]}}#Sa(t){const e=this.#Ta;let i=e[4],s=e[5];const n=[i,s,i,s];let a=i,r=s;const o=t?Math.max:Math.min;for(let t=6,l=e.length;t<l;t+=6){const l=e[t+4],h=e[t+5];if(isNaN(e[t]))Ro.pointBoundingBox(l,h,n),r<h?(a=l,r=h):r===h&&(a=o(a,l));else{const l=[1/0,1/0,-1/0,-1/0];Ro.bezierBoundingBox(i,s,...e.slice(t,t+6),l),Ro.rectBoundingBox(...l,n),r<l[3]?(a=l[2],r=l[3]):r===l[3]&&(a=o(a,l[2]))}i=l,s=h}const l=this.#ka;l[0]=n[0]-this.#sa,l[1]=n[1]-this.#sa,l[2]=n[2]-n[0]+2*this.#sa,l[3]=n[3]-n[1]+2*this.#sa,this.lastPoint=[a,r]}get box(){return this.#ka}newOutliner(t,e,i,s,n,a=0){return new sd(t,e,i,s,n,a)}getNewOutline(t,e){const[i,s,n,a]=this.#ka,[r,o,l,h]=this.#ea,c=n*l,d=a*h,u=i*l+r,p=s*h+o,g=this.newOutliner({x:this.#pa[0]*c+u,y:this.#pa[1]*d+p},this.#ea,this.#da,t,this.#na,e??this.#sa);for(let t=2;t<this.#pa.length;t+=2)g.add({x:this.#pa[t]*c+u,y:this.#pa[t+1]*d+p});return g.getOutlines()}}class ad{#ea;#Ea;#Ca=[];#Ra=[];constructor(t,e=0,i=0,s=!0){const n=[1/0,1/0,-1/0,-1/0],a=1e-4;for(const{x:i,y:s,width:r,height:o}of t){const t=Math.floor((i-e)/a)*a,l=Math.ceil((i+r+e)/a)*a,h=Math.floor((s-e)/a)*a,c=Math.ceil((s+o+e)/a)*a,d=[t,h,c,!0],u=[l,h,c,!1];this.#Ca.push(d,u),Ro.rectBoundingBox(t,h,l,c,n)}const r=n[2]-n[0]+2*i,o=n[3]-n[1]+2*i,l=n[0]-i,h=n[1]-i,c=this.#Ca.at(s?-1:-2),d=[c[0],c[2]];for(const t of this.#Ca){const[e,i,s]=t;t[0]=(e-l)/r,t[1]=(i-h)/o,t[2]=(s-h)/o}this.#ea=new Float32Array([l,h,r,o]),this.#Ea=d}getOutlines(){this.#Ca.sort(((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#Ca)e[3]?(t.push(...this.#Ma(e)),this.#Pa(e)):(this.#La(e),t.push(...this.#Ma(e)));return this.#Da(t)}#Da(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t<s;t+=2){const s=e[t][2],n=e[t+1][2];s.push(n),n.push(s),i.add(s),i.add(n)}const s=[];let n;for(;i.size>0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,c=a;for(n=[e,r],s.push(n);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,a,r,o,l]=t,h!==e&&(n.push(h,c,e,c===a?a:r),h=e),c=c===a?r:a}n.push(h,c)}return new rd(s,this.#ea,this.#Ea)}#Ia(t){const e=this.#Ra;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a<t?i=n+1:s=n-1}return s+1}#Pa([,t,e]){const i=this.#Ia(t);this.#Ra.splice(i,0,[t,e])}#La([,t,e]){const i=this.#Ia(t);for(let s=i;s<this.#Ra.length;s++){const[i,n]=this.#Ra[s];if(i!==t)break;if(i===t&&n===e)return void this.#Ra.splice(s,1)}for(let s=i-1;s>=0;s--){const[i,n]=this.#Ra[s];if(i!==t)break;if(i===t&&n===e)return void this.#Ra.splice(s,1)}}#Ma(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#Ia(s);for(let t=0;t<a;t++){const[i,s]=this.#Ra[t];for(let t=0,a=n.length;t<a;t++){const[,r,o]=n[t];if(!(s<=r||o<=i))if(r>=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1),t--,a--}else n[t][2]=i,o>s&&n.push([e,s,o])}}return n}}class rd extends id{#ea;#Oa;constructor(t,e,i){super(),this.#Oa=t,this.#ea=e,this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Oa){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n<e.length;n+=2){const a=e[n],r=e[n+1];a===i?(t.push(`V${r}`),s=r):r===s&&(t.push(`H${a}`),i=a)}t.push("Z")}return t.join(" ")}serialize([t,e,i,s],n){const a=[],r=i-t,o=s-e;for(const e of this.#Oa){const i=new Array(e.length);for(let n=0;n<e.length;n+=2)i[n]=t+e[n]*r,i[n+1]=s-e[n+1]*o;a.push(i)}return a}get box(){return this.#ea}get classNamesForOutlining(){return["highlightOutline"]}}class od extends sd{newFreeDrawOutline(t,e,i,s,n,a){return new ld(t,e,i,s,n,a)}}class ld extends nd{newOutliner(t,e,i,s,n,a=0){return new od(t,e,i,s,n,a)}}class hd{#Na=null;#Fa=null;#Ba;#ja=null;#za=!1;#Va=!1;#a=null;#Ua;#Ha=null;#_=null;#$a;static#Wa=null;static get _keyboardManager(){return mo(this,"_keyboardManager",new rl([[["Escape","mac+Escape"],hd.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],hd.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],hd.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],hd.prototype._moveToPrevious],[["Home","mac+Home"],hd.prototype._moveToBeginning],[["End","mac+End"],hd.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#Va=!1,this.#$a=Vr.HIGHLIGHT_COLOR,this.#a=t):(this.#Va=!0,this.#$a=Vr.HIGHLIGHT_DEFAULT_COLOR),this.#_=t?._uiManager||e,this.#Ua=this.#_._eventBus,this.#Ba=t?.color||this.#_?.highlightColors.values().next().value||"#FFFF98",hd.#Wa||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Na=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=this.#_._signal;t.addEventListener("click",this.#Ga.bind(this),{signal:e}),t.addEventListener("keydown",this.#nn.bind(this),{signal:e});const i=this.#Fa=document.createElement("span");return i.className="swatch",i.setAttribute("aria-hidden",!0),i.style.backgroundColor=this.#Ba,t.append(i),t}renderMainDropdown(){const t=this.#ja=this.#qa();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#qa(){const t=document.createElement("div"),e=this.#_._signal;t.addEventListener("contextmenu",Wo,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[i,s]of this.#_.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",s),n.title=i,n.setAttribute("data-l10n-id",hd.#Wa[i]);const a=document.createElement("span");n.append(a),a.className="swatch",a.style.backgroundColor=s,n.setAttribute("aria-selected",s===this.#Ba),n.addEventListener("click",this.#Ka.bind(this,s),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#nn.bind(this),{signal:e}),t}#Ka(t,e){e.stopPropagation(),this.#Ua.dispatch("switchannotationeditorparams",{source:this,type:this.#$a,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#Na)return void this.#Ga(t);const e=t.target.getAttribute("data-color");e&&this.#Ka(e,t)}_moveToNext(t){this.#Xa?t.target!==this.#Na?t.target.nextSibling?.focus():this.#ja.firstChild?.focus():this.#Ga(t)}_moveToPrevious(t){t.target!==this.#ja?.firstChild&&t.target!==this.#Na?(this.#Xa||this.#Ga(t),t.target.previousSibling?.focus()):this.#Xa&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Xa?this.#ja.firstChild?.focus():this.#Ga(t)}_moveToEnd(t){this.#Xa?this.#ja.lastChild?.focus():this.#Ga(t)}#nn(t){hd._keyboardManager.exec(this,t)}#Ga(t){if(this.#Xa)return void this.hideDropdown();if(this.#za=0===t.detail,this.#Ha||(this.#Ha=new AbortController,window.addEventListener("pointerdown",this.#c.bind(this),{signal:this.#_.combinedSignal(this.#Ha)})),this.#ja)return void this.#ja.classList.remove("hidden");const e=this.#ja=this.#qa();this.#Na.append(e)}#c(t){this.#ja?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#ja?.classList.add("hidden"),this.#Ha?.abort(),this.#Ha=null}get#Xa(){return this.#ja&&!this.#ja.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#Va||(this.#Xa?(this.hideDropdown(),this.#Na.focus({preventScroll:!0,focusVisible:this.#za})):this.#a?.unselect())}updateColor(t){if(this.#Fa&&(this.#Fa.style.backgroundColor=t),!this.#ja)return;const e=this.#_.highlightColors.values();for(const i of this.#ja.children)i.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#Na?.remove(),this.#Na=null,this.#Fa=null,this.#ja?.remove(),this.#ja=null}}class cd extends dl{#Ya=null;#Qa=0;#Ja;#Za=null;#n=null;#tr=null;#er=null;#ir=0;#sr=null;#nr=null;#y=null;#ar=!1;#Ea=null;#rr;#or=null;#lr="";#ua;#hr="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=zr.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=cd.prototype;return mo(this,"_keyboardManager",new rl([[["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||cd._defaultColor,this.#ua=t.thickness||cd._defaultThickness,this.#rr=t.opacity||cd._defaultOpacity,this.#Ja=t.boxes||null,this.#hr=t.methodOfCreation||"",this.#lr=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#ar=!0,this.#cr(t),this.#dr()):this.#Ja&&(this.#Ya=t.anchorNode,this.#Qa=t.anchorOffset,this.#er=t.focusNode,this.#ir=t.focusOffset,this.#ur(),this.#dr(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#ar?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#ua,methodOfCreation:this.#hr}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#ur(){const t=new ad(this.#Ja,.001);this.#nr=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#nr.box;const e=new ad(this.#Ja,.0025,.001,"ltr"===this._uiManager.direction);this.#tr=e.getOutlines();const{lastPoint:i}=this.#tr;this.#Ea=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#cr({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#nr=t;if(this.#tr=t.getNewOutline(this.#ua/2+1.5,.0025),e>=0)this.#y=e,this.#Za=i,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#or=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#tr.box,path:{d:this.#tr.toSVGPath()}},!0);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#y,{bbox:cd.#pr(this.#nr.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#or,{bbox:cd.#pr(this.#tr.box,e),path:{d:this.#tr.toSVGPath()}})}const[s,n,a,r]=t.box;switch(this.rotation){case 0:this.x=s,this.y=n,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-s,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-s,this.y=1-n,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=s,this.width=a*e/t,this.height=r*t/e;break}}const{lastPoint:o}=this.#tr;this.#Ea=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){dl.initialize(t,e),cd._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case Vr.HIGHLIGHT_DEFAULT_COLOR:cd._defaultColor=e;break;case Vr.HIGHLIGHT_THICKNESS:cd._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Ea}updateParams(t,e){switch(t){case Vr.HIGHLIGHT_COLOR:this.#qn(e);break;case Vr.HIGHLIGHT_THICKNESS:this.#gr(e)}}static get defaultPropertiesToUpdate(){return[[Vr.HIGHLIGHT_DEFAULT_COLOR,cd._defaultColor],[Vr.HIGHLIGHT_THICKNESS,cd._defaultThickness]]}get propertiesToUpdate(){return[[Vr.HIGHLIGHT_COLOR,this.color||cd._defaultColor],[Vr.HIGHLIGHT_THICKNESS,this.#ua||cd._defaultThickness],[Vr.HIGHLIGHT_FREE,this.#ar]]}#qn(t){const e=(t,e)=>{this.color=t,this.#rr=e,this.parent?.drawLayer.updateProperties(this.#y,{root:{fill:t,"fill-opacity":e}}),this.#n?.updateColor(t)},i=this.color,s=this.#rr;this.addCommands({cmd:e.bind(this,t,cd._defaultOpacity),undo:e.bind(this,i,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Vr.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#gr(t){const e=this.#ua,i=t=>{this.#ua=t,this.#fr(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Vr.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.#n=new hd({editor:this}),t.addColorPicker(this.#n)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#_r())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#_r())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#mr(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#dr(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#mr():t&&(this.#dr(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#fr(t){if(!this.#ar)return;this.#cr({highlightOutlines:this.#nr.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#mr(){null!==this.#y&&this.parent&&(this.parent.drawLayer.remove(this.#y),this.#y=null,this.parent.drawLayer.remove(this.#or),this.#or=null)}#dr(t=this.parent){null===this.#y&&(({id:this.#y,clipPathId:this.#Za}=t.drawLayer.draw({bbox:this.#nr.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#rr},rootClass:{highlight:!0,free:this.#ar},path:{d:this.#nr.toSVGPath()}},!1,!0)),this.#or=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#ar},bbox:this.#tr.box,path:{d:this.#tr.toSVGPath()}},this.#ar),this.#sr&&(this.#sr.style.clipPath=this.#Za))}static#pr([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;this.#ar?(t=(t-this.rotation+360)%360,i=cd.#pr(this.#nr.box,t)):i=cd.#pr([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#y,{bbox:i,root:{"data-main-rotation":t}}),e.updateProperties(this.#or,{bbox:cd.#pr(this.#tr.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#lr&&(t.setAttribute("aria-label",this.#lr),t.setAttribute("role","mark")),this.#ar?t.classList.add("free"):this.div.addEventListener("keydown",this.#vr.bind(this),{signal:this._uiManager._signal});const e=this.#sr=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#Za;const[i,s]=this.parentDimensions;return this.setDims(this.width*i,this.height*s),il(this,this.#sr,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#or,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#or,{rootClass:{hovered:!1}})}#vr(t){cd._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#br(!0);break;case 1:case 3:this.#br(!1)}}#br(t){if(!this.#Ya)return;const e=window.getSelection();t?e.setPosition(this.#Ya,this.#Qa):e.setPosition(this.#er,this.#ir)}select(){super.select(),this.#or&&this.parent?.drawLayer.updateProperties(this.#or,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#or&&(this.parent?.drawLayer.updateProperties(this.#or,{rootClass:{selected:!1}}),this.#ar||this.#br(!1))}get _mustFixPosition(){return!this.#ar}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#y,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#or,{rootClass:{hidden:!t}}))}#_r(){return this.#ar?this.rotation:0}#yr(){if(this.#ar)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#Ja,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:c}of n){const n=o*t+i,d=(1-l)*e+s;a[r]=a[r+4]=n,a[r+1]=a[r+3]=d,a[r+2]=a[r+6]=n+h*t,a[r+5]=a[r+7]=d-c*e,r+=8}return a}#wr(t){return this.#nr.serialize(t,this.#_r())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,c=t.combinedSignal(h),d=e=>{h.abort(),this.#xr(t,e)};window.addEventListener("blur",d,{signal:c}),window.addEventListener("pointerup",d,{signal:c}),window.addEventListener("pointerdown",Go,{capture:!0,passive:!1,signal:c}),window.addEventListener("contextmenu",Wo,{signal:c}),i.addEventListener("pointermove",this.#Ar.bind(this,t),{signal:c}),this._freeHighlight=new od({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#Ar(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#xr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof qc){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:zr.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof Gc){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:zr.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Ro.makeHexColor(...n),l.#rr=o||1,r&&(l.#ua=t.thickness),l.annotationElementId=t.id||null,l._initialData=s;const[h,c]=l.pageDimensions,[d,u]=l.pageTranslation;if(a){const t=l.#Ja=[];for(let e=0;e<a.length;e+=8)t.push({x:(a[e]-d)/h,y:1-(a[e+1]-u)/c,width:(a[e+2]-a[e])/h,height:(a[e+1]-a[e+5])/c});l.#ur(),l.#dr(),l.rotate(l.rotation)}else if(r){l.#ar=!0;const t=r[0],i={x:t[0]-d,y:c-(t[1]-u)},s=new od(i,[0,0,h,c],1,l.#ua/2,!0,.001);for(let e=0,n=t.length;e<n;e+=2)i.x=t[e]-d,i.y=c-(t[e+1]-u),s.add(i);const{id:n,clipPathId:a}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:s.toSVGPath()}},!0,!0);l.#cr({highlightOutlines:s.getOutlines(),highlightId:n,clipPathId:a}),l.#dr(),l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),i=dl._colorManager.convert(this.color),s={annotationType:zr.HIGHLIGHT,color:i,opacity:this.#rr,thickness:this.#ua,quadPoints:this.#yr(),outlines:this.#wr(e),pageIndex:this.pageIndex,rect:e,rotation:this.#_r(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#ta(s)?null:(s.id=this.annotationElementId,s)}#ta(t){const{color:e}=this._initialData;return t.color.some(((t,i)=>t!==e[i]))}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class dd{#kr=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#kr[t]=e}toSVGProperties(){const t=this.#kr;return this.#kr=Object.create(null),{root:t}}reset(){this.#kr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){po("Not implemented")}}class ud extends dl{#Tr=null;#Sr;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#Er=null;static#Cr=null;static#Rr=null;static#Mr=NaN;static#Pr=null;static#Lr=null;static#Dr=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#Sr=t.mustBeCommitted||!1,this._addOutlines(t)}_addOutlines(t){t.drawOutlines&&(this.#Ir(t),this.#dr())}#Ir({drawOutlines:t,drawId:e,drawingOptions:i}){this.#Tr=t,this._drawingOptions||=i,e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#Or(t,this.parent),this.#Nr(t.box)}#Or(t,e){const{id:i}=e.drawLayer.draw(ud._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){po("Not implemented")}static get typesMap(){po("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e),this._currentParent&&(ud.#Er.updateProperty(i,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],a=t=>{s.updateProperty(e,t);const i=this.#Tr.updateProperty(e,t);i&&this.#Nr(i),this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties())};this.addCommands({cmd:a.bind(this,i),undo:a.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,ud._mergeSVGProperties(this.#Tr.getPathResizingSVGProperties(this.#Fr()),{bbox:this.#Br()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,ud._mergeSVGProperties(this.#Tr.getPathResizedSVGProperties(this.#Fr()),{bbox:this.#Br()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Br()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,ud._mergeSVGProperties(this.#Tr.getPathTranslatedSVGProperties(this.#Fr(),this.parentDimensions),{bbox:this.#Br()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#Sr&&(this.#Sr=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#mr(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#dr(),this.#Nr(this.#Tr.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#mr()):t&&(this._uiManager.addShouldRescale(this),this.#dr(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#mr(){null!==this._drawId&&this.parent&&(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#dr(t=this.parent){null!==this._drawId&&this.parent===t||(null===this._drawId?(this._drawingOptions.updateAll(),this._drawId=this.#Or(this.#Tr,t)):this.parent.drawLayer.updateParent(this._drawId,t.drawLayer))}#jr([t,e,i,s]){const{parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/n),s*(n/a)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(a/n),s*(n/a)];default:return[t,e,i,s]}}#Fr(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(n/a),s*(a/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/a),s*(a/n)];default:return[t,e,i,s]}}#Nr(t){if([this.x,this.y,this.width,this.height]=this.#jr(t),this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Br(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*n+a)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(r/o),s*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),s*(o/r)];case 6:return[1-t-s*(o/r),1-e,s*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-s*(o/r),i*(r/o),s*(o/r)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/r),e,s*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-s*(o/r),i*(r/o),s*(o/r)];case 14:return[1-t,1-e-i*(r/o),s*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),s*(o/r)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,ud._mergeSVGProperties({bbox:this.#Br()},this.#Tr.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Nr(this.#Tr.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const i=super.render();i.classList.add("draw");const s=document.createElement("div");i.append(s),s.setAttribute("aria-hidden","true"),s.className="internal";const[n,a]=this.parentDimensions;return this.setDims(this.width*n,this.height*a),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),i}static createDrawerInstance(t,e,i,s,n){po("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=s;if(ud.#Pr&&ud.#Pr!==l)return;const{viewport:{rotation:h}}=t,{width:c,height:d}=n.getBoundingClientRect(),u=ud.#Cr=new AbortController,p=t.combinedSignal(u);ud.#Mr||=o,ud.#Pr??=l,window.addEventListener("pointerup",(t=>{ud.#Mr===t.pointerId?this._endDraw(t):ud.#Lr?.delete(t.pointerId)}),{signal:p}),window.addEventListener("pointercancel",(t=>{ud.#Mr===t.pointerId?this._currentParent.endDrawingSession():ud.#Lr?.delete(t.pointerId)}),{signal:p}),window.addEventListener("pointerdown",(t=>{ud.#Pr===t.pointerType&&((ud.#Lr||=new Set).add(t.pointerId),ud.#Er.isCancellable()&&(ud.#Er.removeLastElement(),ud.#Er.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))}),{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",Wo,{signal:p}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p}),n.addEventListener("touchmove",(t=>{t.timeStamp===ud.#Dr&&Go(t)}),{signal:p}),t.toggleDrawing(),e._editorUndoBar?.hide(),ud.#Er?t.drawLayer.updateProperties(this._currentDrawId,ud.#Er.startNew(a,r,c,d,h)):(e.updateUIForDefaultProperties(this),ud.#Er=this.createDrawerInstance(a,r,c,d,h),ud.#Rr=this.getDefaultDrawingOptions(),this._currentParent=t,({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(ud.#Rr.toSVGProperties(),ud.#Er.defaultSVGProperties),!0,!1)))}static _drawMove(t){if(ud.#Dr=-1,!ud.#Er)return;const{offsetX:e,offsetY:i,pointerId:s}=t;ud.#Mr===s&&(ud.#Lr?.size>=1?this._endDraw(t):(this._currentParent.drawLayer.updateProperties(this._currentDrawId,ud.#Er.add(e,i)),ud.#Dr=t.timeStamp,Go(t)))}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,ud.#Er=null,ud.#Rr=null,ud.#Pr=null,ud.#Dr=NaN),ud.#Cr&&(ud.#Cr.abort(),ud.#Cr=null,ud.#Mr=NaN,ud.#Lr=null)}static _endDraw(t){const e=this._currentParent;if(e)if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,ud.#Er.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const t=ud.#Er,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:Vr.DRAW_STEP})}else this.endDrawing(!1)}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(Vr.DRAW_STEP),!ud.#Er.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:ud.#Er.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:ud.#Rr,mustBeCommitted:!t});return this._cleanup(!0),a}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,a){po("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);return l.createDrawingOptions(t),l.#Ir({drawOutlines:o}),l.#dr(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#Tr.serialize([e,i,s,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class pd{#ra=new Float64Array(6);#Cn;#zr;#as;#ua;#pa;#Vr="";#Ur=0;#Oa=new gd;#Hr;#$r;constructor(t,e,i,s,n,a){this.#Hr=i,this.#$r=s,this.#as=n,this.#ua=a,[t,e]=this.#Wr(t,e);const r=this.#Cn=[NaN,NaN,NaN,NaN,t,e];this.#pa=[t,e],this.#zr=[{line:r,points:this.#pa}],this.#ra.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#ua=e)}#Wr(t,e){return id._normalizePoint(t,e,this.#Hr,this.#$r,this.#as)}isEmpty(){return!this.#zr||0===this.#zr.length}isCancellable(){return this.#pa.length<=10}add(t,e){[t,e]=this.#Wr(t,e);const[i,s,n,a]=this.#ra.subarray(2,6),r=t-n,o=e-a;return Math.hypot(this.#Hr*r,this.#$r*o)<=2?null:(this.#pa.push(t,e),isNaN(i)?(this.#ra.set([n,a,t,e],2),this.#Cn.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#ra[0])&&this.#Cn.splice(6,6),this.#ra.set([i,s,n,a,t,e],0),this.#Cn.push(...id.createBezierPoints(i,s,n,a,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const i=this.add(t,e);return i||(2===this.#pa.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Hr=i,this.#$r=s,this.#as=n,[t,e]=this.#Wr(t,e);const a=this.#Cn=[NaN,NaN,NaN,NaN,t,e];this.#pa=[t,e];const r=this.#zr.at(-1);return r&&(r.line=new Float32Array(r.line),r.points=new Float32Array(r.points)),this.#zr.push({line:a,points:this.#pa}),this.#ra.set(a,0),this.#Ur=0,this.toSVGPath(),null}getLastElement(){return this.#zr.at(-1)}setLastElement(t){return this.#zr?(this.#zr.push(t),this.#Cn=t.line,this.#pa=t.points,this.#Ur=0,{path:{d:this.toSVGPath()}}):this.#Oa.setLastElement(t)}removeLastElement(){if(!this.#zr)return this.#Oa.removeLastElement();this.#zr.pop(),this.#Vr="";for(let t=0,e=this.#zr.length;t<e;t++){const{line:e,points:i}=this.#zr[t];this.#Cn=e,this.#pa=i,this.#Ur=0,this.toSVGPath()}return{path:{d:this.#Vr}}}toSVGPath(){const t=id.svgRound(this.#Cn[4]),e=id.svgRound(this.#Cn[5]);if(2===this.#pa.length)return this.#Vr=`${this.#Vr} M ${t} ${e} Z`,this.#Vr;if(this.#pa.length<=6){const i=this.#Vr.lastIndexOf("M");this.#Vr=`${this.#Vr.slice(0,i)} M ${t} ${e}`,this.#Ur=6}if(4===this.#pa.length){const t=id.svgRound(this.#Cn[10]),e=id.svgRound(this.#Cn[11]);return this.#Vr=`${this.#Vr} L ${t} ${e}`,this.#Ur=12,this.#Vr}const i=[];0===this.#Ur&&(i.push(`M ${t} ${e}`),this.#Ur=6);for(let t=this.#Ur,e=this.#Cn.length;t<e;t+=6){const[e,s,n,a,r,o]=this.#Cn.slice(t,t+6).map(id.svgRound);i.push(`C${e} ${s} ${n} ${a} ${r} ${o}`)}return this.#Vr+=i.join(" "),this.#Ur=this.#Cn.length,this.#Vr}getOutlines(t,e,i,s){const n=this.#zr.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#Oa.build(this.#zr,t,e,i,this.#as,this.#ua,s),this.#ra=null,this.#Cn=null,this.#zr=null,this.#Vr=null,this.#Oa}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class gd extends id{#ka;#Gr=0;#sa;#zr;#Hr;#$r;#qr;#as;#ua;build(t,e,i,s,n,a,r){this.#Hr=e,this.#$r=i,this.#qr=s,this.#as=n,this.#ua=a,this.#sa=r??0,this.#zr=t,this.#Kr()}get thickness(){return this.#ua}setLastElement(t){return this.#zr.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#zr.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#zr)if(t.push(`M${id.svgRound(e[4])} ${id.svgRound(e[5])}`),6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${id.svgRound(e[10])} ${id.svgRound(e[11])}`);else for(let i=6,s=e.length;i<s;i+=6){const[s,n,a,r,o,l]=e.subarray(i,i+6).map(id.svgRound);t.push(`C${s} ${n} ${a} ${r} ${o} ${l}`)}else t.push("Z");return t.join("")}serialize([t,e,i,s],n){const a=[],r=[],[o,l,h,c]=this.#Xr();let d,u,p,g,f,_,m,v,b;switch(this.#as){case 0:b=id._rescale,d=t,u=e+s,p=i,g=-s,f=t+o*i,_=e+(1-l-c)*s,m=t+(o+h)*i,v=e+(1-l)*s;break;case 90:b=id._rescaleAndSwap,d=t,u=e,p=i,g=s,f=t+l*i,_=e+o*s,m=t+(l+c)*i,v=e+(o+h)*s;break;case 180:b=id._rescale,d=t+i,u=e,p=-i,g=s,f=t+(1-o-h)*i,_=e+l*s,m=t+(1-o)*i,v=e+(l+c)*s;break;case 270:b=id._rescaleAndSwap,d=t+i,u=e+s,p=-i,g=-s,f=t+(1-l-c)*i,_=e+(1-o-h)*s,m=t+(1-l)*i,v=e+(1-o)*s}for(const{line:t,points:e}of this.#zr)a.push(b(t,d,u,p,g,n?new Array(t.length):null)),r.push(b(e,d,u,p,g,n?new Array(e.length):null));return{lines:a,points:r,rect:[f,_,m,v]}}static deserialize(t,e,i,s,n,{paths:{lines:a,points:r},rotation:o,thickness:l}){const h=[];let c,d,u,p,g;switch(o){case 0:g=id._rescale,c=-t/i,d=e/s+1,u=1/i,p=-1/s;break;case 90:g=id._rescaleAndSwap,c=-e/s,d=-t/i,u=1/s,p=1/i;break;case 180:g=id._rescale,c=t/i+1,d=-e/s,u=-1/i,p=1/s;break;case 270:g=id._rescaleAndSwap,c=e/s+1,d=t/i+1,u=-1/s,p=-1/i}if(!a){a=[];for(const t of r){const e=t.length;if(2===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const i=new Float32Array(3*(e-2));a.push(i);let[s,n,r,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,s,n],0);for(let a=4;a<e;a+=2){const e=t[a],l=t[a+1];i.set(id.createBezierPoints(s,n,r,o,e,l),3*(a-2)),[s,n,r,o]=[r,o,e,l]}}}for(let t=0,e=a.length;t<e;t++)h.push({line:g(a[t].map((t=>t??NaN)),c,d,u,p),points:g(r[t].map((t=>t??NaN)),c,d,u,p)});const f=new this.prototype.constructor;return f.build(h,i,s,1,o,l,n),f}#Yr(t=this.#ua){const e=this.#sa+t/2*this.#qr;return this.#as%180==0?[e/this.#Hr,e/this.#$r]:[e/this.#$r,e/this.#Hr]}#Xr(){const[t,e,i,s]=this.#ka,[n,a]=this.#Yr(0);return[t+n,e+a,i-2*n,s-2*a]}#Kr(){const t=this.#ka=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#zr){if(e.length<=12){for(let i=4,s=e.length;i<s;i+=6)Ro.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],s=e[5];for(let n=6,a=e.length;n<a;n+=6){const[a,r,o,l,h,c]=e.subarray(n,n+6);Ro.bezierBoundingBox(i,s,a,r,o,l,h,c,t),i=h,s=c}}const[e,i]=this.#Yr();t[0]=Io(t[0]-e,0,1),t[1]=Io(t[1]-i,0,1),t[2]=Io(t[2]+e,0,1),t[3]=Io(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#ka}updateProperty(t,e){return"stroke-width"===t?this.#gr(e):null}#gr(t){const[e,i]=this.#Yr();this.#ua=t;const[s,n]=this.#Yr(),[a,r]=[s-e,n-i],o=this.#ka;return o[0]-=a,o[1]-=r,o[2]+=2*a,o[3]+=2*r,o}updateParentDimensions([t,e],i){const[s,n]=this.#Yr();this.#Hr=t,this.#$r=e,this.#qr=i;const[a,r]=this.#Yr(),o=a-s,l=r-n,h=this.#ka;return h[0]-=o,h[1]-=l,h[2]+=2*o,h[3]+=2*l,h}updateRotation(t){return this.#Gr=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#ka.map(id.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#ka;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#ka;let i=0,s=0,n=0,a=0,r=0,o=0;switch(this.#Gr){case 90:s=e/t,n=-t/e,r=t;break;case 180:i=-1,a=-1,r=t,o=e;break;case 270:s=-e/t,n=t/e,o=e;break;default:return""}return`matrix(${i} ${s} ${n} ${a} ${id.svgRound(r)} ${id.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,s]){const[n,a]=this.#Yr(),[r,o,l,h]=this.#ka;if(Math.abs(l-n)<=id.PRECISION||Math.abs(h-a)<=id.PRECISION){const n=t+i/2-(r+l/2),a=e+s/2-(o+h/2);return{path:{"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`,transform:`${this.rotationTransform} translate(${n} ${a})`}}}const c=(i-2*n)/(l-2*n),d=(s-2*a)/(h-2*a),u=l/i,p=h/s;return{path:{"transform-origin":`${id.svgRound(r)} ${id.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${id.svgRound(n)} ${id.svgRound(a)}) scale(${c} ${d}) translate(${id.svgRound(-n)} ${id.svgRound(-a)})`}}}getPathResizedSVGProperties([t,e,i,s]){const[n,a]=this.#Yr(),r=this.#ka,[o,l,h,c]=r;if(r[0]=t,r[1]=e,r[2]=i,r[3]=s,Math.abs(h-n)<=id.PRECISION||Math.abs(c-a)<=id.PRECISION){const n=t+i/2-(o+h/2),a=e+s/2-(l+c/2);for(const{line:t,points:e}of this.#zr)id._translate(t,n,a,t),id._translate(e,n,a,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(i-2*n)/(h-2*n),u=(s-2*a)/(c-2*a),p=-d*(o+n)+t+n,g=-u*(l+a)+e+a;if(1!==d||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#zr)id._rescale(t,p,g,d,u,t),id._rescale(e,p,g,d,u,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[s,n]=i,a=this.#ka,r=t-a[0],o=e-a[1];if(this.#Hr===s&&this.#$r===n)for(const{line:t,points:e}of this.#zr)id._translate(t,r,o,t),id._translate(e,r,o,e);else{const t=this.#Hr/s,e=this.#$r/n;this.#Hr=s,this.#$r=n;for(const{line:i,points:s}of this.#zr)id._rescale(i,r,o,t,e,i),id._rescale(s,r,o,t,e,s);a[2]*=t,a[3]*=e}return a[0]=t,a[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${id.svgRound(t)} ${id.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#ka;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${id.svgRound(t[0])} ${id.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class fd extends dd{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:dl._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){"stroke-width"===t&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new fd(this._viewParameters);return t.updateAll(this),t}}class _d extends ud{static _type="ink";static _editorType=zr.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){dl.initialize(t,e),this._defaultDrawingOptions=new fd(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return mo(this,"typesMap",new Map([[Vr.INK_THICKNESS,"stroke-width"],[Vr.INK_COLOR,"stroke"],[Vr.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,s,n){return new pd(t,e,i,s,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,s,n,a){return gd.deserialize(t,e,i,s,n,a)}static async deserialize(t,e,i){let s=null;if(t instanceof Gc){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,opacity:o,borderStyle:{rawWidth:l},popupRef:h},parent:{page:{pageNumber:c}}}=t;s=t={annotationType:zr.INK,color:Array.from(r),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:c-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:h}}const n=await super.deserialize(t,e,i);return n.annotationElementId=t.id||null,n._initialData=s,n}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:i}){this._drawingOptions=_d.getDefaultDrawingOptions({stroke:Ro.makeHexColor(...t),"stroke-width":e,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:i,rect:s}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":a,"stroke-width":r}}=this,o={annotationType:zr.INK,color:dl._colorManager.convert(n),opacity:a,thickness:r,paths:{lines:e,points:i},pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?(o.isCopy=!0,o):this.annotationElementId&&!this.#ta(o)?null:(o.id=this.annotationElementId,o)}#ta(t){const{color:e,thickness:i,opacity:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some(((t,i)=>t!==e[i]))||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);return t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e}),null}}class md extends gd{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}class vd{static#Qr={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#Jr(t,e,i,s){return s-=e,0===(i-=t)?s>0?0:4:1===i?s+6:2-s}static#Zr=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#to(t,e,i,s,n,a,r){const o=this.#Jr(i,s,n,a);for(let n=0;n<8;n++){const a=(-n+o-r+16)%8;if(0!==t[(i+this.#Zr[2*a])*e+(s+this.#Zr[2*a+1])])return a}return-1}static#eo(t,e,i,s,n,a,r){const o=this.#Jr(i,s,n,a);for(let n=0;n<8;n++){const a=(n+o+r+16)%8;if(0!==t[(i+this.#Zr[2*a])*e+(s+this.#Zr[2*a+1])])return a}return-1}static#io(t,e,i,s){const n=t.length,a=new Int32Array(n);for(let e=0;e<n;e++)a[e]=t[e]<=s?1:0;for(let t=1;t<i-1;t++)a[t*e]=a[t*e+e-1]=0;for(let t=0;t<e;t++)a[t]=a[e*i-1-t]=0;let r,o=1;const l=[];for(let t=1;t<i-1;t++){r=1;for(let i=1;i<e-1;i++){const s=t*e+i,n=a[s];if(0===n)continue;let h=t,c=i;if(1===n&&0===a[s-1])o+=1,c-=1;else{if(!(n>=1&&0===a[s+1])){1!==n&&(r=Math.abs(n));continue}o+=1,c+=1,n>1&&(r=n)}const d=[i,t],u=c===i+1,p={isHole:u,points:d,id:o,parent:0};let g;l.push(p);for(const t of l)if(t.id===r){g=t;break}g?g.isHole?p.parent=u?g.parent:r:p.parent=u?r:g.parent:p.parent=u?r:0;const f=this.#to(a,e,t,i,h,c,0);if(-1===f){a[s]=-o,1!==a[s]&&(r=Math.abs(a[s]));continue}let _=this.#Zr[2*f],m=this.#Zr[2*f+1];const v=t+_,b=i+m;h=v,c=b;let y=t,w=i;for(;;){const n=this.#eo(a,e,y,w,h,c,1);_=this.#Zr[2*n],m=this.#Zr[2*n+1];const l=y+_,u=w+m;d.push(u,l);const p=y*e+w;if(0===a[p+1]?a[p]=-o:1===a[p]&&(a[p]=o),l===t&&u===i&&y===v&&w===b){1!==a[s]&&(r=Math.abs(a[s]));break}h=y,c=w,y=l,w=u}}}return l}static#so(t,e,i,s){if(i-e<=4){for(let n=e;n<i-2;n+=2)s.push(t[n],t[n+1]);return}const n=t[e],a=t[e+1],r=t[i-4]-n,o=t[i-3]-a,l=Math.hypot(r,o),h=r/l,c=o/l,d=h*a-c*n,u=o/r,p=1/l,g=Math.atan(u),f=Math.cos(g),_=Math.sin(g),m=p*(Math.abs(f)+Math.abs(_)),v=p*(1-m+m**2),b=Math.max(Math.atan(Math.abs(_+f)*v),Math.atan(Math.abs(_-f)*v));let y=0,w=e;for(let s=e+2;s<i-2;s+=2){const e=Math.abs(d-h*t[s+1]+c*t[s]);e>y&&(w=s,y=e)}y>(l*b)**2?(this.#so(t,e,w+2,s),this.#so(t,w,i,s)):s.push(n,a)}static#no(t){const e=[],i=t.length;return this.#so(t,0,i,e),e.push(t[i-2],t[i-1]),e.length<=4?null:e}static#ao(t,e,i,s,n,a){const r=new Float32Array(a**2),o=-2*s**2,l=a>>1;for(let t=0;t<a;t++){const e=(t-l)**2;for(let i=0;i<a;i++)r[t*a+i]=Math.exp((e+(i-l)**2)/o)}const h=new Float32Array(256),c=-2*n**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/c);const d=t.length,u=new Uint8Array(d),p=new Uint32Array(256);for(let s=0;s<i;s++)for(let n=0;n<e;n++){const o=s*e+n,c=t[o];let d=0,g=0;for(let o=0;o<a;o++){const u=s+o-l;if(!(u<0||u>=i))for(let i=0;i<a;i++){const s=n+i-l;if(s<0||s>=e)continue;const p=t[u*e+s],f=r[o*a+i]*h[Math.abs(p-c)];d+=p*f,g+=f}}p[u[o]=Math.round(d/g)]++}return[u,p]}static#ro(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#oo(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let s=-1/0,n=1/0;for(let e=0,a=i.length;e<a;e++){if(0===t[3+(e<<2)]){s=i[e]=255;continue}const a=i[e]=t[e<<2];a>s&&(s=a),a<n&&(n=a)}const a=255/(s-n);for(let t=0;t<e;t++)i[t]=(i[t]-n)*a;return i}static#lo(t){let e,i=-1/0,s=-1/0;const n=t.findIndex((t=>0!==t));let a=n,r=n;for(e=n;e<256;e++){const n=t[e];n>i&&(e-a>s&&(s=e-a,r=e-1),i=n,a=e)}for(e=r-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#ho(t){const e=t,{width:i,height:s}=t,{maxDim:n}=this.#Qr;let a=i,r=s;if(i>n||s>n){let o=i,l=s,h=Math.log2(Math.max(i,s)/n);const c=Math.floor(h);h=h===c?c-1:c;for(let i=0;i<h;i++){a=Math.ceil(o/2),r=Math.ceil(l/2);const i=new OffscreenCanvas(a,r);i.getContext("2d").drawImage(t,0,0,o,l,0,0,a,r),o=a,l=r,t!==e&&t.close(),t=i.transferToImageBitmap()}const d=Math.min(n/a,n/r);a=Math.round(a*d),r=Math.round(r*d)}const o=new OffscreenCanvas(a,r).getContext("2d",{willReadFrequently:!0});o.filter="grayscale(1)",o.drawImage(t,0,0,t.width,t.height,0,0,a,r);const l=o.getImageData(0,0,a,r).data;return[this.#oo(l),a,r]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:s},n,a,r,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1});const c=h.font=`${i} ${s} 200px ${e}`,{actualBoundingBoxLeft:d,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:f,fontBoundingBoxDescent:_,width:m}=h.measureText(t),v=1.5,b=Math.ceil(Math.max(Math.abs(d)+Math.abs(u)||0,m)*v),y=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(f)+Math.abs(_)||200)*v);l=new OffscreenCanvas(b,y),h=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),h.font=c,h.filter="grayscale(1)",h.fillStyle="white",h.fillRect(0,0,b,y),h.fillStyle="black",h.fillText(t,.5*b/2,1.5*y/2);const w=this.#oo(h.getImageData(0,0,b,y).data),x=this.#ro(w),A=this.#lo(x),k=this.#io(w,b,y,A);return this.processDrawnLines({lines:{curves:k,width:b,height:y},pageWidth:n,pageHeight:a,rotation:r,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,s,n){const[a,r,o]=this.#ho(t),[l,h]=this.#ao(a,r,o,Math.hypot(r,o)*this.#Qr.sigmaSFactor,this.#Qr.sigmaR,this.#Qr.kernelSize),c=this.#lo(h),d=this.#io(l,r,o,c);return this.processDrawnLines({lines:{curves:d,width:r,height:o},pageWidth:e,pageHeight:i,rotation:s,innerMargin:n,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:s,innerMargin:n,mustSmooth:a,areContours:r}){s%180!=0&&([e,i]=[i,e]);const{curves:o,width:l,height:h}=t,c=t.thickness??0,d=[],u=Math.min(e/l,i/h),p=u/e,g=u/i,f=[];for(const{points:t}of o){const e=a?this.#no(t):t;if(!e)continue;f.push(e);const i=e.length,s=new Float32Array(i),n=new Float32Array(3*(2===i?2:i-2));if(d.push({line:n,points:s}),2===i){s[0]=e[0]*p,s[1]=e[1]*g,n.set([NaN,NaN,NaN,NaN,s[0],s[1]],0);continue}let[r,o,l,h]=e;r*=p,o*=g,l*=p,h*=g,s.set([r,o,l,h],0),n.set([NaN,NaN,NaN,NaN,r,o],0);for(let t=4;t<i;t+=2){const i=s[t]=e[t]*p,a=s[t+1]=e[t+1]*g;n.set(id.createBezierPoints(r,o,l,h,i,a),3*(t-2)),[r,o,l,h]=[l,h,i,a]}}if(0===d.length)return null;const _=r?new md:new gd;return _.build(d,e,i,1,s,r?0:c,n),{outline:_,newCurves:f,areContours:r,thickness:c,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:s,height:n}){let a,r=1/0,o=-1/0,l=0;for(const e of t){l+=e.length;for(let t=2,i=e.length;t<i;t++){const i=e[t]-e[t-2];r=Math.min(r,i),o=Math.max(o,i)}}a=r>=-128&&o<=127?Int8Array:r>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,c=8+3*h,d=new Uint32Array(c);let u=0;d[u++]=c*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*a.BYTES_PER_ELEMENT,d[u++]=0,d[u++]=s,d[u++]=n,d[u++]=e?0:1,d[u++]=Math.max(0,Math.floor(i??0)),d[u++]=h,d[u++]=a.BYTES_PER_ELEMENT;for(const e of t)d[u++]=e.length-2,d[u++]=e[0],d[u++]=e[1];const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(d);const f=a.prototype.constructor;for(const e of t){const t=new f(e.length-2);for(let i=2,s=e.length;i<s;i++)t[i-2]=e[i]-e[i-2];g.write(t)}g.close();const _=await new Response(p.readable).arrayBuffer();return Oo(new Uint8Array(_))}static async decompressSignature(t){try{const i=(e=t,Uint8Array.fromBase64?Uint8Array.fromBase64(e):So(atob(e))),{readable:s,writable:n}=new DecompressionStream("deflate-raw"),a=n.getWriter();await a.ready,a.write(i).then((async()=>{await a.ready,await a.close()})).catch((()=>{}));let r=null,o=0;for await(const t of s)r||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),r.set(t,o),o+=t.length;const l=new Uint32Array(r.buffer,0,r.length>>2),h=l[1];if(0!==h)throw new Error(`Invalid version: ${h}`);const c=l[2],d=l[3],u=0===l[4],p=l[5],g=l[6],f=l[7],_=[],m=(8+3*g)*Uint32Array.BYTES_PER_ELEMENT;let v;switch(f){case Int8Array.BYTES_PER_ELEMENT:v=new Int8Array(r.buffer,m);break;case Int16Array.BYTES_PER_ELEMENT:v=new Int16Array(r.buffer,m);break;case Int32Array.BYTES_PER_ELEMENT:v=new Int32Array(r.buffer,m)}o=0;for(let t=0;t<g;t++){const e=l[3*t+8],i=new Float32Array(e+2);_.push(i);for(let e=0;e<2;e++)i[e]=l[3*t+8+e+1];for(let t=0;t<e;t++)i[t+2]=i[t]+v[o++]}return{areContours:u,thickness:p,outlines:_,width:c,height:d}}catch(t){return uo(`decompressSignature: ${t}`),null}var e}}class bd extends dd{constructor(){super(),super.updateProperties({fill:dl._defaultLineColor,"stroke-width":0})}clone(){const t=new bd;return t.updateAll(this),t}}class yd extends fd{constructor(t){super(t),super.updateProperties({stroke:dl._defaultLineColor,"stroke-width":1})}clone(){const t=new yd(this._viewParameters);return t.updateAll(this),t}}class wd extends ud{#co=!1;#do=null;#uo=null;#po=null;static _type="signature";static _editorType=zr.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#uo=t.signatureData||null,this.#do=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){dl.initialize(t,e),this._defaultDrawingOptions=new bd,this._defaultDrawnSignatureOptions=new yd(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return mo(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#do}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:i}=this;if(i&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),null===this._drawId)if(this.#uo){const{lines:t,mustSmooth:e,areContours:i,description:s,uuid:n,heightInPage:a}=this.#uo,{rawDims:{pageWidth:r,pageHeight:o},rotation:l}=this.parent.viewport,h=vd.processDrawnLines({lines:t,pageWidth:r,pageHeight:o,rotation:l,innerMargin:wd._INNER_MARGIN,mustSmooth:e,areContours:i});this.addSignature(h,a,s,n)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);return i&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#po=t,this.addEditToolbar()}getUuid(){return this.#po}get description(){return this.#do}set description(t){this.#do=t,super.addEditToolbar().then((e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:i,width:s,height:n}=this.#uo,a=Math.max(s,n);return{areContours:e,outline:vd.processDrawnLines({lines:{curves:t.map((t=>({points:t}))),thickness:i,width:s,height:n},pageWidth:a,pageHeight:a,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.signatureManager&&null!==this.#do&&(await t.addEditSignatureButton(this._uiManager.signatureManager,this.#po,this.#do),t.show()),t):null}addSignature(t,e,i,s){const{x:n,y:a}=this,{outline:r}=this.#uo=t;let o;this.#co=r instanceof md,this.#do=i,this.div.setAttribute("data-l10n-args",JSON.stringify({description:i})),this.#co?o=wd.getDefaultDrawingOptions():(o=wd._defaultDrawnSignatureOptions.clone(),o.updateProperties({"stroke-width":r.thickness})),this._addOutlines({drawOutlines:r,drawingOptions:o});const[l,h]=this.parentDimensions,[,c]=this.pageDimensions;let d=e/c;d=d>=1?.5:d,this.width*=d/this.height,this.width>=1&&(d*=.9/this.width,this.width=.9),this.height=d,this.setDims(l*this.width,h*this.height),this.x=n,this.y=a,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(s),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!s,hasDescription:!!i}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:s}=this.parent.viewport;return vd.process(t,e,i,s,wd._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:s},rotation:n}=this.parent.viewport;return vd.extractContoursFromText(t,e,i,s,n,wd._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:s}=this.parent.viewport;return vd.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:s,innerMargin:wd._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=wd.getDefaultDrawingOptions():(this._drawingOptions=wd._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:i,rect:s}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":n}}=this,a={annotationType:zr.SIGNATURE,isSignature:!0,areContours:this.#co,color:[0,0,0],thickness:this.#co?0:n,pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?(a.paths={lines:e,points:i},a.uuid=this.#po,a.isCopy=!0):a.lines=e,this.#do&&(a.accessibilityData={type:"Figure",alt:this.#do}),a}static deserializeDraw(t,e,i,s,n,a){return a.areContours?md.deserialize(t,e,i,s,n,a):gd.deserialize(t,e,i,s,n,a)}static async deserialize(t,e,i){const s=await super.deserialize(t,e,i);return s.#co=t.areContours,s.#do=t.accessibilityData?.alt||"",s.#po=t.uuid,s}}class xd extends dl{#go=null;#fo=null;#_o=null;#mo=null;#vo=null;#bo="";#yo=null;#wo=!1;#xo=null;#Ao=!1;#ko=!1;static _type="stamp";static _editorType=zr.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#mo=t.bitmapUrl,this.#vo=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){dl.initialize(t,e)}static isHandlingMimeForPasting(t){return Zo.includes(t)}static paste(t,e){e.pasteEditor({mode:zr.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#To(t,e=!1){t?(this.#go=t.bitmap,e||(this.#fo=t.id,this.#Ao=t.isSvg),t.file&&(this.#bo=t.file.name),this.#So()):this.remove()}#Eo(){if(this.#_o=null,this._uiManager.enableWaiting(!1),this.#yo){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#go)return this._editToolbar.hide(),void this._uiManager.editAltText(this,!0);if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#go){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#Co(){if(this.#fo)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#fo).then((t=>this.#To(t,!0))).finally((()=>this.#Eo()));if(this.#mo){const t=this.#mo;return this.#mo=null,this._uiManager.enableWaiting(!0),void(this.#_o=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#To(t))).finally((()=>this.#Eo())))}if(this.#vo){const t=this.#vo;return this.#vo=null,this._uiManager.enableWaiting(!0),void(this.#_o=this._uiManager.imageManager.getFromFile(t).then((t=>this.#To(t))).finally((()=>this.#Eo())))}const t=document.createElement("input");t.type="file",t.accept=Zo.join(",");const e=this._uiManager._signal;this.#_o=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#To(e)}else this.remove();i()}),{signal:e}),t.addEventListener("cancel",(()=>{this.remove(),i()}),{signal:e})})).finally((()=>this.#Eo())),t.click()}remove(){this.#fo&&(this.#go=null,this._uiManager.imageManager.deleteId(this.#fo),this.#yo?.remove(),this.#yo=null,this.#xo&&(clearTimeout(this.#xo),this.#xo=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#fo&&null===this.#yo&&this.#Co(),this.isAttachedToDOM||this.parent.add(this))):this.#fo&&this.#Co()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#_o||this.#go||this.#mo||this.#vo||this.#fo||this.#wo)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#wo||(this.#go?this.#So():this.#Co()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:i,bitmap:s}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(this.#fo=i,s&&(this.#go=s),this.#wo=!1,this.#So())}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#xo&&clearTimeout(this.#xo);this.#xo=setTimeout((()=>{this.#xo=null,this.#Ro()}),200)}#So(){const{div:t}=this;let{width:e,height:i}=this.#go;const[s,n]=this.pageDimensions,a=.75;if(this.width)e=this.width*s,i=this.height*n;else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t,i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n),this._uiManager.enableWaiting(!1);const l=this.#yo=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this.width=e/s,this.height=i/n,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Ro(),this.#ko||(this.parent.addUndoableEditor(this),this.#ko=!0),this._reportTelemetry({action:"inserted_image"}),this.#bo&&this.div.setAttribute("aria-description",this.#bo)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#go,a=new Jo;let r=this.#go,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t),l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Ao||(r=this.#Mo(t,i));const c=h.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(d="#8f8f9d",u="#42414d");const p=15,g=p*a.sx,f=p*a.sy,_=new OffscreenCanvas(2*g,2*f),m=_.getContext("2d");m.fillStyle=d,m.fillRect(0,0,2*g,2*f),m.fillStyle=u,m.fillRect(0,0,g,f),m.fillRect(g,f,g,f),c.fillStyle=c.createPattern(_,"repeat"),c.fillRect(0,0,t,i),c.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let c=null;if(i){let e,i;if(a.symmetric&&r.width<t&&r.height<t)e=r.width,i=r.height;else if(r=this.#go,s>t||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a),i=Math.floor(n*a),this.#Ao||(r=this.#Mo(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i),c={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:c}}#Mo(t,e){const{width:i,height:s}=this.#go;let n=i,a=s,r=this.#go;for(;n>2*t||a>2*e;){const i=n,s=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,i,s,0,0,n,a),r=o.transferToImageBitmap()}return r}#Ro(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new Jo,a=Math.ceil(i*t*n.sx),r=Math.ceil(s*e*n.sy),o=this.#yo;if(!o||o.width===a&&o.height===r)return;o.width=a,o.height=r;const l=this.#Ao?this.#go:this.#Mo(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter,h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}#Po(t){if(t){if(this.#Ao){const t=this._uiManager.imageManager.getSvgUrl(this.#fo);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#go);return t.getContext("2d").drawImage(this.#go,0,0),t.toDataURL()}if(this.#Ao){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*Fo.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*Fo.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);return n.getContext("2d").drawImage(this.#go,0,0,this.#go.width,this.#go.height,0,0,i,s),n.transferToImageBitmap()}return structuredClone(this.#go)}static async deserialize(t,e,i){let s=null,n=!1;if(t instanceof Qc){const{data:{rect:a,rotation:r,id:o,structParent:l,popupRef:h},container:c,parent:{page:{pageNumber:d}},canvas:u}=t;let p,g;u?(delete t.canvas,({id:p,bitmap:g}=i.imageManager.getFromCanvas(c.id,u)),u.remove()):(n=!0,t._hasNoCanvas=!0);const f=(await e._structTree.getAriaAttributes(`${Do}${o}`))?.get("aria-label")||"";s=t={annotationType:zr.STAMP,bitmapId:p,bitmap:g,pageIndex:d-1,rect:a.slice(0),rotation:r,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:f},isSvg:!1,structParent:l,popupRef:h}}const a=await super.deserialize(t,e,i),{rect:r,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:c,accessibilityData:d}=t;n?(i.addMissingCanvas(t.id,a),a.#wo=!0):h&&i.imageManager.isValidId(h)?(a.#fo=h,o&&(a.#go=o)):a.#mo=l,a.#Ao=c;const[u,p]=a.pageDimensions;return a.width=(r[2]-r[0])/u,a.height=(r[3]-r[1])/p,a.annotationElementId=t.id||null,d&&(a.altTextData=d),a._initialData=s,a.#ko=!!s,a}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:zr.STAMP,bitmapId:this.#fo,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Ao,structTreeParentId:this._structTreeParentId};if(t)return i.bitmapUrl=this.#Po(!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;const{decorative:s,altText:n}=this.serializeAltText(!1);if(!s&&n&&(i.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#ta(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,null===e)return i;e.stamps||=new Map;const a=this.#Ao?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#fo)){if(this.#Ao){const t=e.stamps.get(this.#fo);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#Po(!1))}}else e.stamps.set(this.#fo,{area:a,serialized:i}),i.bitmap=this.#Po(!1);return i}#ta(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class Ad{#Fn;#Lo=!1;#Do=null;#Io=null;#Oo=null;#No=new Map;#Fo=!1;#Bo=!1;#jo=!1;#zo=null;#Vo=null;#Uo=null;#Ho=null;#_;static _initialized=!1;static#U=new Map([ed,_d,xd,cd,wd].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const c=[...Ad.#U.values()];if(!Ad._initialized){Ad._initialized=!0;for(const e of c)e.initialize(h,t)}t.registerEditorTypes(c),this.#_=t,this.pageIndex=e,this.div=i,this.#Fn=n,this.#Do=a,this.viewport=l,this.#Uo=o,this.drawLayer=r,this._structTree=s,this.#_.addLayer(this)}get isEmpty(){return 0===this.#No.size}get isInvisible(){return this.isEmpty&&this.#_.getMode()===zr.NONE}updateToolbar(t){this.#_.updateToolbar(t)}updateMode(t=this.#_.getMode()){switch(this.#$o(),t){case zr.NONE:return this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case zr.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case zr.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 i of Ad.#U.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#Uo?.div}setEditingState(t){this.#_.setEditingState(t)}addCommands(t){this.#_.addCommands(t)}cleanUndoStack(t){this.#_.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Do?.div.classList.toggle("disabled",!t)}async enable(){this.#jo=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const e of this.#No.values())e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#_.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));if(!this.#Do)return void(this.#jo=!1);const e=this.#Do.getEditableAnnotations();for(const i of e){if(i.hide(),this.#_.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}this.#jo=!1}disable(){this.#Bo=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#No.values())i.disableEditing(),i.annotationElementId&&(null===i.serialize()?(e.set(i.annotationElementId,i),this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()):t.set(i.annotationElementId,i));if(this.#Do){const i=this.#Do.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#_.isDeletedAnnotationElement(i))continue;let n=e.get(i);n?(n.resetAnnotationElement(s),n.show(!1),s.show()):(n=t.get(i),n&&(this.#_.addChangedExistingAnnotation(n),n.renderAnnotationElement(s)&&n.show(!1)),s.show())}}this.#$o(),this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of Ad.#U.values())i.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#Bo=!1}getEditableAnnotation(t){return this.#Do?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#_.getActive()!==t&&this.#_.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#Uo?.div&&!this.#Ho){this.#Ho=new AbortController;const t=this.#_.combinedSignal(this.#Ho);this.#Uo.div.addEventListener("pointerdown",this.#Wo.bind(this),{signal:t}),this.#Uo.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#Uo?.div&&this.#Ho&&(this.#Ho.abort(),this.#Ho=null,this.#Uo.div.classList.remove("highlighting"))}#Wo(t){this.#_.unselectAll();const{target:e}=t;if(e===this.#Uo.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Uo.div.contains(e)){const{isMac:e}=Eo.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#_.showAllEditors("highlight",!0,!0),this.#Uo.div.classList.add("free"),this.toggleDrawing(),cd.startHighlighting(this,"ltr"===this.#_.direction,{target:this.#Uo.div,x:t.x,y:t.y}),this.#Uo.div.addEventListener("pointerup",(()=>{this.#Uo.div.classList.remove("free"),this.toggleDrawing(!0)}),{once:!0,signal:this.#_._signal}),t.preventDefault()}}enableClick(){if(this.#Io)return;this.#Io=new AbortController;const t=this.#_.combinedSignal(this.#Io);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#Io?.abort(),this.#Io=null}attach(t){this.#No.set(t.id,t);const{annotationElementId:e}=t;e&&this.#_.isDeletedAnnotationElement(e)&&this.#_.removeDeletedAnnotationElement(t)}detach(t){this.#No.delete(t.id),this.#Fn?.removePointerInTextLayer(t.contentDiv),!this.#Bo&&t.annotationElementId&&this.#_.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#_.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#_.addDeletedAnnotationElement(t.annotationElementId),dl.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.#_.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#jo),this.#_.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#Oo&&(t._focusEventsAllowed=!1,this.#Oo=setTimeout((()=>{this.#Oo=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#_._signal}),e.focus())}),0)),t._structTreeParentId=this.#Fn?.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.#_.getId()}get#Go(){return Ad.#U.get(this.#_.getMode())}combinedSignal(t){return this.#_.combinedSignal(t)}#qo(t){const e=this.#Go;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Go?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t),await this.#_.updateMode(t.mode);const{offsetX:i,offsetY:s}=this.#Ko(),n=this.getNextId(),a=this.#qo({parent:this,id:n,x:i,y:s,uiManager:this.#_,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(Ad.#U.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#_))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#qo({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#_,isCentered:e,...i});return n&&this.add(n),n}#Ko(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#Ko(),!0,t)}setSelected(t){this.#_.setSelected(t)}toggleSelected(t){this.#_.toggleSelected(t)}unselect(t){this.#_.unselect(t)}pointerup(t){const{isMac:e}=Eo.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#Fo)return;if(this.#Fo=!1,this.#Go?.isDrawer&&this.#Go.supportMultipleDrawings)return;if(!this.#Lo)return void(this.#Lo=!0);const i=this.#_.getMode();i!==zr.STAMP&&i!==zr.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#_.unselectAll()}pointerdown(t){if(this.#_.getMode()===zr.HIGHLIGHT&&this.enableTextSelection(),this.#Fo)return void(this.#Fo=!1);const{isMac:e}=Eo.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(this.#Fo=!0,this.#Go?.isDrawer)return void this.startDrawingSession(t);const i=this.#_.getActive();this.#Lo=!i||i.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#zo)return void this.#Go.startDrawing(this,this.#_,!1,t);this.#_.setCurrentDrawingSession(this),this.#zo=new AbortController;const e=this.#_.combinedSignal(this.#zo);this.div.addEventListener("blur",(({relatedTarget:t})=>{t&&!this.div.contains(t)&&(this.#Vo=null,this.commitOrRemove())}),{signal:e}),this.#Go.startDrawing(this,this.#_,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#Vo=t)}else this.#Vo&&setTimeout((()=>{this.#Vo?.focus(),this.#Vo=null}),0)}endDrawingSession(t=!1){return this.#zo?(this.#_.setCurrentDrawingSession(null),this.#zo.abort(),this.#zo=null,this.#Vo=null,this.#Go.endDrawing(t)):null}findNewParent(t,e,i){const s=this.#_.findParent(e,i);return null!==s&&s!==this&&(s.changeParent(t),!0)}commitOrRemove(){return!!this.#zo&&(this.endDrawingSession(),!0)}onScaleChanging(){this.#zo&&this.#Go.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#_.getActive()?.parent===this&&(this.#_.commitOrRemove(),this.#_.setActiveEditor(null)),this.#Oo&&(clearTimeout(this.#Oo),this.#Oo=null);for(const t of this.#No.values())this.#Fn?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#No.clear(),this.#_.removeLayer(this)}#$o(){for(const t of this.#No.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,Qo(this.div,t);for(const t of this.#_.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#_.commitOrRemove(),this.#$o();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,Qo(this.div,{rotation:i}),e!==i)for(const t of this.#No.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#_.viewParameters.realScale}}class kd{#fn=null;#Xo=new Map;#Yo=new Map;static#y=0;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#fn){if(this.#fn!==t){if(this.#Xo.size>0)for(const e of this.#Xo.values())e.remove(),t.append(e);this.#fn=t}}else this.#fn=t}static get _svgFactory(){return mo(this,"_svgFactory",new xc)}static#Qo(t,[e,i,s,n]){const{style:a}=t;a.top=100*i+"%",a.left=100*e+"%",a.width=100*s+"%",a.height=100*n+"%"}#Jo(){const t=kd._svgFactory.create(1,1,!0);return this.#fn.append(t),t.setAttribute("aria-hidden",!0),t}#Zo(t,e){const i=kd._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s),i.setAttribute("clipPathUnits","objectBoundingBox");const n=kd._svgFactory.createElement("use");return i.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),s}#tl(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=kd.#y++,n=this.#Jo(),a=kd._svgFactory.createElement("defs");n.append(a);const r=kd._svgFactory.createElement("path");a.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#Yo.set(s,r);const l=i?this.#Zo(a,o):null,h=kd._svgFactory.createElement("use");return n.append(h),h.setAttribute("href",`#${o}`),this.updateProperties(n,t),this.#Xo.set(s,n),{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=kd.#y++,s=this.#Jo(),n=kd._svgFactory.createElement("defs");s.append(n);const a=kd._svgFactory.createElement("path");n.append(a);const r=`path_p${this.pageIndex}_${i}`;let o;if(a.setAttribute("id",r),a.setAttribute("vector-effect","non-scaling-stroke"),e){const t=kd._svgFactory.createElement("mask");n.append(t),o=`mask_p${this.pageIndex}_${i}`,t.setAttribute("id",o),t.setAttribute("maskUnits","objectBoundingBox");const e=kd._svgFactory.createElement("rect");t.append(e),e.setAttribute("width","1"),e.setAttribute("height","1"),e.setAttribute("fill","white");const s=kd._svgFactory.createElement("use");t.append(s),s.setAttribute("href",`#${r}`),s.setAttribute("stroke","none"),s.setAttribute("fill","black"),s.setAttribute("fill-rule","nonzero"),s.classList.add("mask")}const l=kd._svgFactory.createElement("use");s.append(l),l.setAttribute("href",`#${r}`),o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();return s.append(h),l.classList.add("mainOutline"),h.classList.add("secondaryOutline"),this.updateProperties(s,t),this.#Xo.set(i,s),i}finalizeDraw(t,e){this.#Yo.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:a}=e,r="number"==typeof t?this.#Xo.get(t):t;if(r){if(i&&this.#tl(r,i),s&&kd.#Qo(r,s),n){const{classList:t}=r;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(a){const t=r.firstChild.firstChild;this.#tl(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#Xo.get(t);i&&(e.#fn.append(i),this.#Xo.delete(t),e.#Xo.set(t,i))}remove(t){this.#Yo.delete(t),null!==this.#fn&&(this.#Xo.get(t).remove(),this.#Xo.delete(t))}destroy(){this.#fn=null;for(const t of this.#Xo.values())t.remove();this.#Xo.clear(),this.#Yo.clear()}}globalThis._pdfjsTestingUtils={HighlightOutliner:ad},globalThis.pdfjsLib={AbortException:ko,AnnotationEditorLayer:Ad,AnnotationEditorParamsType:Vr,AnnotationEditorType:zr,AnnotationEditorUIManager:ll,AnnotationLayer:Zc,AnnotationMode:jr,AnnotationType:Xr,build:"47ad820d9",ColorPicker:hd,createValidAbsoluteUrl:fo,DOMSVGFactory:xc,DrawLayer:kd,FeatureTest:Eo,fetchData:Bo,getDocument:hc,getFilenameFromUrl:function(t){return[t]=t.split(/[#?]/,1),t.substring(t.lastIndexOf("/")+1)},getPdfFilenameFromUrl:function(t,e="document.pdf"){if("string"!=typeof t)return e;if(Vo(t))return uo('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;const i=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,s=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(t);let n=i.exec(s[1])||i.exec(s[2])||i.exec(s[3]);if(n&&(n=n[0],n.includes("%")))try{n=i.exec(decodeURIComponent(n))[0]}catch{}return n||e},getUuid:Lo,getXfaPageViewport:function(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new jo({viewBox:a,userUnit:1,scale:e,rotation:i})},GlobalWorkerOptions:Lh,ImageKind:Kr,InvalidPDFException:wo,isDataScheme:Vo,isPdfFile:Uo,isValidExplicitDest:kl,MathClamp:Io,noContextMenu:Wo,normalizeUnicode:function(t){return Mo||(Mo=/([\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,Po=new Map([["ſt","ſt"]])),t.replaceAll(Mo,((t,e,i)=>e?e.normalize("NFKC"):Po.get(i)))},OPS:io,OutputScale:Jo,PasswordResponses:{NEED_PASSWORD:1,INCORRECT_PASSWORD:2},PDFDataRangeTransport:dc,PDFDateString:qo,PDFWorker:gc,PermissionFlag:{PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},PixelsPerInch:Fo,RenderingCancelledException:zo,ResponseException:xo,setLayerDimensions:Qo,shadow:mo,SignatureExtractor:vd,stopEvent:Go,SupportedImageMimeTypes:Zo,TextLayer:oc,TouchManager:cl,updateUrlHash:_o,Util:Ro,VerbosityLevel:eo,version:"5.3.31",XfaLayer:Ac};const Td={key:0,class:"loading-screen"},Sd={key:1,class:"image-display-area"},Ed={class:"ocr-container",ref:"containerRef"},Cd=["src"],Rd=["onClick","onMouseover"];var Md=v({__name:"renderOCRResponse",props:{image:{type:null,required:!0},language:{type:String,required:!0}},emits:["close","loadingUpdate"],setup(t,{emit:i}){const s=t;Lh.workerSrc="/tta/pdf.worker.mjs";const{useNotificationsStore:n}=e(),a=n(),h=u(null),g=u([]),f=u(),_=u(),v=u([]),w=u(""),A=u(!1),k=u([]),T=u(1),R=b((()=>v.value.sort().map((t=>{var e;return null==(e=g.value[t])?void 0:e.text})).join(" ")));async function P(t,e,n){if(_.value=t,n)return w.value=n,L(),n;console.log(e),document.addEventListener("click",D),A.value=!0,i("loadingUpdate",!0);const r=new FormData;let o;r.append("image",e);try{const t=await fetch("/tta/ocr?language="+s.language,{method:"POST",body:r});if(!t.ok)throw new Error(`Server error: ${t.status}`);o=await t.text(),w.value=o,L()}catch(t){a.add({title:"Error while using OCR",text:"Please check your console/terminal for the error.",type:"error",dialog:!0}),console.error(t)}return A.value=!1,i("loadingUpdate",!1),o}function L(){const t=f.value,e=t.naturalWidth,i=t.naturalHeight,s=t.clientWidth,n=t.clientHeight,a=[];(new DOMParser).parseFromString(w.value,"text/html").querySelectorAll(".ocrx_word").forEach((t=>{const r=t.getAttribute("title");if(r){const o=r.match(/bbox (\d+) (\d+) (\d+) (\d+)/);if(o){const[r,l,h,c,d]=o.map(Number),u=l/e*s,p=h/i*n,g={x0:u,y0:p,x1:u+(c-l)/e*s,y1:p+(d-h)/i*n};a.push({text:t.textContent.trim(),bbox:g})}else console.warn("Malformed bbox data for span:",t)}else console.warn("Missing title attribute for span:",t)})),g.value=a}function D(){const t=document.activeElement;if(("INPUT"===t.tagName||"TEXTAREA"===t.tagName)&&!t.readOnly&&!t.disabled&&R.value){const e=t.selectionStart,i=t.selectionEnd,s=t.value;t.value=s.slice(0,e)+R.value+s.slice(i),t.selectionStart=t.selectionEnd=e+R.length,v.value=[],t.dispatchEvent(new Event("input",{bubbles:!0}))}}return x((async()=>{const t=await new Promise((t=>{const e=new FileReader;e.onload=e=>{t(e.target.result)},"application/pdf"==s.image.type?e.readAsArrayBuffer(s.image):e.readAsDataURL(s.image)}));if(s.image.type.startsWith("image/"))P(t,s.image);else if("application/pdf"==s.image.type){const e=new Uint8Array(t),i=await hc(e).promise;console.log(i.numPages);for(let t=1;t<=i.numPages;t++){const e=await i.getPage(t),s=e.getViewport({scale:1}),n=document.createElement("canvas"),a=n.getContext("2d");n.width=s.width,n.height=s.height,await e.render({canvasContext:a,viewport:s}).promise;const r=await new Promise((t=>n.toBlob((e=>t(e)),"image/png")));k.value.push({string:n.toDataURL("image/png"),file:new File([r],"page"+t+".png",{type:"image/png"})}),n.remove(),console.log({i:t})}const[s]=k.value;s&&P(s.string,s.file).then((t=>s.response=t))}else i("close"),a.add({title:"Error while using OCR",text:`File type '${s.image.type}' not supported.`,type:"error",dialog:!0})})),y((()=>T.value),(t=>{const e=k.value[t-1];e&&P(e.string,e.file,e.response).then((t=>e.response=t))})),F((()=>{document.removeEventListener("click",D)})),(t,e)=>{const i=r("v-progress-circular"),s=r("VPagination"),n=r("v-input");return o(),p(C,null,[A.value?(o(),p("div",Td,[c(i,{indeterminate:"",class:"c"})])):d("v-if",!0),_.value?(o(),p("div",Sd,[m("div",Ed,[m("img",{src:_.value,onLoad:L,style:{width:"100%","object-fit":"contain"},ref_key:"imageRef",ref:f,onMousedown:e[0]||(e[0]=M((()=>{}),["stop"]))},null,40,Cd),(o(!0),p(C,null,I(g.value,((t,i)=>(o(),p("div",{key:i,class:"text-overlay",style:S({padding:"2px",position:"absolute",left:`${t.bbox.x0}px`,top:`${t.bbox.y0}px`,width:t.bbox.x1-t.bbox.x0+"px",height:t.bbox.y1-t.bbox.y0+"px",border:v.value.includes(i)?"2px solid green":h.value===i?"2px solid blue":"1px solid transparent",cursor:"pointer",backgroundColor:"rgba(255, 255, 0, 0.3)"}),onClick:t=>function(t){const e=v.value.indexOf(t);-1==e?v.value.push(t):v.value.splice(e,1)}(i),onMouseover:t=>h.value=i,onMouseleave:e[1]||(e[1]=t=>h.value=null)},null,44,Rd)))),128))],512),k.value.length>1?(o(),l(s,{key:0,modelValue:T.value,"onUpdate:modelValue":e[2]||(e[2]=t=>T.value=t),length:k.value.length,totalVisible:4,class:"pagination-center"},null,8,["modelValue","length"])):d("v-if",!0),c(n,{modelValue:E(R)},null,8,["modelValue"])])):d("v-if",!0)],64)}}});Zn("\n.image-display-area[data-v-0d65f7ea] {\n position: relative;\n background: white;\n border: 1px solid white;\n color: black;\n border-radius: 8px;\n overflow: hidden;\n margin: auto;\n width: 100%;\n display: flex;\n flex-direction: column;\n}\n.pagination-center[data-v-0d65f7ea] {\n margin: 5px auto;\n}\n.ocr-container[data-v-0d65f7ea] {\n position: relative;\n height: 100%;\n}\n.text-overlay[data-v-0d65f7ea] {\n position: absolute;\n}\n.loading-screen[data-v-0d65f7ea] {\n position: absolute;\n width: 100%;\n height: 100%;\n background-color: rgba(255, 255, 255, 0.4);\n display: flex;\n left: 0;\n top: 0;\n z-index: 1000;\n}\n.loading-screen .c[data-v-0d65f7ea] {\n margin: auto;\n}\n",{}),Md.__scopeId="data-v-0d65f7ea",Md.__file="ocr/OCR-interface/src/renderOCRResponse.vue";var Pd=v({__name:"ocredrag",props:{initialX:{type:Number,required:!0},initialY:{type:Number,required:!0}},emits:["close"],setup(t,{emit:e}){const i=t,s=u(null),n=u(!1),a=B({x:i.initialX||50,y:i.initialY||50}),d=B({x:0,y:0}),p=t=>{n.value=!0,d.x=t.clientX-a.x,d.y=t.clientY-a.y,document.addEventListener("mousemove",g),document.addEventListener("mouseup",f)},g=t=>{n.value&&(a.x=t.clientX-d.x,a.y=t.clientY-d.y)},f=()=>{n.value=!1,document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",f)};return j((()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",f)})),(t,i)=>{const d=r("v-icon"),u=r("VButton");return o(),l(z,{to:"body"},[m("div",{ref_key:"draggableElement",ref:s,style:S({position:"absolute",left:a.x+"px",top:a.y+"px",cursor:n.value?"grabbing":"grab",width:"500px","max-width":"80vw",height:"auto",padding:"20px",backgroundColor:"var(--theme--background)",color:"var(--theme--form--field--label--foreground)",border:"var(--theme--border-color) 2px solid",borderRadius:"4px",userSelect:"none","z-index":100}),onMousedown:p},[V(t.$slots,"default"),c(u,{onClick:i[0]||(i[0]=t=>e("close")),outlined:!1,icon:!0,rounded:!0,class:"close-btn"},{default:h((()=>[c(d,{name:"close"})])),_:1})],36)])}}});Zn("\n.close-btn[data-v-6008a42c] {\n position: absolute;\n right: -10px;\n top: -10px;\n z-index: 1001;\n}\n",{}),Pd.__scopeId="data-v-6008a42c",Pd.__file="ocr/OCR-interface/src/ocredrag.vue";const Ld={class:"ocr-container"};var Dd=v({__name:"interface",props:{language:{type:String,required:!0},collection:{type:String,required:!0}},setup(t){const i=t,{useFieldsStore:s}=e(),n=s(),a=u(!1),f=u(),_=u(!1),v=u(),b=u([]);function y(){f.value.click()}async function A(t){const e=t.target.files[0];e&&(v.value=e)}async function k(t,e){const i=e||T(t.target.parentElement);if(i){const t=await fetch(i).then((t=>t.blob())),e=new File([t],"image.png",{type:t.type}),s=f.value,n=new DataTransfer;n.items.add(e),s.files=n.files,s.dispatchEvent(new Event("change",{bubbles:!0}))}}function T(t){let e=0,i="";for(;e<10;){const s=(t=t.parentElement).querySelector("img");if(s){i=s.src;break}e++}return i.split("?")[0]}function S(){v.value=null,f.value.value=""}return x((()=>{const t=n.getFieldsForCollection(i.collection).filter((t=>{var e;return"file-image"==(null==(e=t.meta)?void 0:e.interface)}));w((()=>{setTimeout((()=>{for(const e of t){const t="[data-collection="+i.collection+"][data-field="+e.field+"]",s=document.querySelector(t);s&&s.addEventListener("mouseover",(e=>{const i=s.querySelector(".image-preview img");if(i){!s.querySelector(".ocr_button")&&T(i)&&b.value.push(t+" .actions")}}))}}),500);const e=n.getFieldsForCollection(i.collection).filter((t=>{var e;return"file"==(null==(e=t.meta)?void 0:e.interface)}));w((()=>{setTimeout((()=>{for(const t of e){const e="[data-collection="+i.collection+"][data-field="+t.field+"]",s=document.querySelector(e);if(s){const t=s.querySelector("input");null==t||t.addEventListener("change",(()=>{var t;null==(t=document.getElementById("_SCAN_OCR"))||t.remove()})),s.addEventListener("click",(()=>{setTimeout((()=>{var t;const e=document.querySelector("a[download]");if(e){const i=e.cloneNode(!0);i.href="#",i.querySelector("i").setAttribute("data-icon","camera_video"),i.id="_SCAN_OCR",i.classList.add("hide-by-default"),i.children[1].innerText="Scan with OCR",i.addEventListener("click",(t=>{t.preventDefault(),k(void 0,e.getAttribute("href"))})),null==(t=e.parentNode)||t.insertBefore(i,e)}}),100)}))}}}))})),a.value=!0}))})),(e,i)=>{const s=r("v-icon"),n=r("VButton"),u=r("v-button");return o(),p(C,null,[(o(!0),p(C,null,I(b.value,(t=>(o(),l(z,{to:t},[c(n,{onClick:k,outlined:!1,icon:!0,rounded:!0,class:"ocr_button"},{default:h((()=>[c(s,{name:"camera_video"})])),_:1})],8,["to"])))),256)),a.value?(o(),l(z,{key:0,to:"#sidebar .accordion-root"},[m("div",Ld,[c(u,{class:"ocr-btn",onClick:y,loading:_.value},{default:h((()=>[g(" Import data with OCR ")])),_:1},8,["loading"]),m("input",{type:"file",onChange:A,class:"ocr-input",ref_key:"inputRef",ref:f,accept:"image/*,application/pdf"},null,544),null!=v.value?(o(),l(Pd,{key:0,onClose:S},{default:h((()=>[c(Md,{image:v.value,onClose:i[0]||(i[0]=()=>S()),language:t.language,onLoadingUpdate:i[1]||(i[1]=t=>_.value=t)},null,8,["image","language"])])),_:1})):d("v-if",!0)])])):d("v-if",!0)],64)}}});Zn("\n.ocr-container {\n display: flex;\n}\n.ocr-container .ocr-btn {\n margin: 10px auto;\n}\n.ocr-container .ocr-input {\n display: none;\n}\n.hide-by-default {\n display: none;\n}\na ~ #_SCAN_OCR {\n display: block;\n}\n",{}),Dd.__file="ocr/OCR-interface/src/interface.vue";const Id=[xr,kr,Er,n({id:"tta-ocr-interface",name:"OCR interface",icon:"camera_video",description:"Use OCR to fill fields. (Text to anything)",hideLabel:!0,hideLoader:!0,component:Dd,types:["alias"],localTypes:["presentation"],options:[{field:"language",name:"Language",type:"dropdown",meta:{interface:"select-dropdown",options:{choices:[{value:"eng",text:"English"},{value:"por",text:"Portuguese"},{value:"fra",text:"French"},{value:"osd",text:"Orientation and Script Detection"},{value:"chi_sim",text:"Chinese (Simplified)"},{value:"spa",text:"Spanish"},{value:"deu",text:"German"},{value:"chi_tra",text:"Chinese (Traditional)"},{value:"heb",text:"Hebrew"},{value:"kor",text:"Korean"},{value:"jpn",text:"Japanese"},{value:"rus",text:"Russian"},{value:"nld",text:"Dutch"},{value:"hin",text:"Hindi"},{value:"ita",text:"Italian"},{value:"jpn_vert",text:"Japanese (Vertical)"},{value:"pol",text:"Polish"},{value:"ron",text:"Romanian"},{value:"mar",text:"Marathi"},{value:"ukr",text:"Ukrainian"},{value:"mal",text:"Malayalam"},{value:"tam",text:"Tamil"},{value:"guj",text:"Gujarati"},{value:"tha",text:"Thai"},{value:"kan",text:"Kannada"},{value:"vie",text:"Vietnamese"},{value:"tel",text:"Telugu"},{value:"swe",text:"Swedish"},{value:"tur",text:"Turkish"},{value:"nor",text:"Norwegian"},{value:"ces",text:"Czech"},{value:"ben",text:"Bengali"},{value:"pan",text:"Punjabi"},{value:"equ",text:"Math / Equation Detection"},{value:"ell",text:"Greek"},{value:"bul",text:"Bulgarian"},{value:"lat",text:"Latin"},{value:"kur",text:"Kurdish"},{value:"ori",text:"Odia"},{value:"kat",text:"Georgian"},{value:"amh",text:"Amharic"},{value:"kaz",text:"Kazakh"},{value:"cat",text:"Catalan"},{value:"nep",text:"Nepali"},{value:"urd",text:"Urdu"},{value:"khm",text:"Khmer"},{value:"dan",text:"Danish"},{value:"chi_sim_vert",text:"Chinese (Simplified, Vertical)"},{value:"uzb",text:"Uzbek (Latin)"},{value:"slv",text:"Slovenian"},{value:"mkd",text:"Macedonian"},{value:"tgl",text:"Tagalog"},{value:"srp",text:"Serbian (Cyrillic)"},{value:"hrv",text:"Croatian"},{value:"tir",text:"Tigrinya"},{value:"syr",text:"Syriac"},{value:"lao",text:"Lao"},{value:"fin",text:"Finnish"},{value:"est",text:"Estonian"},{value:"bos",text:"Bosnian"},{value:"uig",text:"Uyghur"},{value:"sin",text:"Sinhala"},{value:"hye",text:"Armenian"},{value:"eus",text:"Basque"},{value:"sqi",text:"Albanian"},{value:"isl",text:"Icelandic"},{value:"bel",text:"Belarusian"},{value:"aze",text:"Azerbaijani (Latin)"},{value:"pus",text:"Pashto"},{value:"oci",text:"Occitan"},{value:"lit",text:"Lithuanian"},{value:"jav",text:"Javanese"},{value:"hun",text:"Hungarian"},{value:"grc",text:"Ancient Greek"},{value:"gle",text:"Irish"},{value:"frm",text:"Middle French"},{value:"afr",text:"Afrikaans"},{value:"uzb_cyrl",text:"Uzbek (Cyrillic)"},{value:"spa_old",text:"Old Spanish"},{value:"snd",text:"Sindhi"},{value:"mya",text:"Burmese"},{value:"iku",text:"Inuktitut"},{value:"fil",text:"Filipino"},{value:"fas",text:"Persian"},{value:"fao",text:"Faroese"},{value:"dzo",text:"Dzongkha"},{value:"cym",text:"Welsh"},{value:"aze_cyrl",text:"Azerbaijani (Cyrillic)"},{value:"ind",text:"Indonesian"},{value:"ara",text:"Arabic"},{value:"yid",text:"Yiddish"},{value:"ton",text:"Tongan"},{value:"tgk",text:"Tajik"},{value:"srp_latn",text:"Serbian (Latin)"},{value:"slk_frak",text:"Slovak (Fraktur)"},{value:"slk",text:"Slovak"},{value:"san",text:"Sanskrit"},{value:"msa",text:"Malay"},{value:"mri",text:"Maori"},{value:"mlt",text:"Maltese"},{value:"lav",text:"Latvian"},{value:"kur_ara",text:"Kurdish (Arabic)"},{value:"kor_vert",text:"Korean (Vertical)"},{value:"kmr",text:"Kurmanji"},{value:"kir",text:"Kyrgyz"},{value:"hat",text:"Haitian Creole"},{value:"glg",text:"Galician"},{value:"fry",text:"Frisian"},{value:"epo",text:"Esperanto"},{value:"div",text:"Divehi"},{value:"chr",text:"Cherokee"},{value:"bod",text:"Tibetan"},{value:"asm",text:"Assamese"},{value:"yor",text:"Yoruba"},{value:"tat",text:"Tatar"},{value:"sun",text:"Sundanese"},{value:"occ",text:"Occitan (alternative)"},{value:"mon",text:"Mongolian"},{value:"ita_old",text:"Old Italian"},{value:"gla",text:"Scottish Gaelic"},{value:"frk",text:"Frankish"},{value:"enm",text:"Middle English"},{value:"deu_frak",text:"German (Fraktur)"},{value:"dan_frak",text:"Danish (Fraktur)"},{value:"chi_tra_vert",text:"Chinese (Traditional, Vertical)"},{value:"ceb",text:"Cebuano"},{value:"bre",text:"Breton"},{value:"swa",text:"Swahili"},{value:"que",text:"Quechua"},{value:"ltz",text:"Luxembourgish"},{value:"kat_old",text:"Old Georgian"},{value:"cos",text:"Corsican"}]}}}]})],Od=[],Nd=[],Fd=[yr],Bd=[],jd=[H,$,W,G,t({id:"ttaocr",name:"TTA OCR",icon:"camera_video",description:"TTA scan image with OCR",overview:({fileID:t,mode:e,language:i})=>[{label:"Mode",text:e},{label:"Language",text:i},{label:"File ID",text:t}],options:[{field:"fileID",name:"File ID",type:"string",meta:{width:"full",interface:"input"}},{field:"mode",name:"Mode",type:"string",meta:{interface:"select-dropdown",options:{choices:[{text:"Text",value:"text"},{text:"Horc",value:"horc"}]}}},{field:"language",name:"Language",type:"dropdown",meta:{interface:"select-dropdown",options:{choices:[{value:"eng",text:"English"},{value:"por",text:"Portuguese"},{value:"fra",text:"French"},{value:"osd",text:"Orientation and Script Detection"},{value:"chi_sim",text:"Chinese (Simplified)"},{value:"spa",text:"Spanish"},{value:"deu",text:"German"},{value:"chi_tra",text:"Chinese (Traditional)"},{value:"heb",text:"Hebrew"},{value:"kor",text:"Korean"},{value:"jpn",text:"Japanese"},{value:"rus",text:"Russian"},{value:"nld",text:"Dutch"},{value:"hin",text:"Hindi"},{value:"ita",text:"Italian"},{value:"jpn_vert",text:"Japanese (Vertical)"},{value:"pol",text:"Polish"},{value:"ron",text:"Romanian"},{value:"mar",text:"Marathi"},{value:"ukr",text:"Ukrainian"},{value:"mal",text:"Malayalam"},{value:"tam",text:"Tamil"},{value:"guj",text:"Gujarati"},{value:"tha",text:"Thai"},{value:"kan",text:"Kannada"},{value:"vie",text:"Vietnamese"},{value:"tel",text:"Telugu"},{value:"swe",text:"Swedish"},{value:"tur",text:"Turkish"},{value:"nor",text:"Norwegian"},{value:"ces",text:"Czech"},{value:"ben",text:"Bengali"},{value:"pan",text:"Punjabi"},{value:"equ",text:"Math / Equation Detection"},{value:"ell",text:"Greek"},{value:"bul",text:"Bulgarian"},{value:"lat",text:"Latin"},{value:"kur",text:"Kurdish"},{value:"ori",text:"Odia"},{value:"kat",text:"Georgian"},{value:"amh",text:"Amharic"},{value:"kaz",text:"Kazakh"},{value:"cat",text:"Catalan"},{value:"nep",text:"Nepali"},{value:"urd",text:"Urdu"},{value:"khm",text:"Khmer"},{value:"dan",text:"Danish"},{value:"chi_sim_vert",text:"Chinese (Simplified, Vertical)"},{value:"uzb",text:"Uzbek (Latin)"},{value:"slv",text:"Slovenian"},{value:"mkd",text:"Macedonian"},{value:"tgl",text:"Tagalog"},{value:"srp",text:"Serbian (Cyrillic)"},{value:"hrv",text:"Croatian"},{value:"tir",text:"Tigrinya"},{value:"syr",text:"Syriac"},{value:"lao",text:"Lao"},{value:"fin",text:"Finnish"},{value:"est",text:"Estonian"},{value:"bos",text:"Bosnian"},{value:"uig",text:"Uyghur"},{value:"sin",text:"Sinhala"},{value:"hye",text:"Armenian"},{value:"eus",text:"Basque"},{value:"sqi",text:"Albanian"},{value:"isl",text:"Icelandic"},{value:"bel",text:"Belarusian"},{value:"aze",text:"Azerbaijani (Latin)"},{value:"pus",text:"Pashto"},{value:"oci",text:"Occitan"},{value:"lit",text:"Lithuanian"},{value:"jav",text:"Javanese"},{value:"hun",text:"Hungarian"},{value:"grc",text:"Ancient Greek"},{value:"gle",text:"Irish"},{value:"frm",text:"Middle French"},{value:"afr",text:"Afrikaans"},{value:"uzb_cyrl",text:"Uzbek (Cyrillic)"},{value:"spa_old",text:"Old Spanish"},{value:"snd",text:"Sindhi"},{value:"mya",text:"Burmese"},{value:"iku",text:"Inuktitut"},{value:"fil",text:"Filipino"},{value:"fas",text:"Persian"},{value:"fao",text:"Faroese"},{value:"dzo",text:"Dzongkha"},{value:"cym",text:"Welsh"},{value:"aze_cyrl",text:"Azerbaijani (Cyrillic)"},{value:"ind",text:"Indonesian"},{value:"ara",text:"Arabic"},{value:"yid",text:"Yiddish"},{value:"ton",text:"Tongan"},{value:"tgk",text:"Tajik"},{value:"srp_latn",text:"Serbian (Latin)"},{value:"slk_frak",text:"Slovak (Fraktur)"},{value:"slk",text:"Slovak"},{value:"san",text:"Sanskrit"},{value:"msa",text:"Malay"},{value:"mri",text:"Maori"},{value:"mlt",text:"Maltese"},{value:"lav",text:"Latvian"},{value:"kur_ara",text:"Kurdish (Arabic)"},{value:"kor_vert",text:"Korean (Vertical)"},{value:"kmr",text:"Kurmanji"},{value:"kir",text:"Kyrgyz"},{value:"hat",text:"Haitian Creole"},{value:"glg",text:"Galician"},{value:"fry",text:"Frisian"},{value:"epo",text:"Esperanto"},{value:"div",text:"Divehi"},{value:"chr",text:"Cherokee"},{value:"bod",text:"Tibetan"},{value:"asm",text:"Assamese"},{value:"yor",text:"Yoruba"},{value:"tat",text:"Tatar"},{value:"sun",text:"Sundanese"},{value:"occ",text:"Occitan (alternative)"},{value:"mon",text:"Mongolian"},{value:"ita_old",text:"Old Italian"},{value:"gla",text:"Scottish Gaelic"},{value:"frk",text:"Frankish"},{value:"enm",text:"Middle English"},{value:"deu_frak",text:"German (Fraktur)"},{value:"dan_frak",text:"Danish (Fraktur)"},{value:"chi_tra_vert",text:"Chinese (Traditional, Vertical)"},{value:"ceb",text:"Cebuano"},{value:"bre",text:"Breton"},{value:"swa",text:"Swahili"},{value:"que",text:"Quechua"},{value:"ltz",text:"Luxembourgish"},{value:"kat_old",text:"Old Georgian"},{value:"cos",text:"Corsican"}]}}}]})];export{Od as displays,Id as interfaces,Nd as layouts,Fd as modules,jd as operations,Bd as panels};
|