diff --git a/src/ProjectTemplates/.gitignore b/src/ProjectTemplates/.gitignore index 22b26761348..4844d4e7b87 100644 --- a/src/ProjectTemplates/.gitignore +++ b/src/ProjectTemplates/.gitignore @@ -8,3 +8,9 @@ package-lock.json # launchSettings.json files are required for the templates. !launchSettings.json + +# Templates include JS dependencies in dist folders. +!**/dist/* + +# Keep the package-lock.json file for updating template dependencies. +!package-lock.json diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/.gitignore b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/.gitignore index ce34cc25bc9..6d861e077d1 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/.gitignore +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/.gitignore @@ -1,4 +1,2 @@ *.db *.db-* -wwwroot/lib.out.js -wwwroot/*.generated.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/Components/Pages/Chat/ChatCitation.razor b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/Components/Pages/Chat/ChatCitation.razor index bcc5924dc22..1d30537ada6 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/Components/Pages/Chat/ChatCitation.razor +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/Components/Pages/Chat/ChatCitation.razor @@ -29,7 +29,7 @@ if (File.EndsWith(".pdf")) { var search = Quote.Trim('.', ',', ' ', '\n', '\r', '\t', '"', '\''); - viewerUrl = $"pdfjs/web/viewer.html?file=/citation/{HttpUtility.UrlEncode(File)}#page={PageNumber}&search={HttpUtility.UrlEncode(search)}&phrase=true"; + viewerUrl = $"pdf_viewer/viewer.html?file=/citation/{HttpUtility.UrlEncode(File)}#page={PageNumber}&search={HttpUtility.UrlEncode(search)}&phrase=true"; } } } diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/app.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/app.css index 36f5764318a..209035d66f4 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/app.css +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/app.css @@ -1,4 +1,4 @@ -@import url('tailwindcss/web/preflight.css'); +@import url('lib/tailwindcss/dist/preflight.css'); html { min-height: 100vh; diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/dompurify/web/purify.es.mjs.map b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/dompurify/web/purify.es.mjs.map deleted file mode 100644 index bfb097cde27..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/dompurify/web/purify.es.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"purify.es.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib.js b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib.js index ee858d6c264..c77a8cb6442 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib.js +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib.js @@ -1,5 +1,5 @@ -import DOMPurify from './dompurify/web/purify.es.mjs'; -import * as marked from './marked/web/marked.esm.js'; +import DOMPurify from './lib/dompurify/dist/purify.es.mjs'; +import * as marked from './lib/marked/dist/marked.esm.js'; const purify = DOMPurify(window); diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/dompurify/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/dompurify/README.md similarity index 71% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/dompurify/README.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/dompurify/README.md index 0ef15c1899e..8ccedde96cb 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/dompurify/README.md +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/dompurify/README.md @@ -1,5 +1,5 @@ -DOMPurify version 3.2.4 +dompurify version 3.2.4 https://github.com/cure53/DOMPurify License: Apache 2.0 and Mozilla Public License 2.0 -To update, replace the files with an updated build from https://github.com/cure53/DOMPurify/releases +To update, replace the files with an updated build from https://www.npmjs.com/package/dompurify diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/dompurify/web/purify.es.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/dompurify/dist/purify.es.mjs similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/dompurify/web/purify.es.mjs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/dompurify/dist/purify.es.mjs diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/marked/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/marked/README.md new file mode 100644 index 00000000000..31aeeb10a82 --- /dev/null +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/marked/README.md @@ -0,0 +1,5 @@ +marked version 15.0.6 +https://github.com/markedjs/marked +License: MIT + +To update, replace the files with with an updated build from https://www.npmjs.com/package/marked diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/marked/web/marked.esm.js b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/marked/dist/marked.esm.js similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/marked/web/marked.esm.js rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/marked/dist/marked.esm.js diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/README.txt b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/README.md similarity index 66% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/README.txt rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/README.md index 38de93f8bad..1ec731136cb 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/README.txt +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/README.md @@ -1,5 +1,5 @@ -pdf.js version 4.10.38 +pdfjs-dist version 4.10.38 https://github.com/mozilla/pdf.js License: Apache-2.0 -To update, replace the files with an updated build from https://github.com/mozilla/pdf.js/releases +To update, replace the files with an updated build from https://www.npmjs.com/package/pdfjs-dist diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs new file mode 100644 index 00000000000..f09214a966f --- /dev/null +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.min.mjs @@ -0,0 +1,21 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2024 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},__webpack_exports__ = globalThis.pdfjsLib = {};t.d(__webpack_exports__,{AbortException:()=>AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>g,AnnotationEditorUIManager:()=>AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>p,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>util_FeatureTest,GlobalWorkerOptions:()=>GlobalWorkerOptions,ImageKind:()=>_,InvalidPDFException:()=>InvalidPDFException,MissingPDFException:()=>MissingPDFException,OPS:()=>X,OutputScale:()=>OutputScale,PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFDateString:()=>PDFDateString,PDFWorker:()=>PDFWorker,PasswordResponses:()=>K,PermissionFlag:()=>f,PixelsPerInch:()=>PixelsPerInch,RenderingCancelledException:()=>RenderingCancelledException,TextLayer:()=>TextLayer,TouchManager:()=>TouchManager,UnexpectedResponseException:()=>UnexpectedResponseException,Util:()=>Util,VerbosityLevel:()=>q,XfaLayer:()=>XfaLayer,build:()=>Nt,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,fetchData:()=>fetchData,getDocument:()=>getDocument,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,noContextMenu:()=>noContextMenu,normalizeUnicode:()=>normalizeUnicode,setLayerDimensions:()=>setLayerDimensions,shadow:()=>shadow,stopEvent:()=>stopEvent,version:()=>Ot});const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],s=[.001,0,0,.001,0,0],n=1.35,a=1,r=2,o=4,l=16,h=32,d=64,c=128,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b=0,A=1,w=2,v=3,y=3,x=4,_={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},E=1,S=2,C=3,T=4,M=5,P=6,D=7,k=8,R=9,I=10,F=11,L=12,O=13,N=14,B=15,H=16,z=17,U=20,G=1,$=2,V=3,j=4,W=5,q={ERRORS:0,WARNINGS:1,INFOS:5},X={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},K={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Y=q.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(Y=t)}function getVerbosityLevel(){return Y}function info(t){Y>=q.INFOS&&console.log(`Info: ${t}`)}function warn(t){Y>=q.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const s=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const Q=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends Q{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends Q{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends Q{constructor(t){super(t,"InvalidPDFException")}}class MissingPDFException extends Q{constructor(t){super(t,"MissingPDFException")}}class UnexpectedResponseException extends Q{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}}class FormatError extends Q{constructor(t){super(t,"FormatError")}}class AbortException extends Q{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,i){return`#${J[t]}${J[e]}${J[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*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,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c);this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){if(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)}else l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(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);return l}}let Z=null,tt=null;function normalizeUnicode(t){if(!Z){Z=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;tt=new Map([["ſt","ſt"]])}return t.replaceAll(Z,((t,e,i)=>e?e.normalize("NFKC"):tt.get(i)))}const et="pdfjs_internal_id_";"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise((i=>{i(t(...e))}))});const it="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"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":i(n.response);return}i(n.responseText)}};n.send(null)}))}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY: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,d,c,u,p,g,m,f;(s%=360)<0&&(s+=360);switch(s){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(r){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+n;g=Math.abs(o-t[0])*i+a;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+n;g=Math.abs(l-t[1])*i+a;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const{userUnit:t,viewBox:e}=this,i=e.map((e=>e*t));return shadow(this,"rawDims",{pageWidth:i[2]-i[0],pageHeight:i[3]-i[1],pageX:i[0],pageY:i[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=Util.applyTransform([t[0],t[1]],this.transform),i=Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends Q{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i=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 d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){a+=h;r+=d}else if("+"===l){a-=h;r-=d}return new Date(Date.UTC(i,s,n,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new PageViewport({viewBox:a,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function getCurrentTransformInverse(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 setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=util_FeatureTest.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;if(i&&e.rotation%180!=0){a.width=d;a.height=h}else{a.width=h;a.height=d}}s&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const t=window.devicePixelRatio||1;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class EditorToolbar{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t;EditorToolbar.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#h,{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))`}this.#d();return t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1;stopEvent(t)}#u(t){this.#a._focusEventsAllowed=!0;stopEvent(t)}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{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",EditorToolbar.#l[t]);this.#p(i);i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal});this.#r.append(i)}get#g(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#p(e);this.#r.prepend(e,this.#g);this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e);this.#r.prepend(e,this.#g)}remove(){this.#s.remove();this.#n?.destroy();this.#n=null}}class HighlightToolbar{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");t.addEventListener("contextmenu",noContextMenu,{signal:this.#m._signal});const e=this.#r=document.createElement("div");e.className="buttons";t.append(e);this.#b();return t}#A(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti){s=a;i=t}else e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i});this.#r.append(t)}}function bindEvents(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class IdManager{#w=0;get id(){return"pdfjs_internal_editor_"+this.#w++}}class ImageManager{#v=function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}();#w=0;#y=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,';return shadow(this,"_isSVGFittingCanvas",e.decode().then((()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]})))}async#x(t,e){this.#y||=new Map;let i=this.#y.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#v}_${this.#w++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,s=new FileReader,n=new Image,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){warn(t);i=null}this.#y.set(t,i);i&&this.#y.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#x(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#x(t,t)}async getFromBlob(t,e){const i=await e;return this.#x(t,i)}async getFromId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#y||=new Map;let i=this.#y.get(t);if(i?.bitmap){i.refCounter+=1;return i}const s=new OffscreenCanvas(e.width,e.height);s.getContext("2d").drawImage(e,0,0);i={bitmap:s.transferToImageBitmap(),id:`image_${this.#v}_${this.#w++}`,refCounter:1,isSvg:!1};this.#y.set(t,i);this.#y.set(i.id,i);return i}getSvgUrl(t){const e=this.#y.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#y||=new Map;const e=this.#y.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#v}_`)}}class CommandManager{#_=[];#E=!1;#S;#C=-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}){s&&t();if(this.#E)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#C){this.#_.length>0&&(this.#_.length=0);this.#C=0;this.#_.push(o);return}if(a&&this.#_[this.#C].type===n){r&&(o.undo=this.#_[this.#C].undo);this.#_[this.#C]=o;return}const l=this.#C+1;if(l===this.#S)this.#_.splice(0,1);else{this.#C=l;l=0;e--)if(this.#_[e].type!==t){this.#_.splice(e+1,this.#C-e);this.#C=e;return}this.#_.length=0;this.#C=-1}}destroy(){this.#_=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#T(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#T(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;if(!r||r(t,e)){s.bind(t,...a,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,getRGB(s))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#M=new AbortController;#P=null;#D=new Map;#k=new Map;#R=null;#I=null;#F=null;#L=new CommandManager;#O=null;#N=null;#B=0;#H=new Set;#z=null;#U=null;#G=new Set;_editorUndoBar=null;#$=!1;#V=!1;#j=!1;#W=null;#q=null;#X=null;#K=null;#Y=!1;#Q=null;#J=new IdManager;#Z=!1;#tt=!1;#et=null;#it=null;#st=null;#nt=null;#at=g.NONE;#rt=new Set;#ot=null;#lt=null;#ht=null;#dt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#ct=[0,0];#ut=null;#pt=null;#gt=null;#mt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#pt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d,c,u){const p=this._signal=this.#M.signal;this.#pt=t;this.#gt=e;this.#R=i;this._eventBus=s;s._on("editingaction",this.onEditingAction.bind(this),{signal:p});s._on("pagechanging",this.onPageChanging.bind(this),{signal:p});s._on("scalechanging",this.onScaleChanging.bind(this),{signal:p});s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:p});s._on("setpreference",this.onSetPreference.bind(this),{signal:p});s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:p});this.#ft();this.#bt();this.#At();this.#I=n.annotationStorage;this.#W=n.filterFactory;this.#lt=a;this.#K=r||null;this.#$=o;this.#V=l;this.#j=h;this.#nt=d||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=c||null;this._supportsPinchToZoom=!1!==u}destroy(){this.#mt?.resolve();this.#mt=null;this.#M?.abort();this.#M=null;this._signal=null;for(const t of this.#k.values())t.destroy();this.#k.clear();this.#D.clear();this.#G.clear();this.#P=null;this.#rt.clear();this.#L.destroy();this.#R?.destroy();this.#Q?.hide();this.#Q=null;if(this.#q){clearTimeout(this.#q);this.#q=null}if(this.#ut){clearTimeout(this.#ut);this.#ut=null}this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#nt}get useNewAltTextFlow(){return this.#V}get useNewAltTextWhenAddingImage(){return this.#j}get hcmFilter(){return shadow(this,"hcmFilter",this.#lt?this.#W.addHCMFilter(this.#lt.foreground,this.#lt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#pt).direction)}get highlightColors(){return shadow(this,"highlightColors",this.#K?new Map(this.#K.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#N=t}setMainHighlightColorPicker(t){this.#st=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#j=e}onPageChanging({pageNumber:t}){this.#B=t-1}focusMainContainer(){this.#pt.focus()}findParent(t,e){for(const i of this.#k.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.#gt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#G.add(t)}removeShouldRescale(t){this.#G.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#G)t.onScaleChanging();this.#N?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#wt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#vt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#k.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.#wt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#vt(o),d=this.#at===g.NONE,callback=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r});d&&this.showAllEditors("highlight",!0,!0)};d?this.switchToMode(g.HIGHLIGHT,callback):callback()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#wt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#Q||=new HighlightToolbar(this);this.#Q.show(e,i,"ltr"===this.direction)}}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#xt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#ot)return;const i=this.#wt(t).closest(".textLayer");if(i){this.#Q?.hide();this.#ot=e;this.#_t({hasSelectedText:!0});if(this.#at===g.HIGHLIGHT||this.#at===g.NONE){this.#at===g.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#Y=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#at===g.HIGHLIGHT?this.#vt(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Et("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:s});window.addEventListener("blur",pointerup,{signal:s})}}}else if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}}#Et(t=""){this.#at===g.HIGHLIGHT?this.highlightSelection(t):this.#$&&this.#yt()}#ft(){document.addEventListener("selectionchange",this.#xt.bind(this),{signal:this._signal})}#St(){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})}#Ct(){this.#X?.abort();this.#X=null}blur(){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!1;this.#Et("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#rt)if(e.div.contains(t)){this.#it=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#it)return;const[t,e]=this.#it;this.#it=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal});e.focus()}#At(){if(this.#et)return;this.#et=new AbortController;const t=this.combinedSignal(this.#et);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Tt(){this.#et?.abort();this.#et=null}#Mt(){if(this.#O)return;this.#O=new AbortController;const t=this.combinedSignal(this.#O);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})}#Pt(){this.#O?.abort();this.#O=null}#bt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#At();this.#Mt()}removeEditListeners(){this.#Tt();this.#Pt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#U)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#P?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#rt){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)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#Dt(e);this.#kt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#at===g.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#Y){this.#Y=!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")}}#_t(t){if(Object.entries(t).some((([t,e])=>this.#dt[t]!==e))){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#dt,t)});this.#at===g.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Rt([[m.HIGHLIGHT_FREE,!0]])}}#Rt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#St();this.#Mt();this.#_t({isEditing:this.#at!==g.NONE,isEmpty:this.#It(),hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:this.#L.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Ct();this.#Pt();this.#_t({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#U){this.#U=t;for(const t of this.#U)this.#Rt(t.defaultPropertiesToUpdate)}}getId(){return this.#J.id}get currentLayer(){return this.#k.get(this.#B)}getLayer(t){return this.#k.get(t)}get currentPageIndex(){return this.#B}addLayer(t){this.#k.set(t.pageIndex,t);this.#Z?t.enable():t.disable()}removeLayer(t){this.#k.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#at!==t){if(this.#mt){await this.#mt.promise;if(!this.#mt)return}this.#mt=Promise.withResolvers();this.#at=t;if(t!==g.NONE){this.setEditingState(!0);await this.#Ft();this.unselectAll();for(const e of this.#k.values())e.updateMode(t);if(e){for(const t of this.#D.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode()}else t.unselect();this.#mt.resolve()}else{i&&this.addNewEditorFromKeyboard();this.#mt.resolve()}}else{this.setEditingState(!1);this.#Lt();this._editorUndoBar?.hide();this.#mt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#at&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#U){switch(t){case m.CREATE:this.currentLayer.addNewEditor();return;case m.HIGHLIGHT_DEFAULT_COLOR:this.#st?.updateColor(e);break;case m.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#ht||=new Map).set(t,e);this.showAllEditors("highlight",e)}for(const i of this.#rt)i.updateParams(t,e);for(const i of this.#U)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#D.values())i.editorType===t&&i.show(e);(this.#ht?.get(m.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Rt([[m.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#tt!==t){this.#tt=t;for(const e of this.#k.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Ft(){if(!this.#Z){this.#Z=!0;const t=[];for(const e of this.#k.values())t.push(e.enable());await Promise.all(t);for(const t of this.#D.values())t.enable()}}#Lt(){this.unselectAll();if(this.#Z){this.#Z=!1;for(const t of this.#k.values())t.disable();for(const t of this.#D.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#D.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#D.get(t)}addEditor(t){this.#D.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#q&&clearTimeout(this.#q);this.#q=setTimeout((()=>{this.focusMainContainer();this.#q=null}),0)}this.#D.delete(t.id);this.unselect(t);t.annotationElementId&&this.#H.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#H.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#H.has(t)}removeDeletedAnnotationElement(t){this.#H.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Dt(t){const e=this.#k.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#P!==t){this.#P=t;t&&this.#Rt(t.propertiesToUpdate)}}get#Ot(){let t=null;for(t of this.#rt);return t}updateUI(t){this.#Ot===t&&this.#Rt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Rt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#rt.has(t)){this.#rt.delete(t);t.unselect();this.#_t({hasSelectedEditor:this.hasSelection})}else{this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}}setSelected(t){this.#N?.commitOrRemove();for(const e of this.#rt)e!==t&&e.unselect();this.#rt.clear();this.#rt.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#rt.has(t)}get firstSelectedEditor(){return this.#rt.values().next().value}unselect(t){t.unselect();this.#rt.delete(t);this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#rt.size}get isEnterHandled(){return 1===this.#rt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#L.undo();this.#_t({hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#It()});this._editorUndoBar?.hide()}redo(){this.#L.redo();this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#L.hasSomethingToRedo(),isEmpty:this.#It()})}addCommands(t){this.#L.add(t);this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#It()})}cleanUndoStack(t){this.#L.cleanType(t)}#It(){if(0===this.#D.size)return!0;if(1===this.#D.size)for(const t of this.#D.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.#rt],undo=()=>{for(const t of e)this.#Dt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#kt(t){for(const t of this.#rt)t.unselect();this.#rt.clear();for(const e of t)if(!e.isEmpty()){this.#rt.add(e);e.select()}this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#rt)t.commit();this.#kt(this.#D.values())}unselectAll(){if(this.#P){this.#P.commitOrRemove();if(this.#at!==g.NONE)return}if(!this.#N?.commitOrRemove()&&this.hasSelection){for(const t of this.#rt)t.unselect();this.#rt.clear();this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#ct[0]+=t;this.#ct[1]+=e;const[s,n]=this.#ct,a=[...this.#rt];this.#ut&&clearTimeout(this.#ut);this.#ut=setTimeout((()=>{this.#ut=null;this.#ct[0]=this.#ct[1]=0;this.addCommands({cmd:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#D.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#z=new Map;for(const t of this.#rt)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=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 move=(t,e,i,s)=>{if(this.#D.has(t.id)){const n=this.#k.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n}]of t)move(e,i,s,n)},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#rt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#at}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/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;tt.stopPropagation()),{signal:i});const onClick=t=>{t.preventDefault();this.#a._uiManager.editAltText(this.#a);this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Xt}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",(e=>{if(e.target===t&&"Enter"===e.key){this.#Gt=!0;onClick(e)}}),{signal:i});await this.#Kt();return t}get#Xt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){if(this.#Bt){this.#Bt.focus({focusVisible:this.#Gt});this.#Gt=!1}}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Vt:this.isEmpty()}get guessedText(){return this.#Vt}async setGuessedText(t){if(null===this.#o){this.#Vt=t;this.#jt=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#Kt()}}toggleAltTextBadge(t=!1){if(this.#Wt&&!this.#o){if(!this.#$t){const t=this.#$t=document.createElement("div");t.className="noAltTextBadge";this.#a.div.append(t)}this.#$t.classList.toggle("hidden",!t)}else{this.#$t?.remove();this.#$t=null}}serialize(t){let e=this.#o;t||this.#Vt!==e||(e=this.#jt);return{altText:e,decorative:this.#Nt,guessedText:this.#Vt,textWithDisclaimer:this.#jt}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){if(i){this.#Vt=i;this.#jt=s}if(this.#o!==t||this.#Nt!==e){if(!n){this.#o=t;this.#Nt=e}this.#Kt()}}toggle(t=!1){if(this.#Bt){if(!t&&this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#Bt.disabled=!t}}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Xt}})}destroy(){this.#Bt?.remove();this.#Bt=null;this.#Ht=null;this.#zt=null;this.#$t?.remove();this.#$t=null}async#Kt(){const t=this.#Bt;if(!t)return;if(this.#Wt){t.classList.toggle("done",!!this.#o);t.setAttribute("data-l10n-id",AltText.#qt[this.#Xt]);this.#Ht?.setAttribute("data-l10n-id",AltText.#qt[`${this.#Xt}-label`]);if(!this.#o){this.#zt?.remove();return}}else{if(!this.#o&&!this.#Nt){t.classList.remove("done");this.#zt?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#zt;if(!e){this.#zt=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.#Ut);this.#Ut=null}),{once:!0});t.addEventListener("mouseenter",(()=>{this.#Ut=setTimeout((()=>{this.#Ut=null;this.#zt.classList.add("show");this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s});t.addEventListener("mouseleave",(()=>{if(this.#Ut){clearTimeout(this.#Ut);this.#Ut=null}this.#zt?.classList.remove("show")}),{signal:s})}if(this.#Nt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#o}e.parentNode||t.append(e);const i=this.#a.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class TouchManager{#pt;#Yt=!1;#Qt=null;#Jt;#Zt;#te;#ee;#ie;#se=null;#ne;#ae=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#pt=t;this.#Qt=i;this.#Jt=e;this.#Zt=s;this.#te=n;this.#ee=a;this.#ne=new AbortController;this.#ie=AbortSignal.any([r,this.#ne.signal]);t.addEventListener("touchstart",this.#re.bind(this),{passive:!1,signal:this.#ie})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return shadow(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#re(t){if(this.#Jt?.()||t.touches.length<2)return;if(!this.#ae){this.#ae=new AbortController;const t=AbortSignal.any([this.#ie,this.#ae.signal]),e=this.#pt,i={signal:t,passive:!1};e.addEventListener("touchmove",this.#oe.bind(this),i);e.addEventListener("touchend",this.#le.bind(this),i);e.addEventListener("touchcancel",this.#le.bind(this),i);this.#Zt?.()}stopEvent(t);if(2!==t.touches.length||this.#Qt?.()){this.#se=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#se={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#oe(t){if(!this.#se||2!==t.touches.length)return;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.#se,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=a-s,m=r-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#Yt&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=s;o.touch0Y=n;o.touch1X=a;o.touch1Y=r;t.preventDefault();if(!this.#Yt){this.#Yt=!0;return}const A=[(s+a)/2,(n+r)/2];this.#te?.(A,b,f)}#le(t){this.#ae.abort();this.#ae=null;this.#ee?.();if(this.#se){t.preventDefault();this.#se=null;this.#Yt=!1}}destroy(){this.#ne?.abort();this.#ne=null}}class AnnotationEditor{#he=null;#de=null;#o=null;#ce=!1;#ue=null;#pe="";#ge=!1;#me=null;#fe=null;#be=null;#Ae=null;#we="";#ve=!1;#ye=null;#xe=!1;#_e=!1;#Ee=!1;#Se=null;#Ce=0;#Te=0;#Me=null;#Pe=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#De=!1;#ke=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;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 shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#De}set _isDraggable(t){this.#De=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.#ke}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Re();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ve?this.#ve=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.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()}#Ie([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.#Ie(this.parentDimensions,t,e)}translateInPage(t,e){this.#ye||=[this.x,this.y,this.width,this.height];this.#Ie(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#ye||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;this.x+=t/s;this.y+=e/n;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x: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.#ye&&(this.#ye[0]!==this.x||this.#ye[1]!==this.y)}get _hasBeenResized(){return!!this.#ye&&(this.#ye[2]!==this.width||this.#ye[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:a,width:r,height:o}=this;r*=i;o*=s;n*=i;a*=s;if(this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(i-r,n));a=Math.max(0,Math.min(s-o,a));break;case 90:n=Math.max(0,Math.min(i-o,n));a=Math.min(s,Math.max(r,a));break;case 180:n=Math.min(i,Math.max(r,n));a=Math.min(s,Math.max(o,a));break;case 270:n=Math.min(i,Math.max(o,n));a=Math.max(0,Math.min(s-r,a))}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#Fe(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#Fe(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#Fe(t,e,360-this.parentRotation)}#Le(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.#ge||(n.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#ge&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`);this.#ge||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#Oe(){if(this.#me)return;this.#me=document.createElement("div");this.#me.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.#me.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#Ne.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#me)}#Ne(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;this.#fe=[e.screenX,e.screenY];const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#Be.bind(this,t),{passive:!0,capture:!0,signal:a});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:a});window.addEventListener("contextmenu",noContextMenu,{signal:a});this.#be={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 pointerUpCallback=()=>{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",pointerUpCallback,{signal:a});window.addEventListener("blur",pointerUpCallback,{signal:a})}#ze(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.#be)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#be;this.#be=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.#ze.bind(this,n,a,r,o),undo:this.#ze.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Be(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/s,d=this.#Le(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#Le(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(r,o),b=p(r,o);let A=transf(...b);const w=AnnotationEditor._round(n+A[0]),v=AnnotationEditor._round(a+A[1]);let y,x,_=1,E=1;if(e.fromKeyboard)({deltaX:y,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#fe;[y,x]=this.screenToPageTranslation(t-s,i-n);this.#fe[0]=t;this.#fe[1]=i}[y,x]=(S=y/i,C=x/s,[c[0]*S+c[2]*C,c[1]*S+c[3]*C]);var S,C;if(g){const t=Math.hypot(r,o);_=E=Math.max(Math.min(Math.hypot(b[0]-f[0]-y,b[1]-f[1]-x)/t,1/r,1/o),l/r,h/o)}else m?_=Math.max(l,Math.min(1,Math.abs(b[0]-f[0]-y)))/r:E=Math.max(h,Math.min(1,Math.abs(b[1]-f[1]-x)))/o;const T=AnnotationEditor._round(r*_),M=AnnotationEditor._round(o*E);A=transf(...p(T,M));const P=w-A[0],D=v-A[1];this.#ye||=[this.x,this.y,this.width,this.height];this.width=T;this.height=M;this.x=P;this.y=D;this.setDims(i*T,s*M);this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){if(this._editToolbar||this.#_e)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());this.#o&&await this._editToolbar.addAltText(this.#o);return this._editToolbar}removeEditToolbar(){if(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(){if(!this.#o){AltText.initialize(AnnotationEditor._l10n);this.#o=new AltText(this);if(this.#he){this.#o.data=this.#he;this.#he=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(){this.div=document.createElement("div");this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360);this.div.className=this.name;this.div.setAttribute("id",this.id);this.div.tabIndex=this.#ce?-1:0;this._isVisible||this.div.classList.add("hidden");this.setInForeground();this.#Ue();const[t,e]=this.parentDimensions;if(this.parentRotation%180!=0){this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`;this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`}const[i,s]=this.getInitialTranslation();this.translate(i,s);bindEvents(this,this.div,["pointerdown"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Pe||=new TouchManager({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ge.bind(this),onPinching:this.#$e.bind(this),onPinchEnd:this.#Ve.bind(this),signal:this._uiManager._signal}));this._uiManager._editorUndoBar?.hide();return this.div}#Ge(){this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#o?.toggle(!1);this.parent.togglePointerEvents(!1)}#$e(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#Le(this.rotation),transf=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[a,r]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/a,u=AnnotationEditor.MIN_SIZE/r;s=Math.max(Math.min(s,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*s),g=AnnotationEditor._round(d*s);if(p===h&&g===d)return;this.#ye||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),A=transf(p/2,g/2);this.x=f-A[0];this.y=b-A[1];this.width=p;this.height=g;this.setDims(a*p,r*g);this.fixAndSetPosition();this._onResizing()}#Ve(){this.#o?.toggle(!0);this.parent.togglePointerEvents(!0);this.#He()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#ve=!0;this._isDraggable?this.#je(t):this.#We(t)}}get isSelected(){return this._uiManager.isSelected(this)}#We(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#je(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},cancelDrag=t=>{s.abort();this.#ue=null;this.#ve=!1;this._uiManager.endDragSession()||this.#We(t);i&&this._onStopDragging()};if(e){this.#Ce=t.clientX;this.#Te=t.clientY;this.#ue=t.pointerId;this.#pe=t.pointerType;window.addEventListener("pointermove",(t=>{if(!i){i=!0;this._onStartDragging()}const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#ue){stopEvent(t);return}const[a,r]=this.screenToPageTranslation(e-this.#Ce,s-this.#Te);this.#Ce=e;this.#Te=s;this._uiManager.dragSelectedEditors(a,r)}),a);window.addEventListener("touchmove",stopEvent,a);window.addEventListener("pointerdown",(t=>{t.pointerType===this.#pe&&(this.#Pe||t.isPrimary)&&cancelDrag(t);stopEvent(t)}),a)}const pointerUpCallback=t=>{this.#ue&&this.#ue!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Se&&clearTimeout(this.#Se);this.#Se=setTimeout((()=>{this.#Se=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,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-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(){this.#_e=!0}disableEditMode(){this.#_e=!1}isInEditMode(){return this.#_e}shouldGetKeyboardEvents(){return this.#Ee}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 e0&&t0}#Ue(){if(this.#Ae||!this.div)return;this.#Ae=new AbortController;const t=this._uiManager.combinedSignal(this.#Ae);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#Ue()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){unreachable("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.#he=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);s.x=r/n;s.y=o/a;s.width=l/n;s.height=h/a;return s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#Ae?.abort();this.#Ae=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#Se){clearTimeout(this.#Se);this.#Se=null}this.#Re();this.removeEditToolbar();if(this.#Me){for(const t of this.#Me.values())clearTimeout(t);this.#Me=null}this.parent=null;this.#Pe?.destroy();this.#Pe=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#Oe();this.#me.classList.remove("hidden");bindEvents(this,this.div,["keydown"])}}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#me.children;if(!this.#de){this.#de=Array.from(e);const t=this.#qe.bind(this),i=this.#Xe.bind(this),s=this._uiManager._signal;for(const e of this.#de){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.#Ke.bind(this,n),{signal:s});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const i=this.#de[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#de.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#me?.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(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#xe}set isEditing(t){this.#xe=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}setAspectRatio(t,e){this.#ge=!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.#Me||=new Map;const{action:e}=t;let i=this.#Me.get(e);i&&clearTimeout(i);i=setTimeout((()=>{this._reportTelemetry(t);this.#Me.delete(e);0===this.#Me.size&&(this.#Me=null)}),AnnotationEditor._telemetryTimeout);this.#Me.set(e,i)}else{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.#ce=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#ce=!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 FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const st=3285377520,nt=4294901760,at=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:st;this.h2=t?4294967295&t:st}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let s=0,n=t.length;s>>8;e[i++]=255&n}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17;r=r*c&nt|r*p&at;l^=r;l=l<<13|l>>>19;l=5*l+3864292196}else{o=a[t];o=o*d&nt|o*u&at;o=o<<15|o>>>17;o=o*c&nt|o*p&at;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}r=0;switch(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*d&nt|r*u&at;r=r<<15|r>>>17;r=r*c&nt|r*p&at;1&s?l^=r:h^=r}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&nt|36045*t&at;e=4283543511*e&nt|(2950163797*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;t=444984403*t&nt|60499*t&at;e=3301882366*e&nt|(3120437893*(e<<16|t>>>16)&nt)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const rt=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Qe=!1;#Je=null;#Ze=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ze.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ze.get(t)}remove(t){this.#Ze.delete(t);0===this.#Ze.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#Ze.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ze.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#Ze.set(t,e)}s&&this.#ti();e instanceof AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ze.has(t)}getAll(){return this.#Ze.size>0?objectFromMap(this.#Ze):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ze.size}#ti(){if(!this.#Qe){this.#Qe=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#Qe){this.#Qe=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Ze.size)return rt;const t=new Map,e=new MurmurHash3_64,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ze){const r=a instanceof AnnotationEditor?a.serialize(!1,s):a;if(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}:rt}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ze.values()){if(!(i instanceof AnnotationEditor))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);if(!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.#Je=null}get modifiedIds(){if(this.#Je)return this.#Je;const t=[];for(const e of this.#Ze.values())e instanceof AnnotationEditor&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#Je={ids:new Set(t),hash:t.join(",")}}}class PrintAnnotationStorage extends AnnotationStorage{#ei;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#ei={map:n,hash:i,transfer:s}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ei}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#ii=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#ii.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#ii.has(t.loadedName)){assert(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load();this.#ii.add(i);e?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(a)}}else unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;(e||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0);return shadow(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAA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Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let i,s;const n=this._document.createElement("canvas");n.width=1;n.height=1;const a=n.getContext("2d");let r=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let d=int32(l,16);for(i=0,s=o.length-3;i>24&255,t>>16&255,t>>8&255,255&t)}(d));const c=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(c);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++r>30){warn("Load test font never loaded.");e();return}a.font="30px "+t;a.fillText(".",0,20);a.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,(()=>{u.remove();e.complete()}))}}class FontFaceObject{constructor(t,{disableFontFace:e=!1,fontExtraProperties:i=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e;this.fontExtraProperties=!0===i;this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}(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}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=n}}const ot=1,lt=2,ht=1,dt=2,ct=3,ut=4,pt=5,gt=6,mt=7,ft=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof MissingPDFException||t instanceof PasswordException||t instanceof UnexpectedResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"MissingPDFException":return new MissingPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"UnexpectedResponseException":return new UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#si=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.#ni.bind(this),{signal:this.#si.signal})}#ni({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#ai(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ot)i.resolve(t.data);else{if(t.callback!==lt)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:i,targetName:s,callback:ot,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:i,targetName:s,callback:lt,callbackId:t.callbackId,reason:wrapReason(e)})}))}else t.streamId?this.#ri(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();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);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;o.postMessage({sourceName:a,targetName:r,stream:gt,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=!0;o.postMessage({sourceName:a,targetName:r,stream:ht,streamId:n,reason:wrapReason(t)});return e.promise}},i)}#ri(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;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}n.postMessage({sourceName:i,targetName:s,stream:ut,streamId:e,chunk:t},r)},close(){if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:ct,streamId:e});delete a.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:pt,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(r,t.data,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,reason:wrapReason(t)})}))}#ai(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 ft:t.success?a.startCall.resolve():a.startCall.reject(wrapReason(t.reason));break;case mt:t.success?a.pullCall.resolve():a.pullCall.reject(wrapReason(t.reason));break;case gt:if(!r){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve();r.desiredSize=t.desiredSize;Promise.try(r.onPull||onFn).then((function(){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:mt,streamId:e,reason:wrapReason(t)})}));break;case ut:assert(a,"enqueue should have stream controller");if(a.isClosed)break;a.controller.enqueue(t.chunk);break;case ct:assert(a,"close should have stream controller");if(a.isClosed)break;a.isClosed=!0;a.controller.close();this.#oi(a,e);break;case pt:assert(a,"error should have stream controller");a.controller.error(wrapReason(t.reason));this.#oi(a,e);break;case dt:t.success?a.cancelCall.resolve():a.cancelCall.reject(wrapReason(t.reason));this.#oi(a,e);break;case ht:if(!r)break;const o=wrapReason(t.reason);Promise.try(r.onCancel||onFn,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:dt,streamId:e,reason:wrapReason(t)})}));r.sinkCapability.reject(o);r.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#oi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#si?.abort();this.#si=null}}class BaseCanvasFactory{#li=!1;constructor({enableHWA:t=!1}){this.#li=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.#li})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}e&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}const bt="Fill",At="Stroke",wt="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s);t.clip(n)}class BaseShadingPattern{getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_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===At||s===bt){const a=e.current.getClippedPathBoundingBox(s,getCurrentTransform(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=Util.transform(i,[1,0,0,1,a[0],a[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else{applyBoundingBox(t,this._bbox);n=this._createGradient(t)}return n}}function drawTriangle(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=a;a=r;r=u}if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=r;r=o;o=u}if(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,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,A=(l[n+1]+e.offsetY)*e.scaleY;if(g>=A)return;const w=h[a],v=h[a+1],y=h[a+2],x=h[r],_=h[r+1],E=h[r+2],S=h[o],C=h[o+1],T=h[o+2],M=Math.round(g),P=Math.round(A);let D,k,R,I,F,L,O,N;for(let t=M;t<=P;t++){if(tA?1:f===A?0:(f-t)/(f-A);D=m-(m-b)*e;k=x-(x-S)*e;R=_-(_-C)*e;I=E-(E-T)*e}let e;e=tA?1:(g-t)/(g-A);F=p-(p-b)*e;L=w-(w-S)*e;O=v-(v-C)*e;N=y-(y-T)*e;const i=Math.round(Math.min(D,F)),s=Math.round(Math.max(D,F));let n=c*t+4*i;for(let t=i;t<=s;t++){e=(D-t)/(D-F);e<0?e=0:e>1&&(e=1);d[n++]=k-(k-L)*e|0;d[n++]=R-(R-O)*e|0;d[n++]=I-(I-N)*e|0;d[n++]=255}}}function drawFigure(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=Math.ceil(p*b)?w=o:y=!0;E>=Math.ceil(g*A)?v=l:x=!0;const S=this.getSizeAndScale(w,this.ctx.canvas.width,b),C=this.getSizeAndScale(v,this.ctx.canvas.height,A),T=t.cachedCanvases.getCanvas("pattern",S.size,C.size),M=T.context,P=r.createCanvasGraphics(M);P.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(P,s,a);M.translate(-S.scale*h,-C.scale*d);P.transform(S.scale,0,0,C.scale,0,0);M.save();this.clipBbox(P,h,d,c,u);P.baseTransform=getCurrentTransform(P.ctx);P.executeOperatorList(i);P.endDrawing();M.restore();if(y||x){const e=T.canvas;y&&(w=o);x&&(v=l);const i=this.getSizeAndScale(w,this.ctx.canvas.width,b),s=this.getSizeAndScale(v,this.ctx.canvas.height,A),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=y?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.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:d}}return{canvas:T.canvas,scaleX:S.scale,scaleY:C.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);n>=s?n=s:i=n/t;return{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r);t.current.updateRectMinMax(getCurrentTransform(t.ctx),[e,i,s,n]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case vt:const t=this.ctx;s.fillStyle=t.fillStyle;s.strokeStyle=t.strokeStyle;n.fillColor=t.fillStyle;n.strokeColor=t.strokeStyle;break;case yt:const a=Util.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a;s.strokeStyle=a;n.fillColor=a;n.strokeColor=a;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;if(s!==wt){n=Util.transform(n,e.baseTransform);this.matrix&&(n=Util.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");o.setTransform(r);return o}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),m=i.length,f=s+7>>3,b=4294967295,A=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;uf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}}for(;l=a){g=n;m=s*g}l=0;for(p=m;p--;){c[l++]=d[h++];c[l++]=d[h++];c[l++]=d[h++];c[l++]=255}t.putImageData(o,0,u*xt)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,s=e.width,n=i%xt,a=(i-n)/xt,r=0===n?a:a+1,o=t.createImageData(s,xt);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint){s.breakIt(r,i);return r}p=a[r];if(p!==X.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t)){e.get(t,i);return r}}r++;if(r===o)return r;if(l&&++d>10){if(Date.now()>h){i();return r}d=0}}}#hi(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#hi();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,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;if(r>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);r/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}n=this.cachedCanvases.getCanvas(d,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;d="prescale1"===d?"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=getCurrentTransform(e);let o,l,h,d;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);if(!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}if(!h){d=this.cachedCanvases.getCanvas("maskCanvas",i,s);putBinaryImageMask(d.context,t)}let c=Util.transform(r,[1/i,0,0,-1/s,0,0]);c=Util.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=Util.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,A=this.cachedCanvases.getCanvas("fillCanvas",f,b),w=A.context,v=u,y=p;w.translate(-v,-y);w.transform(...c);if(!h){h=this._scaleImage(d.canvas,getCurrentTransformInverse(w));h=h.img;o&&a&&o.set(l,h)}w.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(w),t.interpolate);drawImageAtIntegerCoords(w,h,0,0,h.width,h.height,0,0,i,s);w.globalCompositeOperation="source-in";const x=Util.transform(getCurrentTransformInverse(w),[1,0,0,1,-v,-y]);w.fillStyle=a?n.getPattern(e,this,x,bt):n;w.fillRect(0,0,i,s);if(o&&!a){this.cachedCanvases.delete("fillCanvas");o.set(l,A.canvas)}return{canvas:A.canvas,offsetX:Math.round(v),offsetY:Math.round(y)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=_t[t]}setLineJoin(t){this.ctx.lineJoin=Et[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;if(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.current.fillAlpha=i;this.ctx.globalAlpha=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;this.ctx=s.context;const n=this.ctx;n.setTransform(...getCurrentTransform(this.suspendedCtx));copyCtxState(this.suspendedCtx,n);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function ctxScale(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function ctxTransform(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 ctxSetTransform(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 ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(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"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;if(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,d){let c=t.canvas,u=o-h,p=l-d;if(a){const e=Util.makeHexColor(...a);if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),n=t.context;n.drawImage(c,-u,-p);n.globalCompositeOperation="destination-atop";n.fillStyle=e;n.fillRect(0,0,i,s);n.globalCompositeOperation="source-over";c=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const n=new Path2D;n.rect(u,p,i,s);t.clip(n);t.globalCompositeOperation="destination-atop";t.fillStyle=e;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(c,u,p,i,s,o,l,i,s);e.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}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){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=getCurrentTransform(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100);this.current.fontSizeScale=e/h;this.ctx.font=`${l} ${o} ${h}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t;this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e);this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a];this.current.textMatrixScale=Math.hypot(t,e);this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#ci(t,e,i){const s=new Path2D;s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return 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,d=l&y,c=!!(l&x),u=r.patternFill&&!o.missingFile,p=r.patternStroke&&!o.missingFile;let g;(o.disableFontFace||c||u||p)&&(g=o.getPathGenerator(this.commonObjs,t));if(o.disableFontFace||u||p){a.save();a.translate(e,i);a.scale(h,-h);if(d===b||d===w)if(s){const t=a.getTransform();a.setTransform(...s);a.fill(this.#ci(g,t,s))}else a.fill(g);if(d===A||d===w)if(n){const t=a.getTransform();a.setTransform(...n);a.stroke(this.#ci(g,t,n))}else{a.lineWidth/=h;a.stroke(g)}a.restore()}else{d!==b&&d!==w||a.fillText(t,e,i);d!==A&&d!==w||a.strokeText(t,e,i)}if(c){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(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;t0&&e[t]<255){i=!0;break}return shadow(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,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=e.textRenderingMode===b&&!i.disableFontFace&&!e.patternFill;n.save();n.transform(...e.textMatrix);n.translate(e.x,e.y+e.textRise);l>0?n.scale(h,-1):n.scale(h,1);let f,v;if(e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,getCurrentTransformInverse(n),bt);f=getCurrentTransform(n);n.restore();n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,getCurrentTransformInverse(n),At);v=getCurrentTransform(n);n.restore();n.strokeStyle=t}let x=e.lineWidth;const _=e.textMatrixScale;if(0===_||0===x){const t=e.textRenderingMode&y;t!==A&&t!==w||(x=this.getSinglePixelWidth())}else x/=_;if(1!==a){n.scale(a,a);x/=a}n.lineWidth=x;if(i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t){i.push(e.unicode);s+=e.width}n.fillText(i.join(""),0,0);e.x+=s*g*h;n.restore();this.compose();return}let E,S=0;for(E=0;E0){const t=1e3*n.measureText(b).width/s*a;if(xnew CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new TilingPattern(t,i,this.ctx,n,s)}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,e,i){this.ctx.strokeStyle=this.current.strokeColor=Util.makeHexColor(t,e,i);this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=Util.makeHexColor(t,e,i);this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e=null){let i;if(this.cachedPatterns.has(t))i=this.cachedPatterns.get(t);else{i=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t));this.cachedPatterns.set(t,i)}e&&(i.matrix=e);return i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,getCurrentTransformInverse(e),wt);const s=getCurrentTransformInverse(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=Util.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);t&&this.transform(...t);this.baseTransform=getCurrentTransform(this.ctx);if(e){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i);this.current.updateRectMinMax(getCurrentTransform(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||info("TODO: Support non-isolated groups.");t.knockout&&warn("Knockout groups not supported.");const i=getCurrentTransform(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let s=Util.getAxialAlignedBoundingBox(t.bbox,getCurrentTransform(e));const n=[0,0,e.canvas.width,e.canvas.height];s=Util.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 d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r);c.transform(...i);if(t.smask)this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(a,r);e.save()}copyCtxState(e,c);this.ctx=c;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();this.ctx=i;this.ctx.imageSmoothingEnabled=!1;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=getCurrentTransform(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const i=Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(i)}}beginAnnotation(t,e,i,s,n){this.#hi();resetCtxToDefault(this.ctx);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(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;const[n,r]=Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d);this.annotationCanvas.savedCtx=this.ctx;this.ctx=c;this.ctx.save();this.ctx.setTransform(n,0,0,-r,0,a*r);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath();this.ctx.rect(e[0],e[1],s,a);this.ctx.clip();this.ctx.beginPath()}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...i);this.transform(...s)}endAnnotation(){if(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.processingType3;if(s){void 0===s.compiled&&(s.compiled=function compileType3Glyph(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;){d[c++]=e&t?0:255;t>>=1}}let u=0;c=0;if(0!==d[c]){l[0]=1;++u}for(r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0);if(s[t]){l[o+r]=s[t];++u}c++}if(d[c-h]!==d[c]){l[o+r]=d[c]?2:4;++u}if(u>1e3)return null}c=h*(i-1);o=a*n;if(0!==d[c]){l[o]=8;++u}for(r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4;l[t]&=r>>2|r<<2}g.lineTo(t%n,t/n|0);l[t]||--u}while(s!==t);--a}d=null;l=null;return function(t){t.save();t.scale(1/e,-1/i);t.translate(0,-i);t.fill(g);t.beginPath();t.restore()}}(t));if(s.compiled){s.compiled(i);return}}const n=this._createMaskCanvas(t),a=n.canvas;i.save();i.setTransform(1,0,0,1,0,0);i.drawImage(a,n.offsetX,n.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=getCurrentTransform(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;te?h/e:1;r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a;this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();e.lineWidth=i||1;if(1===s&&1===n){e.stroke();return}const a=e.getLineDash();t&&e.save();e.scale(s,n);if(a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t)));e.lineDashOffset/=t}e.stroke();t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in X)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[X[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#ui=null;static#pi="";static get workerPort(){return this.#ui}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#ui=t}static get workerSrc(){return this.#pi}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#pi=t}}class Metadata{#gi;#mi;constructor({parsedData:t,rawData:e}){this.#gi=t;this.#mi=e}getRaw(){return this.#mi}get(t){return this.#gi.get(t)??null}getAll(){return objectFromMap(this.#gi)}has(t){return this.#gi.has(t)}}const Tt=Symbol("INTERNAL");class OptionalContentGroup{#fi=!1;#bi=!1;#Ai=!1;#wi=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#fi=!!(t&r);this.#bi=!!(t&o);this.name=e;this.intent=i;this.usage=s;this.rbGroups=n}get visible(){if(this.#Ai)return this.#wi;if(!this.#wi)return!1;const{print:t,view:e}=this.usage;return this.#fi?"OFF"!==e?.viewState:!this.#bi||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Tt&&unreachable("Internal method `_setVisible` called.");this.#Ai=i;this.#wi=e}}class OptionalContentConfig{#vi=null;#yi=new Map;#xi=null;#_i=null;constructor(t,e=r){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#_i=t.order;for(const i of t.groups)this.#yi.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#yi.values())t._setVisible(Tt,!1);for(const e of t.on)this.#yi.get(e)._setVisible(Tt,!0);for(const e of t.off)this.#yi.get(e)._setVisible(Tt,!1);this.#xi=this.getHash()}}#Ei(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?objectFromMap(this.#yi):null}getGroup(t){return this.#yi.get(t)||null}getHash(){if(null!==this.#vi)return this.#vi;const t=new MurmurHash3_64;for(const[e,i]of this.#yi)t.update(`${e}:${i.visible}`);return this.#vi=t.hexdigest()}}class PDFDataTransportStream{constructor(t,{disableRange:e=!1,disableStream:i=!1}){assert(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;this._queuedChunks=[];this._progressiveDone=a;this._contentDispositionFilename=r;if(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{assert(this._rangeReaders.some((function(e){if(e._begin!==t)return!1;e._enqueue(i);return!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(){assert(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,i=!1,s=null){this._stream=t;this._done=i||!1;this._filename=isPdfFile(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();this._requests.push(t);return 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 PDFDataTransportStreamRangeReader{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;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._removeRangeReader(this)}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function getResponseOrigin(t){try{return new URL(t).origin}catch{}return null}function validateRangeRequestCapabilities({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;n.suggestedLength=a;if(a<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;if("identity"!==(t.get("Content-Encoding")||"identity"))return n;n.allowRangeRequests=!0;return n}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const s=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,s,n]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[s,n]}const n=[];for(let t=0;t{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,s);this._reader=e.body.getReader();this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n;this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(i);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("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();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{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,createFetchOptions(n,this._withCredentials,this._abortController)).then((e=>{const i=getResponseOrigin(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseStatusError(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();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(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);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);s.expectedStatus=206}else s.expectedStatus=200;e.responseType="arraybuffer";assert(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);return 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}if(4!==s.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===s.status&&this.isHttp){i.onError(s.status);return}const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus){i.onError(s.status);return}const a=function network_getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:stringToBytes(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)i.onDone({begin:parseInt(e[1],10),chunk:a});else{warn('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 PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(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(){assert(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const i=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);i.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{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=getResponseOrigin(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}=validateRangeRequestCapabilities({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0);this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(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);this._done=!0;if(!(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=createResponseStatusError(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(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);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 PDFNetworkStreamRangeRequestReader{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=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(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??=createResponseStatusError(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;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;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 Mt=/^[a-z][a-z0-9\-+.]+:/i;class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrlOrPath(t){if(Mt.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{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=new MissingPDFException(`Missing PDF "${this._url}".`));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(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return 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 AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{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(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return 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 Pt=30;class TextLayer{#Si=Promise.withResolvers();#pt=null;#Ci=!1;#Ti=!!globalThis.FontInspector?.enabled;#Mi=null;#Pi=null;#Di=0;#ki=0;#Ri=null;#Ii=null;#Fi=0;#Li=0;#Oi=Object.create(null);#Ni=[];#Bi=null;#Hi=[];#zi=new WeakMap;#Ui=null;static#Gi=new Map;static#$i=new Map;static#Vi=new WeakMap;static#ji=null;static#Wi=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#Bi=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Bi=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#pt=this.#Ii=e;this.#Li=i.scale*(globalThis.devicePixelRatio||1);this.#Fi=i.rotation;this.#Pi={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#Ui=[1,0,0,-1,-a,r+n];this.#ki=s;this.#Di=n;TextLayer.#qi();setLayerDimensions(e,i);this.#Si.promise.finally((()=>{TextLayer.#Wi.delete(this);this.#Pi=null;this.#Oi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Ri.read().then((({value:t,done:e})=>{if(e)this.#Si.resolve();else{this.#Mi??=t.lang;Object.assign(this.#Oi,t.styles);this.#Xi(t.items);pump()}}),this.#Si.reject)};this.#Ri=this.#Bi.getReader();TextLayer.#Wi.add(this);pump();return this.#Si.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#Fi){e?.();this.#Fi=s;setLayerDimensions(this.#Ii,{rotation:s})}if(i!==this.#Li){e?.();this.#Li=i;const t={div:null,properties:null,ctx:TextLayer.#Ki(this.#Mi)};for(const e of this.#Hi){t.properties=this.#zi.get(e);t.div=e;this.#Yi(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Ri?.cancel(t).catch((()=>{}));this.#Ri=null;this.#Si.reject(t)}get textDivs(){return this.#Hi}get textContentItemsStr(){return this.#Ni}#Xi(t){if(this.#Ci)return;this.#Pi.ctx??=TextLayer.#Ki(this.#Mi);const e=this.#Hi,i=this.#Ni;for(const s of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Ci=!0;return}if(void 0!==s.str){i.push(s.str);this.#Qi(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#pt;this.#pt=document.createElement("span");this.#pt.classList.add("markedContent");null!==s.id&&this.#pt.setAttribute("id",`${s.id}`);t.append(this.#pt)}else"endMarkedContent"===s.type&&(this.#pt=this.#pt.parentNode)}}#Qi(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Hi.push(e);const s=Util.transform(this.#Ui,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#Oi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Ti&&a.fontSubstitution||a.fontFamily;r=TextLayer.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*TextLayer.#Ji(r,this.#Mi);let h,d;if(0===n){h=s[4];d=s[5]-l}else{h=s[4]+l*Math.sin(n);d=s[5]-l*Math.cos(n)}const c="calc(var(--scale-factor)*",u=e.style;if(this.#pt===this.#Ii){u.left=`${(100*h/this.#ki).toFixed(2)}%`;u.top=`${(100*d/this.#Di).toFixed(2)}%`}else{u.left=`${c}${h.toFixed(2)}px)`;u.top=`${c}${d.toFixed(2)}px)`}u.fontSize=`${c}${(TextLayer.#ji*o).toFixed(2)}px)`;u.fontFamily=r;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ti&&(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)}p&&(i.canvasWidth=a.vertical?t.height:t.width);this.#zi.set(e,i);this.#Pi.div=e;this.#Pi.properties=i;this.#Yi(this.#Pi);i.hasText&&this.#pt.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#pt.append(t)}}#Yi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";TextLayer.#ji>1&&(a=`scale(${1/TextLayer.#ji})`);if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;TextLayer.#Zi(s,o*this.#Li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#Li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`);a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Wi.size>0)){this.#Gi.clear();for(const{canvas:t}of this.#$i.values())t.remove();this.#$i.clear()}}static#Ki(t=null){let e=this.#$i.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.#$i.set(t,e);this.#Vi.set(e,{size:0,family:""})}return e}static#Zi(t,e,i){const s=this.#Vi.get(t);if(e!==s.size||i!==s.family){t.font=`${e}px ${i}`;s.size=e;s.family=i}}static#qi(){if(null!==this.#ji)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.#ji=t.getBoundingClientRect().height;t.remove()}static#Ji(t,e){const i=this.#Gi.get(t);if(i)return i;const s=this.#Ki(e);s.canvas.width=s.canvas.height=Pt;this.#Zi(s,Pt,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);this.#Gi.set(t,e);s.canvas.width=s.canvas.height=0;return e}s.strokeStyle="red";s.clearRect(0,0,Pt,Pt);s.strokeText("g",0,0);let o=s.getImageData(0,0,Pt,Pt).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Pt);break}s.clearRect(0,0,Pt,Pt);s.strokeText("A",0,Pt);o=s.getImageData(0,0,Pt,Pt).data;a=0;for(let t=0,e=o.length;t0){a=Pt-Math.floor(t/4/Pt);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;this.#Gi.set(t,l);return l}}class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Dt=65536,kt=e?class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}:class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}},Rt=e?class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMCMapReaderFactory,It=e?class NodeFilterFactory extends BaseFilterFactory{}:class DOMFilterFactory extends BaseFilterFactory{#ts;#es;#is;#ss;#ns;#as;#w=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#ss=t;this.#ns=e}get#y(){return this.#es||=new Map}get#rs(){return this.#as||=new Map}get#os(){if(!this.#is){const t=this.#ns.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.#ns.createElementNS(it,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#is=this.#ns.createElementNS(it,"defs");t.append(i);i.append(this.#is);this.#ns.body.append(t)}return this.#is}#ls(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(",")]}#hs(t){if(void 0===this.#ts){this.#ts="";const t=this.#ns.URL;t!==this.#ns.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#ts=t.split("#",1)[0])}return`url(${this.#ts}#${t})`}addFilter(t){if(!t)return"none";let e=this.#y.get(t);if(e)return e;const[i,s,n]=this.#ls(t),a=1===t.length?i:`${i}${s}${n}`;e=this.#y.get(a);if(e){this.#y.set(t,e);return e}const r=`g_${this.#ss}_transfer_map_${this.#w++}`,o=this.#hs(r);this.#y.set(t,o);this.#y.set(a,o);const l=this.#ds(r);this.#cs(i,s,n,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#rs.get(s);if(n?.key===i)return n.url;if(n){n.filter?.remove();n.key=i;n.url="none";n.filter=null}else{n={key:i,url:"none",filter:null};this.#rs.set(s,n)}if(!t||!e)return n.url;const a=this.#us(t);t=Util.makeHexColor(...a);const r=this.#us(e);e=Util.makeHexColor(...r);this.#os.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#ss}_hcm_filter`,d=n.filter=this.#ds(h);this.#cs(l,l,l,d);this.#ps(d);const getSteps=(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(",")};this.#cs(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);n.url=this.#hs(h);return n.url}addAlphaFilter(t){let e=this.#y.get(t);if(e)return e;const[i]=this.#ls([t]),s=`alpha_${i}`;e=this.#y.get(s);if(e){this.#y.set(t,e);return e}const n=`g_${this.#ss}_alpha_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(s,a);const r=this.#ds(n);this.#gs(i,r);return a}addLuminosityFilter(t){let e,i,s=this.#y.get(t||"luminosity");if(s)return s;if(t){[e]=this.#ls([t]);i=`luminosity_${e}`}else i="luminosity";s=this.#y.get(i);if(s){this.#y.set(t,s);return s}const n=`g_${this.#ss}_luminosity_map_${this.#w++}`,a=this.#hs(n);this.#y.set(t,a);this.#y.set(i,a);const r=this.#ds(n);this.#ms(r);t&&this.#gs(e,r);return a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#rs.get(t);if(r?.key===a)return r.url;if(r){r.filter?.remove();r.key=a;r.url="none";r.filter=null}else{r={key:a,url:"none",filter:null};this.#rs.set(t,r)}if(!e||!i)return r.url;const[o,l]=[e,i].map(this.#us.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#us.bind(this));d{const s=new Array(256),n=(d-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(",")},p=`g_${this.#ss}_hcm_${t}_filter`,g=r.filter=this.#ds(p);this.#ps(g);this.#cs(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);r.url=this.#hs(p);return r.url}destroy(t=!1){if(!t||!this.#as?.size){this.#is?.parentNode.parentNode.remove();this.#is=null;this.#es?.clear();this.#es=null;this.#as?.clear();this.#as=null;this.#w=0}}#ms(t){const e=this.#ns.createElementNS(it,"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)}#ps(t){const e=this.#ns.createElementNS(it,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#ds(t){const e=this.#ns.createElementNS(it,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#os.append(e);return e}#fs(t,e,i){const s=this.#ns.createElementNS(it,e);s.setAttribute("type","discrete");s.setAttribute("tableValues",i);t.append(s)}#cs(t,e,i,s){const n=this.#ns.createElementNS(it,"feComponentTransfer");s.append(n);this.#fs(n,"feFuncR",t);this.#fs(n,"feFuncG",e);this.#fs(n,"feFuncB",i)}#gs(t,e){const i=this.#ns.createElementNS(it,"feComponentTransfer");e.append(i);this.#fs(i,"feFuncA",t)}#us(t){this.#os.style.color=t;return getRGB(getComputedStyle(this.#os).getPropertyValue("color"))}},Ft=e?class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMStandardFontDataFactory;function getDocument(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const i=new PDFDocumentLoadingTask,{docId:s}=i,n=t.url?function getUrlProp(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(e&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function getDataProp(t){if(e&&"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 stringToBytes(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,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof PDFDataRangeTransport?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:Dt;let c=t.worker instanceof PDFWorker?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||isDataScheme(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||Rt,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,A=t.StandardFontDataFactory||Ft,w=!0!==t.stopAtErrors,v=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,y=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!e,_="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!e&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),E=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,S="boolean"==typeof t.disableFontFace?t.disableFontFace:e,C=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,P=!0===t.disableRange,D=!0===t.disableStream,k=!0===t.disableAutoFetch,R=!0===t.pdfBug,I=t.CanvasFactory||kt,F=t.FilterFactory||It,L=!0===t.enableHWA,O=h?h.length:t.length??NaN,N="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!e&&!S,B="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===DOMCMapReaderFactory&&A===DOMStandardFontDataFactory&&g&&b&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(b,document.baseURI);setVerbosityLevel(u);const H={canvasFactory:new I({ownerDocument:M,enableHWA:L}),filterFactory:new F({docId:s,ownerDocument:M}),cMapReaderFactory:B?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:B?null:new A({baseUrl:b})};if(!c){const t={verbosity:u,port:GlobalWorkerOptions.workerPort};c=t.port?PDFWorker.fromPort(t):new PDFWorker(t);i._worker=c}const z={docId:s,apiVersion:"4.10.38",data:a,password:l,disableAutoFetch:k,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:v,disableFontFace:S,ignoreErrors:w,isEvalSupported:y,isOffscreenCanvasSupported:x,isImageDecoderSupported:_,canvasMaxAreaInBytes:E,fontExtraProperties:C,useSystemFonts:N,cMapUrl:B?g:null,standardFontDataUrl:B?b:null}},U={disableFontFace:S,fontExtraProperties:C,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:k,enableXfa:T}};c.promise.then((function(){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",z,a?[a.buffer]:null);let l;if(h)l=new PDFDataTransportStream(h,{disableRange:P,disableStream:D});else if(!a){if(!n)throw new Error("getDocument - no `url` parameter provided.");let t;if(e)if(isValidFetchUrl(n)){if("undefined"==typeof fetch||"undefined"==typeof Response||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");t=PDFFetchStream}else t=PDFNodeStream;else t=isValidFetchUrl(n)?PDFFetchStream:PDFNetworkStream;l=new t({url:n,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:P,disableStream:D})}return t.then((t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(s,t,c.port),n=new WorkerTransport(e,i,l,U,H);i._transport=n;e.send("Ready",null)}))})).catch(i._capability.reject);return i}function isRefProxy(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class PDFDocumentLoadingTask{static#ss=0;constructor(){this._capability=Promise.withResolvers();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#ss++;this.destroyed=!1;this.onPassword=null;this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}}class PDFDataRangeTransport{constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{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 shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}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 PDFPageProxy{#bs=null;#As=!1;constructor(t,e,i,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._maybeCleanupAfterRender=!1;this._intentStates=new Map;this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=p.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:g,cacheKey:m}=u;this.#As=!1;this.#ws();r||=this._transport.getOptionalContentConfig(g);let f=this._intentStates.get(m);if(!f){f=Object.create(null);this._intentStates.set(m,f)}if(f.streamReaderCancelTimeout){clearTimeout(f.streamReaderCancelTimeout);f.streamReaderCancelTimeout=null}const b=!!(g&o);if(!f.displayReadyCapability){f.displayReadyCapability=Promise.withResolvers();f.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(u)}const complete=t=>{f.renderTasks.delete(A);(this._maybeCleanupAfterRender||b)&&(this.#As=!0);this.#vs(!b);if(t){A.capability.reject(t);this._abortOperatorList({intentState:f,reason:t instanceof Error?t:new Error(t)})}else A.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},A=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:f.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:h});(f.renderTasks||=new Set).add(A);const w=A.task;Promise.all([f.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&g))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:t,optionalContentConfig:e});A.operatorListChanged()}})).catch(complete);return w}getOperatorList({intent:t="display",annotationMode:e=p.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);if(!r){r=Object.create(null);this._intentStates.set(n.cacheKey,r)}if(!r.opListReadCapability){a=Object.create(null);a.operatorListChanged=function operatorListChanged(){if(r.operatorList.lastChunk){r.opListReadCapability.resolve(r.operatorList);r.renderTasks.delete(a)}};r.opListReadCapability=Promise.withResolvers();(r.renderTasks||=new Set).add(a);r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(n)}return r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{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=>XfaText.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 pump(){s.read().then((function({value:e,done:i}){if(i)t(n);else{n.lang??=e.lang;Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#As=!1;this.#ws();return Promise.all(t)}cleanup(t=!1){this.#As=!0;const e=this.#vs(!1);t&&e&&(this._stats&&=new StatTimer);return e}#vs(t=!1){this.#ws();if(!this.#As||this.destroyed)return!1;if(t){this.#bs=setTimeout((()=>{this.#bs=null;this.#vs(!1)}),5e3);return!1}for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#As=!1;return!0}#ws(){if(this.#bs){clearTimeout(this.#bs);this.#bs=null}}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}}),(t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#vs(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),i);return}}t.streamReader.cancel(new AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class LoopbackPort{#ys=new Map;#xs=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#xs.then((()=>{for(const[t]of this.#ys)t.call(this,i)}))}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#ys.set(e,s)}removeEventListener(t,e){const i=this.#ys.get(e);i?.();this.#ys.delete(e)}terminate(){for(const[,t]of this.#ys)t?.();this.#ys.clear()}}class PDFWorker{static#_s=0;static#Es=!1;static#Ss;static{if(e){this.#Es=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{let i;try{i=new URL(t);if(!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;this._readyCapability=Promise.withResolvers();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#Ss?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(PDFWorker.#Ss||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}#Cs(){this._readyCapability.resolve();this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t;this._messageHandler=new MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this.#Cs()}_initialize(){if(PDFWorker.#Es||PDFWorker.#Ts){this._setupFakeWorker();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location.href,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{s.abort();i.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},s=new AbortController;e.addEventListener("error",(()=>{this._webWorker||terminateEarly()}),{signal:s.signal});i.on("test",(t=>{s.abort();if(!this.destroyed&&t){this._messageHandler=i;this._port=e;this._webWorker=e;this.#Cs()}else terminateEarly()}));i.on("ready",(t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorker.#Es){warn("Setting up fake worker.");PDFWorker.#Es=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const i="fake"+PDFWorker.#_s++,s=new MessageHandler(i+"_worker",i,e);t.setup(s,e);this._messageHandler=new MessageHandler(i,i+"_worker",e);this.#Cs()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;this._webWorker?.terminate();this._webWorker=null;PDFWorker.#Ss?.delete(this._port);this._port=null;this._messageHandler?.destroy();this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ss?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Ts)return this.#Ts;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{#Ms=new Map;#Ps=new Map;#Ds=new Map;#ks=new Map;#Rs=null;constructor(t,e,i,s,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({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.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.setupMessageHandler()}#Is(t,e=null){const i=this.#Ms.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);this.#Ms.set(t,s);return s}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=p.ENABLE,i=null,s=!1,n=!1){let g=r,m=rt;switch(t){case"any":g=a;break;case"display":break;case"print":g=o;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&o&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case p.DISABLE:g+=d;break;case p.ENABLE:break;case p.ENABLE_FORMS:g+=l;break;case p.ENABLE_STORAGE:g+=h;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(g+=c);n&&(g+=u);const{ids:b,hash:A}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,A].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Rs?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Ps.values())t.push(e._destroy());this.#Ps.clear();this.#Ds.clear();this.#ks.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy();TextLayer.cleanup();this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{assert(this._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}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._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;if(!i||!s){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:i,isRangeSupported:s,contentLength:n}}));t.on("GetRangeReader",((t,e)=>{assert(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{i.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(t=>{e._capability.reject(wrapReason(t))}));t.on("PasswordRequest",(t=>{this.#Rs=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Rs.reject(t):this.#Rs.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Rs.reject(t)}return this.#Rs.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.#Ps.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":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new FontFaceObject(s,{disableFontFace:n,fontExtraProperties:a,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null);this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;assert(h,"The imageRef must be defined.");for(const t of this.#Ps.values())for(const[,i]of t.objs)if(i?.ref===h){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}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.#Ps.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s);s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;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("FetchBuiltInCMap",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(t)}));t.on("FetchStandardFontData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._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.#Ds.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.#ks.set(i.refStr,t);const s=new PDFPageProxy(e,i,this,this._params.pdfBug);this.#Ps.set(e,s);return s}));this.#Ds.set(e,s);return s}getPageIndex(t){return isRefProxy(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.#Is("GetFieldObjects")}hasJSActions(){return this.#Is("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.#Is("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.#Is("GetOptionalContentConfig").then((e=>new OptionalContentConfig(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Ms.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#Ms.set(t,i);return 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.#Ps.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ks.get(e)??null}}const Lt=Symbol("INITIAL_DATA");class PDFObjects{#Fs=Object.create(null);#Ls(t){return this.#Fs[t]||={...Promise.withResolvers(),data:Lt}}get(t,e=null){if(e){const i=this.#Ls(t);i.promise.then((()=>e(i.data)));return null}const i=this.#Fs[t];if(!i||i.data===Lt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Fs[t];return!!e&&e.data!==Lt}delete(t){const e=this.#Fs[t];if(!e||e.data===Lt)return!1;delete this.#Fs[t];return!0}resolve(t,e=null){const i=this.#Ls(t);i.data=e;i.resolve()}clear(){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e?.bitmap?.close()}this.#Fs=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e!==Lt&&(yield[t,e])}}}class RenderTask{#Os=null;constructor(t){this.#Os=t;this.onContinue=null}get promise(){return this.#Os.capability.promise}cancel(t=0){this.#Os.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Os.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Os;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Ns=null;static#Bs=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:d=!1,pageColors:c=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=d;this.pageColors=c;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Bs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Bs.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new CanvasGraphics(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();if(this.#Ns){window.cancelAnimationFrame(this.#Ns);this.#Ns=null}InternalRenderTask.#Bs.delete(this._canvas);this.callback(t||new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Ns=window.requestAnimationFrame((()=>{this.#Ns=null;this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Bs.delete(this._canvas);this.callback()}}}}}const Ot="4.10.38",Nt="f9bea397f";function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[scaleAndClamp(1-Math.min(1,t+s)),scaleAndClamp(1-Math.min(1,i+s)),scaleAndClamp(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(it,t)}}class XfaLayer{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":null!==a.value&&(t.textContent=a.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{null!==a.value&&t.setAttribute("value",a.value);if("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;o.append(a);if(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&&XfaText.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:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t);a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);a.append(c);o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i});if(o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&XfaText.shouldBuildText(d)&&l.push(t);c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const Bt=1e3,Ht=new WeakSet;function getRectDims(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case S:return new LinkAnnotationElement(t);case E:return new TextAnnotationElement(t);case U:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case H:return new PopupAnnotationElement(t);case C:return new FreeTextAnnotationElement(t);case T:return new LineAnnotationElement(t);case M:return new SquareAnnotationElement(t);case P:return new CircleAnnotationElement(t);case k:return new PolylineAnnotationElement(t);case N:return new CaretAnnotationElement(t);case B:return new InkAnnotationElement(t);case D:return new PolygonAnnotationElement(t);case R:return new HighlightAnnotationElement(t);case I:return new UnderlineAnnotationElement(t);case F:return new SquigglyAnnotationElement(t);case L:return new StrikeOutAnnotationElement(t);case O:return new StampAnnotationElement(t);case z:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Hs=null;#zs=!1;#Us=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 AnnotationElement._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Hs||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#Gs(e);this.#Us?.popup.updateEdited(t)}resetEdited(){if(this.#Hs){this.#Gs(this.#Hs.rect);this.#Us?.popup.resetEdited();this.#Hs=null}}#Gs(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);const{width:l,height:h}=getRectDims(t);e.left=100*(t[0]-r)/n+"%";e.top=100*(a-t[3]+o)/a+"%";if(0===s){e.width=100*l/n+"%";e.height=100*h/a+"%"}else this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||(n.tabIndex=Bt);const{style:a}=n;a.zIndex=this.parent.zIndex++;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,n);return n}const{width:r,height:o}=getRectDims(e.rect);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(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case G:a.borderStyle="solid";break;case $:a.borderStyle="dashed";break;case V:warn("Unimplemented border style: beveled");break;case j:warn("Unimplemented border style: inset");break;case W:a.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#zs=!0;a.borderColor=Util.makeHexColor(0|s[0],0|s[1],0|s[2])}else a.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%";a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){a.width=100*r/h+"%";a.height=100*o/d+"%"}else this.setRotation(p,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=getRectDims(this.data.rect);let r,o;if(t%180==0){r=100*n/i;o=100*a/s}else{r=100*a/i;o=100*n/s}e.style.width=`${r}%`;e.style.height=`${o}%`;e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=ColorConverters[`${n}_HTML`](a);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_rgb`](a)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const 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.#zs){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0;r=["url('data:image/svg+xml;utf8,",'',``];this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");c.append(u);for(let i=2,s=t.length;i`)}if(this.#zs){r.push("')");a.backgroundImage=r.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#Us=new PopupAnnotationElement({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(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues: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||Ht.has(r)?i.push({id:n,exportValue:s,domElement:r}):warn(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Ht.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})}))}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);s=!0}else if(t.action){this._bindNamedAction(i,t.action);s=!0}else if(t.attachment){this.#$s(i,t.attachment,t.attachmentDest);s=!0}else if(t.setOCGState){this.#Vs(i,t.setOCGState);s=!0}else if(t.dest){this._bindLink(i,t.dest);s=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);s=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);s=!0}else if(this.isTooltipOnly&&!s){this._bindLink(i,"");s=!0}}this.container.classList.add("linkAnnotation");s&&this.container.append(i);return this.container}#js(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#js()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};this.#js()}#$s(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);return!1};this.#js()}#Vs(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};this.#js()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}});return!1})}t.onclick||(t.onclick=()=>!1);this.#js()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#js();if(this._fieldObjects)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;o.push(e);switch(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&&(Ht.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)if("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":Util.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,a=t.style;let r;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(n*s))||1);r=Math.min(s,roundToOneDecimal(e/n))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(s,roundToOneDecimal(t/n))}a.fontSize=`calc(${r}px * var(--scale-factor))`;a.color=Util.makeHexColor(i[0],i[1],i[2]);null!==this.data.textAlignment&&(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const 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};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=r??n;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type="text";i.setAttribute("value",r??n);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);Ht.add(i);i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=Bt;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 blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;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){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",s);let a=o.userValue;if(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;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:s}=t.target;if(o.lastCommittedValue!==s){o.lastCommittedValue=s;o.userValue=s;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const s=blurListener;blurListener=null;i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{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))}blurListener&&i.addEventListener("blur",blurListener);if(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(--scale-factor) - 1ch)`}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof s){s="Off"!==s;t.setValue(i,{value:s})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");Ht.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=Bt;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}));if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s){s=s!==e.buttonValue;t.setValue(i,{value:s})}if(s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");Ht.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=Bt;n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}));if(this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e);t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Ht.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=Bt;let n=this.data.combo&&this.data.options.length>0;if(!this.data.combo){s.size=this.data.options.length;this.data.multiSelect&&(s.multiple=!0)}s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);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 getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let r=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,o=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1;s.remove(a);if(n.length>0){-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]});r=getValue(!1)},insert(i){const{index:n,displayValue:a,exportValue:o}=i.detail.insert,l=s.children[n],h=document.createElement("option");h.textContent=a;h.value=o;l?l.before(h):s.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e;n.value=i;s.append(n)}s.options.length>0&&(s.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)}));s.addEventListener("input",(i=>{const s=getValue(!0),n=getValue(!1);t.setValue(e,{value:s});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}));this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))}else s.addEventListener("input",(function(i){t.setValue(e,{value:getValue(!0)})}));this.data.combo&&this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:AnnotationElement._hasPopupData(e)});this.elements=i;this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new PopupElement({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()}this.container.setAttribute("aria-controls",e.map((t=>`${et}${t}`)).join(","));return this.container}}class PopupElement{#Ws=this.#qs.bind(this);#Xs=this.#Ks.bind(this);#Ys=this.#Qs.bind(this);#Js=this.#Zs.bind(this);#tn=null;#pt=null;#en=null;#in=null;#sn=null;#nn=null;#an=null;#rn=!1;#on=null;#C=null;#ln=null;#hn=null;#dn=null;#Hs=null;#cn=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#pt=t;this.#dn=s;this.#en=a;this.#hn=r;this.#nn=o;this.#tn=e;this.#ln=l;this.#an=h;this.#sn=i;this.#in=PDFDateString.toDateObject(n);this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger){t.addEventListener("click",this.#Js);t.addEventListener("mouseenter",this.#Ys);t.addEventListener("mouseleave",this.#Xs);t.classList.add("popupTriggerArea")}for(const t of i)t.container?.addEventListener("keydown",this.#Ws);this.#pt.hidden=!0;d&&this.#Zs()}render(){if(this.#on)return;const t=this.#on=document.createElement("div");t.className="popup";if(this.#tn){const e=t.style.outlineColor=Util.makeHexColor(...this.#tn);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=Util.makeHexColor(...this.#tn.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");e.append(i);({dir:i.dir,str:i.textContent}=this.#dn);t.append(e);if(this.#in){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.#in.valueOf()}));e.append(t)}const s=this.#un;if(s){XfaLayer.render({xfaHtml:s,intent:"richText",div:t});t.lastChild.classList.add("richText","popupContent")}else{const e=this._formatContents(this.#en);t.append(e)}this.#pt.append(t)}get#un(){const t=this.#hn,e=this.#en;return!t?.str||e?.str&&e.str!==t.str?null:this.#hn.html||null}get#pn(){return this.#un?.attributes?.style?.fontSize||0}get#gn(){return this.#un?.attributes?.style?.color||null}#mn(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#gn,fontSize:this.#pn?`calc(${this.#pn}px * var(--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=0&&n.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#xn.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Sn()}));!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#En}addHighlightArea(){this.container.classList.add("highlightArea")}#Sn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Cn=null;#Tn=null;#Mn=new Map;#Pn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t;this.#Cn=e;this.#Tn=i;this.#Pn=r||null;this.page=n;this.viewport=a;this.zIndex=0;this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Mn.size>0}async#Dn(t,e){const i=t.firstChild||t,s=i.id=`${et}${e}`,n=await(this.#Pn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t);this.#Cn?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(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 DOMSVGFactory,annotationStorage:t.annotationStorage||new AnnotationStorage,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===H;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=getRectDims(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=AnnotationElementFactory.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.#Dn(a,t.id);if(i._isEditable){this.#Mn.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}this.#kn()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#kn();e.hidden=!1}#kn(){if(!this.#Tn)return;const t=this.div;for(const[e,i]of this.#Tn){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)}this.#Tn.clear()}getEditableAnnotations(){return Array.from(this.#Mn.values())}getEditableAnnotation(t){return this.#Mn.get(t)}}const zt=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#tn;#Rn="";#In=`${this.id}-editor`;#Fn=null;#pn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=g.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.#tn=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#pn=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case m.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case m.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case m.FREETEXT_SIZE:this.#Ln(e);break;case m.FREETEXT_COLOR:this.#On(e)}}static get defaultPropertiesToUpdate(){return[[m.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[m.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[m.FREETEXT_SIZE,this.#pn],[m.FREETEXT_COLOR,this.#tn]]}#Ln(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`;this.translate(0,-(t-this.#pn)*this.parentScale);this.#pn=t;this.#Nn()},e=this.#pn;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#On(t){const setColor=t=>{this.#tn=this.editorDiv.style.color=t},e=this.#tn;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#pn)*t]}rebuild(){if(this.parent){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1);this.parent.updateToolbar(g.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#Fn=new AbortController;const t=this._uiManager.combinedSignal(this.#Fn);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t});this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t});this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t});this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t});this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){if(this.isInEditMode()){this.parent.setEditingState(!0);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#In);this._isDraggable=!0;this.#Fn?.abort();this.#Fn=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing")}}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#Bn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#Hn(i));e=i}return t.join("\n")}#Nn(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=s;e.classList.toggle("hidden",n)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Rn,e=this.#Rn=this.#Bn().trimEnd();if(t===e)return;const setText=t=>{this.#Rn=t;if(t){this.#zn();this._uiManager.rebuild(this);this.#Nn()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#Nn()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#In);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);bindEvents(this,this.div,["dblclick","keydown"]);if(this.width){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,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o;u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o;u=e-(n[1]-d)/l;[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-d-this.width*o)/l;[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#zn();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Hn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(zt,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=FreeTextEditor.#Un(e.getData("text")||"").replaceAll(zt,"\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")){a.insertNode(document.createTextNode(s));this.editorDiv.normalize();n.collapseToStart();return}const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;h.push(r.nodeValue.slice(o).replaceAll(zt,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Hn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(zt,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Hn(i))}}this.#Rn=`${l.join("\n")}${s}${h.join("\n")}`;this.#zn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c);d.setEnd(t,c);break}c-=e}n.removeAllRanges();n.addRange(d)}#zn(){this.editorDiv.replaceChildren();if(this.#Rn)for(const t of this.#Rn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Gn(){return this.#Rn.replaceAll(" "," ")}static#Un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:d}}}=t;if(!l||0===l.length)return null;s=t={annotationType:g.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);n.#pn=t.fontSize;n.#tn=Util.makeHexColor(...t.color);n.#Rn=FreeTextEditor.#Un(t.value);n.annotationElementId=t.id||null;n._initialData=s;return n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=FreeTextEditor._internalPadding*this.parentScale,i=this.getRect(e,e),s=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#tn),n={annotationType:g.FREETEXT,color:s,fontSize:this.#pn,value:this.#Gn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t)return n;if(this.annotationElementId&&!this.#$n(n))return null;n.id=this.annotationElementId;return n}#$n(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.#pn}px * var(--scale-factor))`;i.color=this.#tn;e.replaceChildren();for(const t of this.#Rn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}const s=FreeTextEditor._internalPadding*this.parentScale;t.updateEdited({rect:this.getRect(s,s),popupContent:this.#Rn});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#ha(i);return i.join(" ")}#oa(){const[t,e,i,s]=this.#Vn,[n,a,r,o]=this.#ra();return`M${(this.#Kn[2]-t)/i} ${(this.#Kn[3]-e)/s} L${(this.#Kn[4]-t)/i} ${(this.#Kn[5]-e)/s} L${n} ${a} L${r} ${o} L${(this.#Kn[16]-t)/i} ${(this.#Kn[17]-e)/s} L${(this.#Kn[14]-t)/i} ${(this.#Kn[15]-e)/s} Z`}#ha(t){const e=this.#jn;t.push(`L${e[4]} ${e[5]} Z`)}#la(t){const[e,i,s,n]=this.#Vn,a=this.#Kn.subarray(4,6),r=this.#Kn.subarray(16,18),[o,l,h,d]=this.#ra();t.push(`L${(a[0]-e)/s} ${(a[1]-i)/n} L${o} ${l} L${h} ${d} L${(r[0]-e)/s} ${(r[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,a){return new FreeDrawOutline(t,e,i,s,n,a)}getOutlines(){const t=this.#Xn,e=this.#jn,i=this.#Kn,[s,n,a,r]=this.#Vn,o=new Float32Array((this.#ia?.length??0)+2);for(let t=0,e=o.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#ua(l,h);return this.newFreeDrawOutline(l,o,this.#Vn,this.#ta,this.#Wn,this.#qn)}#da(t){const e=this.#Kn,[i,s,n,a]=this.#Vn,[r,o,l,h]=this.#ra(),d=new Float32Array(36);d.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);return this.newFreeDrawOutline(d,t,this.#Vn,this.#ta,this.#Wn,this.#qn)}#ua(t,e){const i=this.#jn;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#ca(t,e){const i=this.#Kn.subarray(4,6),s=this.#Kn.subarray(16,18),[n,a,r,o]=this.#Vn,[l,h,d,c]=this.#ra();t.set([NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Vn;#pa=new Float32Array(4);#Wn;#qn;#ia;#ta;#ga;constructor(t,e,i,s,n,a){super();this.#ga=t;this.#ia=e;this.#Vn=i;this.#ta=s;this.#Wn=n;this.#qn=a;this.lastPoint=[NaN,NaN];this.#ma(a);const[r,o,l,h]=this.#pa;for(let e=0,i=t.length;et[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#ba)if(e[3]){t.push(...this.#wa(e));this.#va(e)}else{this.#ya(e);t.push(...this.#wa(e))}return this.#xa(t)}#xa(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;n=[e,r];s.push(n);for(;;){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;if(h!==e){n.push(h,d,e,d===a?a:r);h=e}d=d===a?r:a}n.push(h,d)}return new HighlightOutline(s,this.#Vn,this.#fa)}#_a(t){const e=this.#Aa;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=0;s--){const[i,n]=this.#Aa[s];if(i!==t)break;if(i===t&&n===e){this.#Aa.splice(s,1);return}}}#wa(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_a(s);for(let t=0;t=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 HighlightOutline extends Outline{#Vn;#Ea;constructor(t,e,i){super();this.#Ea=t;this.#Vn=e;this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Ea){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n-1){this.#Xa=!0;this.#Za(t);this.#tr()}else if(this.#Ua){this.#Ha=t.anchorNode;this.#za=t.anchorOffset;this.#Va=t.focusNode;this.#ja=t.focusOffset;this.#er();this.#tr();this.rotate(this.rotation)}}get telemetryInitialData(){return{action:"added",type:this.#Xa?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#ea,methodOfCreation:this.#Ja}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#er(){const t=new HighlightOutliner(this.#Ua,.001);this.#qa=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#qa.box;const e=new HighlightOutliner(this.#Ua,.0025,.001,"ltr"===this._uiManager.direction);this.#$a=e.getOutlines();const{lastPoint:i}=this.#$a;this.#fa=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#Za({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#qa=t;this.#$a=t.getNewOutline(this.#ea/2+1.5,.0025);if(e>=0){this.#w=e;this.#Ga=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Ya=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#w,{bbox:HighlightEditor.#ir(this.#qa.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,e),path:{d:this.#$a.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.#$a;this.#fa=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case m.HIGHLIGHT_DEFAULT_COLOR:HighlightEditor._defaultColor=e;break;case m.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#fa}updateParams(t,e){switch(t){case m.HIGHLIGHT_COLOR:this.#On(e);break;case m.HIGHLIGHT_THICKNESS:this.#sr(e)}}static get defaultPropertiesToUpdate(){return[[m.HIGHLIGHT_DEFAULT_COLOR,HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[m.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,this.#ea||HighlightEditor._defaultThickness],[m.HIGHLIGHT_FREE,this.#Xa]]}#On(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.#Ka=e;this.parent?.drawLayer.updateProperties(this.#w,{root:{fill:t,"fill-opacity":e}});this.#n?.updateColor(t)},e=this.color,i=this.#Ka;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#sr(t){const e=this.#ea,setThickness=t=>{this.#ea=t;this.#nr(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.highlightColors){this.#n=new ColorPicker({editor:this});t.addColorPicker(this.#n)}return t}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#ar())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#ar())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#rr();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#rr();else if(t){this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#nr(t){if(!this.#Xa)return;this.#Za({highlightOutlines:this.#qa.getNewOutline(t/2)});this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#rr(){if(null!==this.#w&&this.parent){this.parent.drawLayer.remove(this.#w);this.#w=null;this.parent.drawLayer.remove(this.#Ya);this.#Ya=null}}#tr(t=this.parent){if(null===this.#w){({id:this.#w,clipPathId:this.#Ga}=t.drawLayer.draw({bbox:this.#qa.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#Ka},rootClass:{highlight:!0,free:this.#Xa},path:{d:this.#qa.toSVGPath()}},!1,!0));this.#Ya=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Xa},bbox:this.#$a.box,path:{d:this.#$a.toSVGPath()}},this.#Xa);this.#Wa&&(this.#Wa.style.clipPath=this.#Ga)}}static#ir([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Xa){t=(t-this.rotation+360)%360;i=HighlightEditor.#ir(this.#qa.box,t)}else i=HighlightEditor.#ir([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#w,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Ya,{bbox:HighlightEditor.#ir(this.#$a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#Qa){t.setAttribute("aria-label",this.#Qa);t.setAttribute("role","mark")}this.#Xa?t.classList.add("free"):this.div.addEventListener("keydown",this.#or.bind(this),{signal:this._uiManager._signal});const e=this.#Wa=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#Ga;const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);bindEvents(this,this.#Wa,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1}})}#or(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#lr(!0);break;case 1:case 3:this.#lr(!1)}}#lr(t){if(!this.#Ha)return;const e=window.getSelection();t?e.setPosition(this.#Ha,this.#za):e.setPosition(this.#Va,this.#ja)}select(){super.select();this.#Ya&&this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Ya){this.parent?.drawLayer.updateProperties(this.#Ya,{rootClass:{selected:!1}});this.#Xa||this.#lr(!1)}}get _mustFixPosition(){return!this.#Xa}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#w,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Ya,{rootClass:{hidden:!t}})}}#ar(){return this.#Xa?this.rotation:0}#hr(){if(this.#Xa)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#Ua,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l)*e+s;a[r]=a[r+4]=n;a[r+1]=a[r+3]=c;a[r+2]=a[r+6]=n+h*t;a[r+5]=a[r+7]=c-d*e;r+=8}return a}#dr(t){return this.#qa.serialize(t,this.#ar())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#cr(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:d});window.addEventListener("pointerup",pointerUpCallback,{signal:d});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d});window.addEventListener("contextmenu",noContextMenu,{signal:d});i.addEventListener("pointermove",this.#ur.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({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#ur(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#cr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:g.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 InkAnnotationElement){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:g.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=Util.makeHexColor(...n);l.#Ka=o||1;r&&(l.#ea=t.thickness);l.annotationElementId=t.id||null;l._initialData=s;const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(a){const t=l.#Ua=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#pr=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))this.updateProperty(e,i)}updateSVGProperty(t,e){this.#pr[t]=e}toSVGProperties(){const t=this.#pr;this.#pr=Object.create(null);return{root:t}}reset(){this.#pr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#gr=null;#mr;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#fr=null;static#br=null;static#Ar=null;static#wr=NaN;static#vr=null;static#yr=null;static#xr=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#mr=t.mustBeCommitted||!1;if(t.drawOutlines){this.#_r(t);this.#tr()}}#_r({drawOutlines:t,drawId:e,drawingOptions:i}){this.#gr=t;this._drawingOptions||=i;if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#Er(t,this.parent);this.#Sr(t.box)}#Er(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#fr.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],setter=t=>{s.updateProperty(e,t);const i=this.#gr.updateProperty(e,t);i&&this.#Sr(i);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties())};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizingSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathResizedSVGProperties(this.#Cr()),{bbox:this.#Tr()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Tr(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#gr.getPathTranslatedSVGProperties(this.#Cr(),this.parentDimensions),{bbox:this.#Tr()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#mr){this.#mr=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#rr();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#tr();this.#Sr(this.#gr.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#rr()}else if(t){this._uiManager.addShouldRescale(this);this.#tr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#rr(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#tr(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#Er(this.#gr,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Mr([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]}}#Cr(){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]}}#Sr(t){[this.x,this.y,this.width,this.height]=this.#Mr(t);if(this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Tr(){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,DrawingEditor._mergeSVGProperties({bbox:this.#Tr()},this.#gr.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Sr(this.#gr.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);this._uiManager.addShouldRescale(this);this.disableEditing();return t}static createDrawerInstance(t,e,i,s,n){unreachable("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=s;if(DrawingEditor.#vr&&DrawingEditor.#vr!==l)return;const{viewport:{rotation:h}}=t,{width:d,height:c}=n.getBoundingClientRect(),u=DrawingEditor.#br=new AbortController,p=t.combinedSignal(u);DrawingEditor.#wr||=o;DrawingEditor.#vr??=l;window.addEventListener("pointerup",(t=>{DrawingEditor.#wr===t.pointerId?this._endDraw(t):DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointercancel",(t=>{DrawingEditor.#wr===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#yr?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointerdown",(t=>{if(DrawingEditor.#vr===t.pointerType){(DrawingEditor.#yr||=new Set).add(t.pointerId);if(DrawingEditor.#fr.isCancellable()){DrawingEditor.#fr.removeLastElement();DrawingEditor.#fr.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}}),{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",(t=>{t.timeStamp===DrawingEditor.#xr&&stopEvent(t)}),{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#fr)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.startNew(a,r,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#fr=this.createDrawerInstance(a,r,d,c,h);DrawingEditor.#Ar=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#Ar.toSVGProperties(),DrawingEditor.#fr.defaultSVGProperties),!0,!1))}}static _drawMove(t){DrawingEditor.#xr=-1;if(!DrawingEditor.#fr)return;const{offsetX:e,offsetY:i,pointerId:s}=t;if(DrawingEditor.#wr===s)if(DrawingEditor.#yr?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.add(e,i));DrawingEditor.#xr=t.timeStamp;stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#fr=null;DrawingEditor.#Ar=null;DrawingEditor.#vr=null;DrawingEditor.#xr=NaN}if(DrawingEditor.#br){DrawingEditor.#br.abort();DrawingEditor.#br=null;DrawingEditor.#wr=NaN;DrawingEditor.#yr=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#fr.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#fr,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:m.DRAW_STEP})}else this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(m.DRAW_STEP);if(!DrawingEditor.#fr.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#fr.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#Ar,mustBeCommitted:!t});this._cleanup(!0);return a}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,a){unreachable("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);l.createDrawingOptions(t);l.#_r({drawOutlines:o});l.#tr();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#gr.serialize([e,i,s,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#Kn=new Float64Array(6);#bn;#Pr;#Fi;#ea;#ia;#Dr="";#kr=0;#Ea=new InkDrawOutline;#Rr;#Ir;constructor(t,e,i,s,n,a){this.#Rr=i;this.#Ir=s;this.#Fi=n;this.#ea=a;[t,e]=this.#Fr(t,e);const r=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];this.#Pr=[{line:r,points:this.#ia}];this.#Kn.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#ea=e)}#Fr(t,e){return Outline._normalizePoint(t,e,this.#Rr,this.#Ir,this.#Fi)}isEmpty(){return!this.#Pr||0===this.#Pr.length}isCancellable(){return this.#ia.length<=10}add(t,e){[t,e]=this.#Fr(t,e);const[i,s,n,a]=this.#Kn.subarray(2,6),r=t-n,o=e-a;if(Math.hypot(this.#Rr*r,this.#Ir*o)<=2)return null;this.#ia.push(t,e);if(isNaN(i)){this.#Kn.set([n,a,t,e],2);this.#bn.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Kn[0])&&this.#bn.splice(6,6);this.#Kn.set([i,s,n,a,t,e],0);this.#bn.push(...Outline.createBezierPoints(i,s,n,a,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#ia.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Rr=i;this.#Ir=s;this.#Fi=n;[t,e]=this.#Fr(t,e);const a=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ia=[t,e];const r=this.#Pr.at(-1);if(r){r.line=new Float32Array(r.line);r.points=new Float32Array(r.points)}this.#Pr.push({line:a,points:this.#ia});this.#Kn.set(a,0);this.#kr=0;this.toSVGPath();return null}getLastElement(){return this.#Pr.at(-1)}setLastElement(t){if(!this.#Pr)return this.#Ea.setLastElement(t);this.#Pr.push(t);this.#bn=t.line;this.#ia=t.points;this.#kr=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Pr)return this.#Ea.removeLastElement();this.#Pr.pop();this.#Dr="";for(let t=0,e=this.#Pr.length;tt??NaN)),d,c,u,p),points:g(r[t].map((t=>t??NaN)),d,c,u,p)});const m=new InkDrawOutline;m.build(h,i,s,1,o,l,n);return m}#Hr(t=this.#ea){const e=this.#Wn+t/2*this.#Or;return this.#Fi%180==0?[e/this.#Rr,e/this.#Ir]:[e/this.#Ir,e/this.#Rr]}#Br(){const[t,e,i,s]=this.#pa,[n,a]=this.#Hr(0);return[t+n,e+a,i-2*n,s-2*a]}#Nr(){const t=this.#pa=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Pr){if(e.length<=12){for(let i=4,s=e.length;it!==e[i]))||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e});return null}}class StampEditor extends AnnotationEditor{#Ur=null;#Gr=null;#$r=null;#Vr=null;#jr=null;#Wr="";#qr=null;#Xr=null;#Kr=!1;#Yr=!1;static _type="stamp";static _editorType=g.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Vr=t.bitmapUrl;this.#jr=t.bitmapFile}static initialize(t,e){AnnotationEditor.initialize(t,e)}static get supportedTypes(){return shadow(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return shadow(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(g.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}}#Qr(t,e=!1){if(t){this.#Ur=t.bitmap;if(!e){this.#Gr=t.id;this.#Kr=t.isSvg}t.file&&(this.#Wr=t.file.name);this.#Jr()}else this.remove()}#Zr(){this.#$r=null;this._uiManager.enableWaiting(!1);if(this.#qr)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){this._editToolbar.hide();this._uiManager.editAltText(this,!0)}else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ur){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;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#to(){if(this.#Gr){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#Gr).then((t=>this.#Qr(t,!0))).finally((()=>this.#Zr()));return}if(this.#Vr){const t=this.#Vr;this.#Vr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}if(this.#jr){const t=this.#jr;this.#jr=null;this._uiManager.enableWaiting(!0);this.#$r=this._uiManager.imageManager.getFromFile(t).then((t=>this.#Qr(t))).finally((()=>this.#Zr()));return}const t=document.createElement("input");t.type="file";t.accept=StampEditor.supportedTypesStr;const e=this._uiManager._signal;this.#$r=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.#Qr(e)}else this.remove();i()}),{signal:e});t.addEventListener("cancel",(()=>{this.remove();i()}),{signal:e})})).finally((()=>this.#Zr()));t.click()}remove(){if(this.#Gr){this.#Ur=null;this._uiManager.imageManager.deleteId(this.#Gr);this.#qr?.remove();this.#qr=null;if(this.#Xr){clearTimeout(this.#Xr);this.#Xr=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Gr&&null===this.#qr&&this.#to();this.isAttachedToDOM||this.parent.add(this)}}else this.#Gr&&this.#to()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#$r||this.#Ur||this.#Vr||this.#jr||this.#Gr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.div.setAttribute("role","figure");this.addAltTextButton();this.#Ur?this.#Jr():this.#to();if(this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}this._uiManager.addShouldRescale(this);return this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#Xr&&clearTimeout(this.#Xr);this.#Xr=setTimeout((()=>{this.#Xr=null;this.#eo()}),200)}#Jr(){const{div:t}=this;let{width:e,height:i}=this.#Ur;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.#qr=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.#eo();if(!this.#Yr){this.parent.addUndoableEditor(this);this.#Yr=!0}this._reportTelemetry({action:"inserted_image"});this.#Wr&&l.setAttribute("aria-label",this.#Wr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ur,a=new OutputScale;let r=this.#Ur,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.#Kr||(r=this.#io(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(window.matchMedia?.("(prefers-color-scheme: dark)").matches){c="#8f8f9d";u="#42414d"}const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c;b.fillRect(0,0,2*g,2*m);b.fillStyle=u;b.fillRect(0,0,g,m);b.fillRect(g,m,g,m);d.fillStyle=d.createPattern(f,"repeat");d.fillRect(0,0,t,i);d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a);i=Math.floor(n*a);this.#Kr||(r=this.#io(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);d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#io(t,e){const{width:i,height:s}=this.#Ur;let n=i,a=s,r=this.#Ur;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}#eo(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new OutputScale,a=Math.ceil(i*t*n.sx),r=Math.ceil(s*e*n.sy),o=this.#qr;if(!o||o.width===a&&o.height===r)return;o.width=a;o.height=r;const l=this.#Kr?this.#Ur:this.#io(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}getImageForAltText(){return this.#qr}#so(t){if(t){if(this.#Kr){const t=this._uiManager.imageManager.getSvgUrl(this.#Gr);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Ur);t.getContext("2d").drawImage(this.#Ur,0,0);return t.toDataURL()}if(this.#Kr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#Ur,0,0,this.#Ur.width,this.#Ur.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#Ur)}static async deserialize(t,e,i){let s=null;if(t instanceof StampAnnotationElement){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:h,parent:{page:{pageNumber:d}}}=t,c=h.querySelector("canvas"),u=i.imageManager.getFromCanvas(h.id,c);c.remove();const p=(await e._structTree.getAriaAttributes(`${et}${r}`))?.get("aria-label")||"";s=t={annotationType:g.STAMP,bitmapId:u.id,bitmap:u.bitmap,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:d}=t;if(l&&i.imageManager.isValidId(l)){n.#Gr=l;r&&(n.#Ur=r)}else n.#Vr=o;n.#Kr=h;const[c,u]=n.pageDimensions;n.width=(a[2]-a[0])/c;n.height=(a[3]-a[1])/u;n.annotationElementId=t.id||null;d&&(n.altTextData=d);n._initialData=s;n.#Yr=!!s;return n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:g.STAMP,bitmapId:this.#Gr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Kr,structTreeParentId:this._structTreeParentId};if(t){i.bitmapUrl=this.#so(!0);i.accessibilityData=this.serializeAltText(!0);return i}const{decorative:s,altText:n}=this.serializeAltText(!1);!s&&n&&(i.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#$n(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}i.id=this.annotationElementId;if(null===e)return i;e.stamps||=new Map;const a=this.#Kr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#Gr)){if(this.#Kr){const t=e.stamps.get(this.#Gr);if(a>t.area){t.area=a;t.serialized.bitmap.close();t.serialized.bitmap=this.#so(!1)}}}else{e.stamps.set(this.#Gr,{area:a,serialized:i});i.bitmap=this.#so(!1)}return i}#$n(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){t.updateEdited({rect:this.getRect(0,0)});return null}}class AnnotationEditorLayer{#Cn;#no=!1;#ao=null;#ro=null;#oo=null;#lo=new Map;#ho=!1;#do=!1;#co=!1;#uo=null;#po=null;#go=null;#mo=null;#m;static _initialized=!1;static#U=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor].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 d=[...AnnotationEditorLayer.#U.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#m=t;this.pageIndex=e;this.div=i;this.#Cn=n;this.#ao=a;this.viewport=l;this.#go=o;this.drawLayer=r;this._structTree=s;this.#m.addLayer(this)}get isEmpty(){return 0===this.#lo.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===g.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){this.#fo();switch(t){case g.NONE:this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case g.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case g.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of AnnotationEditorLayer.#U.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#go?.div}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}cleanUndoStack(t){this.#m.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#ao?.div.classList.toggle("disabled",!t)}async enable(){this.#co=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);const t=new Set;for(const e of this.#lo.values()){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#m.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}if(!this.#ao){this.#co=!1;return}const e=this.#ao.getEditableAnnotations();for(const i of e){i.hide();if(this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#co=!1}disable(){this.#do=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#lo.values()){i.disableEditing();if(i.annotationElementId)if(null===i.serialize()){e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show();i.remove()}else t.set(i.annotationElementId,i)}if(this.#ao){const i=this.#ao.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);if(n){n.resetAnnotationElement(s);n.show(!1);s.show()}else{n=t.get(i);if(n){this.#m.addChangedExistingAnnotation(n);n.renderAnnotationElement(s)&&n.show(!1)}s.show()}}}this.#fo();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#U.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);this.#do=!1}getEditableAnnotation(t){return this.#ao?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#go?.div&&!this.#mo){this.#mo=new AbortController;const t=this.#m.combinedSignal(this.#mo);this.#go.div.addEventListener("pointerdown",this.#bo.bind(this),{signal:t});this.#go.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#go?.div&&this.#mo){this.#mo.abort();this.#mo=null;this.#go.div.classList.remove("highlighting")}}#bo(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#go.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#go.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0);this.#go.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#go.div,x:t.x,y:t.y});this.#go.div.addEventListener("pointerup",(()=>{this.#go.div.classList.remove("free");this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal});t.preventDefault()}}enableClick(){if(this.#ro)return;this.#ro=new AbortController;const t=this.#m.combinedSignal(this.#ro);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.#ro?.abort();this.#ro=null}attach(t){this.#lo.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#lo.delete(t.id);this.#Cn?.removePointerInTextLayer(t.contentDiv);!this.#do&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#m.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#m.addDeletedAnnotationElement(t.annotationElementId);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#m.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#co);this.#m.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#oo){t._focusEventsAllowed=!1;this.#oo=setTimeout((()=>{this.#oo=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal});e.focus()}}),0)}t._structTreeParentId=this.#Cn?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Ao(){return AnnotationEditorLayer.#U.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#wo(t){const e=this.#Ao;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Ao?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t);this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#vo(),n=this.getNextId(),a=this.#wo({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#U.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#wo({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});n&&this.add(n);return n}#vo(){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(){this.createAndAddNewEditor(this.#vo(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(!(0!==t.button||t.ctrlKey&&e)&&t.target===this.div&&this.#ho){this.#ho=!1;this.#Ao?.isDrawer&&this.#Ao.supportMultipleDrawings||(this.#no?this.#m.getMode()!==g.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#no=!0)}}pointerdown(t){this.#m.getMode()===g.HIGHLIGHT&&this.enableTextSelection();if(this.#ho){this.#ho=!1;return}const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#ho=!0;if(this.#Ao?.isDrawer){this.startDrawingSession(t);return}const i=this.#m.getActive();this.#no=!i||i.isEmpty()}startDrawingSession(t){this.div.focus();if(this.#uo){this.#Ao.startDrawing(this,this.#m,!1,t);return}this.#m.setCurrentDrawingSession(this);this.#uo=new AbortController;const e=this.#m.combinedSignal(this.#uo);this.div.addEventListener("blur",(({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#po=null;this.commitOrRemove()}}),{signal:e});this.#Ao.startDrawing(this,this.#m,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#po=t)}else this.#po&&setTimeout((()=>{this.#po?.focus();this.#po=null}),0)}endDrawingSession(t=!1){if(!this.#uo)return null;this.#m.setCurrentDrawingSession(null);this.#uo.abort();this.#uo=null;this.#po=null;return this.#Ao.endDrawing(t)}findNewParent(t,e,i){const s=this.#m.findParent(e,i);if(null===s||s===this)return!1;s.changeParent(t);return!0}commitOrRemove(){if(this.#uo){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#uo&&this.#Ao.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#m.getActive()?.parent===this){this.#m.commitOrRemove();this.#m.setActiveEditor(null)}if(this.#oo){clearTimeout(this.#oo);this.#oo=null}for(const t of this.#lo.values()){this.#Cn?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#lo.clear();this.#m.removeLayer(this)}#fo(){for(const t of this.#lo.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#m.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#m.commitOrRemove();this.#fo();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#lo.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class DrawLayer{#nn=null;#w=0;#yo=new Map;#xo=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#nn){if(this.#nn!==t){if(this.#yo.size>0)for(const e of this.#yo.values()){e.remove();t.append(e)}this.#nn=t}}else this.#nn=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#_o(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+"%"}#Eo(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#nn.append(t);t.setAttribute("aria-hidden",!0);return t}#So(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s);i.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");i.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return s}#Co(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=this.#w++,n=this.#Eo(),a=DrawLayer._svgFactory.createElement("defs");n.append(a);const r=DrawLayer._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.#xo.set(s,r);const l=i?this.#So(a,o):null,h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#yo.set(s,n);return{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=this.#w++,s=this.#Eo(),n=DrawLayer._svgFactory.createElement("defs");s.append(n);const a=DrawLayer._svgFactory.createElement("path");n.append(a);const r=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",r);a.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");n.append(t);o=`mask_p${this.pageIndex}_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const s=DrawLayer._svgFactory.createElement("use");t.append(s);s.setAttribute("href",`#${r}`);s.setAttribute("stroke","none");s.setAttribute("fill","black");s.setAttribute("fill-rule","nonzero");s.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");s.append(l);l.setAttribute("href",`#${r}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();s.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(s,t);this.#yo.set(i,s);return i}finalizeDraw(t,e){this.#xo.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.#yo.get(t):t;if(r){i&&this.#Co(r,i);s&&DrawLayer.#_o(r,s);if(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.#Co(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#yo.get(t);if(i){e.#nn.append(i);this.#yo.delete(t);e.#yo.set(t,i)}}remove(t){this.#xo.delete(t);if(null!==this.#nn){this.#yo.get(t).remove();this.#yo.delete(t)}}destroy(){this.#nn=null;for(const t of this.#yo.values())t.remove();this.#yo.clear();this.#xo.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner};var Ut=__webpack_exports__.AbortException,Gt=__webpack_exports__.AnnotationEditorLayer,$t=__webpack_exports__.AnnotationEditorParamsType,Vt=__webpack_exports__.AnnotationEditorType,jt=__webpack_exports__.AnnotationEditorUIManager,Wt=__webpack_exports__.AnnotationLayer,qt=__webpack_exports__.AnnotationMode,Xt=__webpack_exports__.ColorPicker,Kt=__webpack_exports__.DOMSVGFactory,Yt=__webpack_exports__.DrawLayer,Qt=__webpack_exports__.FeatureTest,Jt=__webpack_exports__.GlobalWorkerOptions,Zt=__webpack_exports__.ImageKind,te=__webpack_exports__.InvalidPDFException,ee=__webpack_exports__.MissingPDFException,ie=__webpack_exports__.OPS,se=__webpack_exports__.OutputScale,ne=__webpack_exports__.PDFDataRangeTransport,ae=__webpack_exports__.PDFDateString,re=__webpack_exports__.PDFWorker,oe=__webpack_exports__.PasswordResponses,le=__webpack_exports__.PermissionFlag,he=__webpack_exports__.PixelsPerInch,de=__webpack_exports__.RenderingCancelledException,ce=__webpack_exports__.TextLayer,ue=__webpack_exports__.TouchManager,pe=__webpack_exports__.UnexpectedResponseException,ge=__webpack_exports__.Util,me=__webpack_exports__.VerbosityLevel,fe=__webpack_exports__.XfaLayer,be=__webpack_exports__.build,Ae=__webpack_exports__.createValidAbsoluteUrl,we=__webpack_exports__.fetchData,ve=__webpack_exports__.getDocument,ye=__webpack_exports__.getFilenameFromUrl,xe=__webpack_exports__.getPdfFilenameFromUrl,_e=__webpack_exports__.getXfaPageViewport,Ee=__webpack_exports__.isDataScheme,Se=__webpack_exports__.isPdfFile,Ce=__webpack_exports__.noContextMenu,Te=__webpack_exports__.normalizeUnicode,Me=__webpack_exports__.setLayerDimensions,Pe=__webpack_exports__.shadow,De=__webpack_exports__.stopEvent,ke=__webpack_exports__.version;export{Ut as AbortException,Gt as AnnotationEditorLayer,$t as AnnotationEditorParamsType,Vt as AnnotationEditorType,jt as AnnotationEditorUIManager,Wt as AnnotationLayer,qt as AnnotationMode,Xt as ColorPicker,Kt as DOMSVGFactory,Yt as DrawLayer,Qt as FeatureTest,Jt as GlobalWorkerOptions,Zt as ImageKind,te as InvalidPDFException,ee as MissingPDFException,ie as OPS,se as OutputScale,ne as PDFDataRangeTransport,ae as PDFDateString,re as PDFWorker,oe as PasswordResponses,le as PermissionFlag,he as PixelsPerInch,de as RenderingCancelledException,ce as TextLayer,ue as TouchManager,pe as UnexpectedResponseException,ge as Util,me as VerbosityLevel,fe as XfaLayer,be as build,Ae as createValidAbsoluteUrl,we as fetchData,ve as getDocument,ye as getFilenameFromUrl,xe as getPdfFilenameFromUrl,_e as getXfaPageViewport,Ee as isDataScheme,Se as isPdfFile,Ce as noContextMenu,Te as normalizeUnicode,Me as setLayerDimensions,Pe as shadow,De as stopEvent,ke as version}; \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs new file mode 100644 index 00000000000..3ec0f16d5c9 --- /dev/null +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/build/pdf.worker.min.mjs @@ -0,0 +1,21 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2024 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */var e={d:(t,i)=>{for(var a in i)e.o(i,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:i[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__ = globalThis.pdfjsWorker = {};e.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],s=1.35,r=.35,n=.25925925925925924,g=1,o=2,c=4,C=8,h=16,l=64,Q=128,E=256,u="pdfjs_internal_editor_",d=3,f=9,p=13,m=15,y={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},w=0,D=4,b=1,F=2,S=3,k=1,R=2,N=3,G=4,M=5,U=6,x=7,L=8,H=9,J=10,Y=11,v=12,K=13,T=14,q=15,O=16,W=17,j=20,X="Group",Z="R",V=1,z=2,_=4,$=16,AA=32,eA=128,tA=512,iA=1,aA=2,sA=4096,rA=8192,nA=32768,gA=65536,oA=131072,IA=1048576,cA=2097152,CA=8388608,hA=16777216,lA=1,BA=2,QA=3,EA=4,uA=5,dA={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},fA={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},pA={O:"PageOpen",C:"PageClose"},mA=1,yA=5,wA=1,DA=2,bA=3,FA=4,SA=5,kA=6,RA=7,NA=8,GA=9,MA=10,UA=11,xA=12,LA=13,HA=14,JA=15,YA=16,vA=17,KA=18,TA=19,qA=20,OA=21,PA=22,WA=23,jA=24,XA=25,ZA=26,VA=27,zA=28,_A=29,$A=30,Ae=31,ee=32,te=33,ie=34,ae=35,se=36,re=37,ne=38,ge=39,oe=40,Ie=41,ce=42,Ce=43,he=44,le=45,Be=46,Qe=47,Ee=48,ue=49,de=50,fe=51,pe=52,me=53,ye=54,we=55,De=56,be=57,Fe=58,Se=59,ke=60,Re=61,Ne=62,Ge=63,Me=64,Ue=65,xe=66,Le=67,He=68,Je=69,Ye=70,ve=71,Ke=72,Te=73,qe=74,Oe=75,Pe=76,We=77,je=80,Xe=81,Ze=83,Ve=84,ze=85,_e=86,$e=87,At=88,et=89,tt=90,it=91,at=92,st=93,rt=1,nt=2;let gt=mA;function getVerbosityLevel(){return gt}function info(e){gt>=yA&&console.log(`Info: ${e}`)}function warn(e){gt>=mA&&console.log(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,i=null){if(!e)return null;try{if(i&&"string"==typeof e){if(i.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(i.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const a=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(a))return a}catch{}return null}function shadow(e,t,i,a=!1){Object.defineProperty(e,t,{value:i,enumerable:!a,configurable:!0,writable:!1});return i}const ot=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ot{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends ot{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends ot{constructor(e){super(e,"InvalidPDFException")}}class MissingPDFException extends ot{constructor(e){super(e,"MissingPDFException")}}class UnexpectedResponseException extends ot{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t}}class FormatError extends ot{constructor(e){super(e,"FormatError")}}class AbortException extends ot{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,i=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):shadow(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const It=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,i){return`#${It[e]}${It[t]}${It[i]}`}static scaleMinMax(e,t){let i;if(e[0]){if(e[0]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[3];t[3]*=e[3]}else{i=t[0];t[0]=t[1];t[1]=i;i=t[2];t[2]=t[3];t[3]=i;if(e[1]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const i=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/i,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/i]}static getAxialAlignedBoundingBox(e,t){const i=this.applyTransform(e,t),a=this.applyTransform(e.slice(2,4),t),s=this.applyTransform([e[0],e[3]],t),r=this.applyTransform([e[2],e[1]],t);return[Math.min(i[0],a[0],s[0],r[0]),Math.min(i[1],a[1],s[1],r[1]),Math.max(i[0],a[0],s[0],r[0]),Math.max(i[1],a[1],s[1],r[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],i=e[0]*t[0]+e[1]*t[2],a=e[0]*t[1]+e[1]*t[3],s=e[2]*t[0]+e[3]*t[2],r=e[2]*t[1]+e[3]*t[3],n=(i+r)/2,g=Math.sqrt((i+r)**2-4*(i*r-s*a))/2,o=n+g||1,c=n-g||1;return[Math.sqrt(o),Math.sqrt(c)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const i=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),a=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(i>a)return null;const s=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),r=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return s>r?null:[i,s,a,r]}static#A(e,t,i,a,s,r,n,g,o,c){if(o<=0||o>=1)return;const C=1-o,h=o*o,l=h*o,Q=C*(C*(C*e+3*o*t)+3*h*i)+l*a,E=C*(C*(C*s+3*o*r)+3*h*n)+l*g;c[0]=Math.min(c[0],Q);c[1]=Math.min(c[1],E);c[2]=Math.max(c[2],Q);c[3]=Math.max(c[3],E)}static#e(e,t,i,a,s,r,n,g,o,c,C,h){if(Math.abs(o)<1e-12){Math.abs(c)>=1e-12&&this.#A(e,t,i,a,s,r,n,g,-C/c,h);return}const l=c**2-4*C*o;if(l<0)return;const Q=Math.sqrt(l),E=2*o;this.#A(e,t,i,a,s,r,n,g,(-c+Q)/E,h);this.#A(e,t,i,a,s,r,n,g,(-c-Q)/E,h)}static bezierBoundingBox(e,t,i,a,s,r,n,g,o){if(o){o[0]=Math.min(o[0],e,n);o[1]=Math.min(o[1],t,g);o[2]=Math.max(o[2],e,n);o[3]=Math.max(o[3],t,g)}else o=[Math.min(e,n),Math.min(t,g),Math.max(e,n),Math.max(t,g)];this.#e(e,i,s,n,t,a,r,g,3*(3*(i-s)-e+n),6*(e-2*i+s),3*(i-e),o);this.#e(e,i,s,n,t,a,r,g,3*(3*(a-r)-t+g),6*(t-2*a+r),3*(a-t),o);return o}}const ct=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const i=new TextDecoder(t,{fatal:!0}),a=stringToBytes(e),s=i.decode(a);return s.includes("")?s.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):s}catch(e){warn(`stringToPDFString: "${e}".`)}}const t=[];for(let i=0,a=e.length;iIt[e])).join("")}"function"!=typeof Promise.try&&(Promise.try=function(e,...t){return new Promise((i=>{i(e(...t))}))});const lt=Symbol("CIRCULAR_REF"),Bt=Symbol("EOF");let Qt=Object.create(null),Et=Object.create(null),ut=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return Et[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return Qt[e]||=new Cmd(e)}}const dt=function nonSerializableClosure(){return dt};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=dt}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetch(a,this.suppressEncryption):a}async getAsync(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetchAsync(a,this.suppressEncryption):a}getArray(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}a instanceof Ref&&this.xref&&(a=this.xref.fetch(a,this.suppressEncryption));if(Array.isArray(a)){a=a.slice();for(let e=0,t=a.length;e{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:i=!1}){const a=new Dict(e),s=new Map;for(const e of t)if(e instanceof Dict)for(const[t,a]of e._map){let e=s.get(t);if(void 0===e){e=[];s.set(t,e)}else if(!(i&&a instanceof Dict))continue;e.push(a)}for(const[t,i]of s){if(1===i.length||!(i[0]instanceof Dict)){a._map.set(t,i[0]);continue}const s=new Dict(e);for(const e of i)for(const[t,i]of e._map)s._map.has(t)||s._map.set(t,i);s.size>0&&a._map.set(t,s)}s.clear();return a.size>0?a:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){delete this._map[e]}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=ut[e];if(t)return t;const i=/^(\d+)R(\d*)$/.exec(e);return i&&"0"!==i[1]?ut[e]=new Ref(parseInt(i[1]),i[2]?parseInt(i[2]):0):null}static get(e,t){const i=0===t?`${e}R`:`${e}R${t}`;return ut[i]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,i=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const ft=/^[1-9]\.\d$/,pt=2**31-1;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends ot{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends ot{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends ot{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends ot{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let i=0;for(let a=0;a0,"The number should be a positive integer.");const i="M".repeat(e/1e3|0)+mt[e%1e3/100|0]+mt[10+(e%100/10|0)]+mt[20+e%10];return t?i.toLowerCase():i}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every((e=>"number"==typeof e)):ArrayBuffer.isView(e)&&(0===e.length||"number"==typeof e[0])&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const i=e.match(t);return i?{name:i[1],pos:parseInt(i[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let i=0;for(let a=0,s=e.length;a126||35===s||40===s||41===s||60===s||62===s||91===s||93===s||123===s||125===s||47===s||37===s){i"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,i,a){if(!e)return;let s=null;if(e instanceof Ref){if(a.has(e))return;s=e;a.put(s);e=t.fetch(e)}if(Array.isArray(e))for(const s of e)_collectJS(s,t,i,a);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let a;t instanceof BaseStream?a=t.getString():"string"==typeof t&&(a=t);a&&=stringToPDFString(a).replaceAll("\0","");a&&i.push(a)}_collectJS(e.getRaw("Next"),t,i,a)}s&&a.remove(s)}function collectActions(e,t,i){const a=Object.create(null),s=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(s)for(let t=s.length-1;t>=0;t--){const r=s[t];if(r instanceof Dict)for(const t of r.getKeys()){const s=i[t];if(!s)continue;const n=[];_collectJS(r.getRaw(t),e,n,new RefSet);n.length>0&&(a[s]=n)}}if(t.has("A")){const i=[];_collectJS(t.get("A"),e,i,new RefSet);i.length>0&&(a.Action=i)}return objectSize(a)>0?a:null}const yt={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,i=e.length;t55295&&(i<57344||i>65533)&&t++;yield i}}function encodeToXmlString(e){const t=[];let i=0;for(let a=0,s=e.length;a55295&&(s<57344||s>65533)&&a++;i=a+1}}if(0===t.length)return e;i: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:i,fontWeight:a,italicAngle:s}=e;if(!validateFontName(i,!0))return!1;const r=a?a.toString():"";e.fontWeight=t.has(r)?r:"400";const n=parseFloat(s);e.italicAngle=isNaN(n)||n<-90||n>90?"14":s.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[i,a]of e){if(!i.startsWith(u))continue;let e=t.get(a.pageIndex);if(!e){e=[];t.set(a.pageIndex,e)}e.push(a)}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return function isAscii(e){return/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let i=0,a=e.length;i>8&255],It[255&a])}return t.join("")}function stringToUTF16String(e,t=!1){const i=[];t&&i.push("þÿ");for(let t=0,a=e.length;t>8&255),String.fromCharCode(255&a))}return i.join("")}function getRotationMatrix(e,t,i){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,i];case 270:return[0,-1,1,0,0,i];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,i,a){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+i||this.bytes.length;this.dict=a}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e)return t.subarray(i,a);let s=i+e;s>a&&(s=a);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,i=null){return new Stream(this.bytes.buffer,e,t,i)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,i){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=i;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,i=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=i;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const i=Math.floor(e/this.chunkSize);if(i>this.numChunks)return;const a=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let s=i;s=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e){a>this.progressiveDataLength&&this.ensureRange(i,a);return t.subarray(i,a)}let s=i+e;s>a&&(s=a);s>this.progressiveDataLength&&this.ensureRange(i,s);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,i=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),i=Math.floor((this.end-1)/e)+1,a=[];for(let e=t;e{const readChunk=({value:r,done:n})=>{try{if(n){const t=arrayBuffersToBytes(a);a=null;e(t);return}s+=r.byteLength;i.isStreamingSupported&&this.onProgress({loaded:s});a.push(r);i.read().then(readChunk,t)}catch(e){t(e)}};i.read().then(readChunk,t)})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,i=new Set;this._chunksNeededByRequest.set(t,i);for(const t of e)this.stream.hasChunk(t)||i.add(t);if(0===i.size)return Promise.resolve();const a=Promise.withResolvers();this._promisesByRequest.set(t,a);const s=[];for(const e of i){let i=this._requestsByChunk.get(e);if(!i){i=[];this._requestsByChunk.set(e,i);s.push(e)}i.push(t)}if(s.length>0){const e=this.groupChunks(s);for(const t of e){const e=t.beginChunk*this.chunkSize,i=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,i).catch(a.reject)}}return a.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const i=this.getBeginChunk(e),a=this.getEndChunk(t),s=[];for(let e=i;e=0&&a+1!==r){t.push({beginChunk:i,endChunk:a+1});i=r}s+1===e.length&&t.push({beginChunk:i,endChunk:r+1});a=r}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,i=void 0===e.begin,a=i?this.progressiveDataLength:e.begin,s=a+t.byteLength,r=Math.floor(a/this.chunkSize),n=s0||g.push(i)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(n);Number.isInteger(e)&&this._requestChunks([e])}for(const e of g){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}class ColorSpace{constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t){const i=new Uint8ClampedArray(3);this.getRgbItem(e,t,i,0);return i}getRgbItem(e,t,i,a){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,i,a,s,r,n){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,i,a,s,r,n,g,o){const c=t*i;let C=null;const h=1<h&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=n<=8?new Uint8Array(h):new Uint16Array(h);for(let e=0;e=.99554525?1:this.#B(0,1,1.055*e**(1/2.4)-.055)}#B(e,t,i){return Math.max(e,Math.min(t,i))}#Q(e){return e<0?-this.#Q(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#I}#E(e,t,i){if(0===e[0]&&0===e[1]&&0===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=this.#Q(0),s=(1-a)/(1-this.#Q(e[0])),r=1-s,n=(1-a)/(1-this.#Q(e[1])),g=1-n,o=(1-a)/(1-this.#Q(e[2])),c=1-o;i[0]=t[0]*s+r;i[1]=t[1]*n+g;i[2]=t[2]*o+c}#u(e,t,i){if(1===e[0]&&1===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#C(e,a,s);this.#c(CalRGBCS.#a,s,i)}#d(e,t,i){const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#h(e,a,s);this.#c(CalRGBCS.#a,s,i)}#t(e,t,i,a,s){const r=this.#B(0,1,e[t]*s),n=this.#B(0,1,e[t+1]*s),g=this.#B(0,1,e[t+2]*s),o=1===r?1:r**this.GR,c=1===n?1:n**this.GG,C=1===g?1:g**this.GB,h=this.MXA*o+this.MXB*c+this.MXC*C,l=this.MYA*o+this.MYB*c+this.MYC*C,Q=this.MZA*o+this.MZB*c+this.MZC*C,E=CalRGBCS.#g;E[0]=h;E[1]=l;E[2]=Q;const u=CalRGBCS.#o;this.#u(this.whitePoint,E,u);const d=CalRGBCS.#g;this.#E(this.blackPoint,u,d);const f=CalRGBCS.#o;this.#d(CalRGBCS.#r,d,f);const p=CalRGBCS.#g;this.#c(CalRGBCS.#s,f,p);i[a]=255*this.#l(p[0]);i[a+1]=255*this.#l(p[1]);i[a+2]=255*this.#l(p[2])}getRgbItem(e,t,i,a){this.#t(e,t,i,a,1)}getRgbBuffer(e,t,i,a,s,r,n){const g=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#f(e){return e>=6/29?e**3:108/841*(e-4/29)}#p(e,t,i,a){return i+e*(a-i)/t}#t(e,t,i,a,s){let r=e[t],n=e[t+1],g=e[t+2];if(!1!==i){r=this.#p(r,i,0,100);n=this.#p(n,i,this.amin,this.amax);g=this.#p(g,i,this.bmin,this.bmax)}n>this.amax?n=this.amax:nthis.bmax?g=this.bmax:g>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,i){let a=0;for(let s=i;s>=0;s--){a+=e[s]+t[s];e[s]=255&a;a>>=8}}function incHex(e,t){let i=1;for(let a=t;a>=0&&i>0;a--){i+=e[a];e[a]=255&i;i>>=8}}const wt=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const i=this.readByte();if(i<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&i);t=t<<7|127&i}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let i;const a=this.tmpBuf;let s=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");i=!(128&e);a[s++]=127&e}while(!i);let r=t,n=0,g=0;for(;r>=0;){for(;g<8&&a.length>0;){n|=a[--s]<>=8;g-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const i=1&e[t]?255:0;let a=0;for(let s=0;s<=t;s++){a=(1&a)<<8|e[s];e[s]=a>>1^i}}readString(){const e=this.readNumber(),t=new Array(e);for(let i=0;i=0;){const e=l>>5;if(7===e){switch(31&l){case 0:a.readString();break;case 1:r=a.readString()}continue}const i=!!(16&l),s=15&l;if(s+1>wt)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const Q=1,E=a.readNumber();switch(e){case 0:a.readHex(n,s);a.readHexNumber(g,s);addHex(g,n,s);t.addCodespaceRange(s+1,hexToInt(n,s),hexToInt(g,s));for(let e=1;es&&(a=s)}else{for(;!this.eof;)this.readBlock(t);a=this.bufferLength}this.pos=a;return this.buffer.subarray(i,a)}async getImageData(e,t=null){if(!this.canAsyncDecodeImageFromBuffer)return this.getBytes(e,t);const i=await this.stream.asyncGetBytes();return this.decodeImage(i,t)}reset(){this.pos=0}makeSubStream(e,t,i=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const i=e+t;for(;this.bufferLength<=i&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,i)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter((e=>e instanceof BaseStream));let i=0;for(const t of e)i+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(i);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let i;try{i=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const a=this.bufferLength,s=a+i.length;this.ensureBuffer(s).set(i,a);this.bufferLength=s}getBaseStreams(){const e=[];for(const t of this.streams){const i=t.getBaseStreams();i&&e.push(...i)}return e.length>0?e:null}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.str=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.str;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const i=this.bufferLength;let a,s;if(122===t){a=this.ensureBuffer(i+4);for(s=0;s<4;++s)a[i+s]=0;this.bufferLength+=4}else{const r=this.input;r[0]=t;for(s=1;s<5;++s){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();r[s]=t;if(-1===t||126===t)break}a=this.ensureBuffer(i+s-1);this.bufferLength+=s-1;if(s<5){for(;s<5;++s)r[s]=117;this.eof=!0}let n=0;for(s=0;s<5;++s)n=85*n+(r[s]-33);for(s=3;s>=0;--s){a[i+s]=255&n;n>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.str=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.str.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,i=this.ensureBuffer(this.bufferLength+t);let a=this.bufferLength,s=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(s<0)s=e;else{i[a++]=s<<4|e;s=-1}}if(s>=0&&this.eof){i[a++]=s<<4;s=-1}this.firstDigit=s;this.bufferLength=a}}const bt=-1,Ft=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],St=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],kt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Rt=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Nt=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Gt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let i;for(;0===(i=this._lookBits(12));)this._eatBits(1);1===i&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,i=this.columns;let a,s,r,n,g;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let r,g,o;if(this.nextLine2D){for(n=0;t[n]=64);do{g+=o=this._getWhiteCode()}while(o>=64)}else{do{r+=o=this._getWhiteCode()}while(o>=64);do{g+=o=this._getBlackCode()}while(o>=64)}this._addPixels(t[this.codingPos]+r,s);t[this.codingPos]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]=64);else do{r+=o=this._getWhiteCode()}while(o>=64);this._addPixels(t[this.codingPos]+r,s);s^=1}}let c=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){r=this._lookBits(12);if(this.eoline)for(;r!==bt&&1!==r;){this._eatBits(1);r=this._lookBits(12)}else for(;0===r;){this._eatBits(1);r=this._lookBits(12)}if(1===r){this._eatBits(12);c=!0}else r===bt&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&c&&this.byteAlign){r=this._lookBits(12);if(1===r){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(n=0;n<4;++n){r=this._lookBits(12);1!==r&&info("bad rtc code: "+r);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){r=this._lookBits(13);if(r===bt){this.eof=!0;return-1}if(r>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&r)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){g=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]r){g<<=r;1&this.codingPos||(g|=255>>8-r);this.outputBits-=r;r=0}else{g<<=this.outputBits;1&this.codingPos||(g|=255>>8-this.outputBits);r-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){g<<=r;r=0}}}while(r)}this.black&&(g^=255);return g}_addPixels(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}this.codingPos=a}_addPixelsNeg(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}else if(e0&&e=s){const t=i[e-s];if(t[0]===a){this._eatBits(a);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=Ft[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,Ft);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return bt}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===bt)return 1;e=t>>5?kt[t>>3]:St[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,kt);if(e[0])return e[1];e=this._findTableCode(11,12,St);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===bt)return 1;t=e>>7?!(e>>9)&&e>>7?Nt[(e>>1)-64]:Gt[e>>7]:Rt[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Gt);if(e[0])return e[1];e=this._findTableCode(7,12,Nt,64);if(e[0])return e[1];e=this._findTableCode(10,13,Rt);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;i instanceof Dict||(i=Dict.empty);const a={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(a,{K:i.get("K"),EndOfLine:i.get("EndOfLine"),EncodedByteAlign:i.get("EncodedByteAlign"),Columns:i.get("Columns"),Rows:i.get("Rows"),EndOfBlock:i.get("EndOfBlock"),BlackIs1:i.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Mt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ut=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),xt=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Lt=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Ht=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.str=e;this.dict=e.dict;const i=e.getByte(),a=e.getByte();if(-1===i||-1===a)throw new FormatError(`Invalid header in flate stream: ${i}, ${a}`);if(8!=(15&i))throw new FormatError(`Unknown compression method in flate stream: ${i}, ${a}`);if(((i<<8)+a)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${i}, ${a}`);if(32&a)throw new FormatError(`FDICT bit set in flate stream: ${i}, ${a}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const i=await this.asyncGetBytes();return i?.subarray(0,e)||this.getBytes(e)}async asyncGetBytes(){this.str.reset();const e=this.str.getBytes();try{const{readable:t,writable:i}=new DecompressionStream("deflate"),a=i.getWriter();await a.ready;a.write(e).then((async()=>{await a.ready;await a.close()})).catch((()=>{}));const s=[];let r=0;for await(const e of t){s.push(e);r+=e.byteLength}const n=new Uint8Array(r);let g=0;for(const e of s){n.set(e,g);g+=e.byteLength}return n}catch{this.str=new Stream(e,2,e.length,this.str.dict);this.reset();return null}}get isAsync(){return!0}getBits(e){const t=this.str;let i,a=this.codeSize,s=this.codeBuf;for(;a>e;this.codeSize=a-=e;return i}getCode(e){const t=this.str,i=e[0],a=e[1];let s,r=this.codeSize,n=this.codeBuf;for(;r>16,c=65535&g;if(o<1||r>o;this.codeSize=r-o;return c}generateHuffmanTable(e){const t=e.length;let i,a=0;for(i=0;ia&&(a=e[i]);const s=1<>=1}for(i=e;i>=1;if(0===t){let t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let i=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}i|=t<<8;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let s=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}s|=t<<8;if(s!==(65535&~i)&&(0!==i||0!==s))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const r=this.bufferLength,n=r+i;e=this.ensureBuffer(n);this.bufferLength=n;if(0===i)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(i);e.set(t,r);t.length0;)C[g++]=Q}s=this.generateHuffmanTable(C.subarray(0,e));r=this.generateHuffmanTable(C.subarray(e,c))}}e=this.buffer;let n=e?e.length:0,g=this.bufferLength;for(;;){let t=this.getCode(s);if(t<256){if(g+1>=n){e=this.ensureBuffer(g+1);n=e.length}e[g++]=t;continue}if(256===t){this.bufferLength=g;return}t-=257;t=Ut[t];let a=t>>16;a>0&&(a=this.getBits(a));i=(65535&t)+a;t=this.getCode(r);t=xt[t];a=t>>16;a>0&&(a=this.getBits(a));const o=(65535&t)+a;if(g+i>=n){e=this.ensureBuffer(g+i);n=e.length}for(let t=0;t>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let i=e[t]>>1,a=1&e[t];const s=Jt[i],r=s.qe;let n,g=this.a-r;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&g));this.a=g;e[t]=i<<1|a;return n}}class Jbig2Error extends ot{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,i){this.data=e;this.start=t;this.end=i}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,i){const a=e.getContexts(t);let s=1;function readBits(e){let t=0;for(let r=0;r>>0}const r=readBits(1),n=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let g;0===r?g=n:n>0&&(g=-n);return g>=-2147483648&&g<=pt?g:null}function decodeIAID(e,t,i){const a=e.getContexts("IAID");let s=1;for(let e=0;e=F&&x=S){K=K<<1&d;for(u=0;u=0&&H=0){J=G[L][H];J&&(K|=J<=e?c<<=1:c=c<<1|w[g][o]}for(Q=0;Q=m||o<0||o>=p?c<<=1:c=c<<1|a[g][o]}const E=D.readBit(b,c);t[n]=E}}return w}function decodeTextRegion(e,t,i,a,s,r,n,g,o,c,C,h,l,Q,E,u,d,f,p){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const m=[];let y,w;for(y=0;y1&&(s=e?p.readBits(f):decodeInteger(b,"IAIT",D));const r=n*F+s,S=e?Q.symbolIDTable.decode(p):decodeIAID(b,D,o),k=t&&(e?p.readBit():decodeInteger(b,"IARI",D));let R=g[S],N=R[0].length,G=R.length;if(k){const e=decodeInteger(b,"IARDW",D),t=decodeInteger(b,"IARDH",D);N+=e;G+=t;R=decodeRefinement(N,G,E,R,(e>>1)+decodeInteger(b,"IARDX",D),(t>>1)+decodeInteger(b,"IARDY",D),!1,u,d)}let M=0;c?1&h?M=G-1:a+=G-1:h>1?a+=N-1:M=N-1;const U=r-(1&h?0:G-1),x=a-(2&h?N-1:0);let L,H,J;if(c)for(L=0;L>5&7;const o=[31&n];let c=t+6;if(7===n){g=536870911&readUint32(e,c-1);c+=3;let t=g+7>>3;o[0]=e[c++];for(;--t>0;)o.push(e[c++])}else if(5===n||6===n)throw new Jbig2Error("invalid referred-to flags");i.retainBits=o;let C=4;i.number<=256?C=1:i.number<=65536&&(C=2);const h=[];let l,Q;for(l=0;l>>24&255;r[3]=t.height>>16&255;r[4]=t.height>>8&255;r[5]=255&t.height;for(l=c,Q=e.length;l>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;c+=2;if(!e.huffman){o=0===e.template?4:1;n=[];for(g=0;g>2&3;C.stripSize=1<>4&3;C.transposed=!!(64&h);C.combinationOperator=h>>7&3;C.defaultPixelValue=h>>9&1;C.dsOffset=h<<17>>27;C.refinementTemplate=h>>15&1;if(C.huffman){const e=readUint16(a,c);c+=2;C.huffmanFS=3&e;C.huffmanDS=e>>2&3;C.huffmanDT=e>>4&3;C.huffmanRefinementDW=e>>6&3;C.huffmanRefinementDH=e>>8&3;C.huffmanRefinementDX=e>>10&3;C.huffmanRefinementDY=e>>12&3;C.huffmanRefinementSizeSelector=!!(16384&e)}if(C.refinement&&!C.refinementTemplate){n=[];for(g=0;g<2;g++){n.push({x:readInt8(a,c),y:readInt8(a,c+1)});c+=2}C.refinementAt=n}C.numberOfSymbolInstances=readUint32(a,c);c+=4;r=[C,i.referredTo,a,c,s];break;case 16:const l={},Q=a[c++];l.mmr=!!(1&Q);l.template=Q>>1&3;l.patternWidth=a[c++];l.patternHeight=a[c++];l.maxPatternIndex=readUint32(a,c);c+=4;r=[l,i.number,a,c,s];break;case 22:case 23:const E={};E.info=readRegionSegmentInformation(a,c);c+=Ot;const u=a[c++];E.mmr=!!(1&u);E.template=u>>1&3;E.enableSkip=!!(8&u);E.combinationOperator=u>>4&7;E.defaultPixelValue=u>>7&1;E.gridWidth=readUint32(a,c);c+=4;E.gridHeight=readUint32(a,c);c+=4;E.gridOffsetX=4294967295&readUint32(a,c);c+=4;E.gridOffsetY=4294967295&readUint32(a,c);c+=4;E.gridVectorX=readUint16(a,c);c+=2;E.gridVectorY=readUint16(a,c);c+=2;r=[E,i.referredTo,a,c,s];break;case 38:case 39:const d={};d.info=readRegionSegmentInformation(a,c);c+=Ot;const f=a[c++];d.mmr=!!(1&f);d.template=f>>1&3;d.prediction=!!(8&f);if(!d.mmr){o=0===d.template?4:1;n=[];for(g=0;g>2&1;p.combinationOperator=m>>3&3;p.requiresBuffer=!!(32&m);p.combinationOperatorOverride=!!(64&m);r=[p];break;case 49:case 50:case 51:case 62:break;case 53:r=[i.number,a,c,s];break;default:throw new Jbig2Error(`segment type ${i.typeName}(${i.type}) is not implemented`)}const C="on"+i.typeName;C in t&&t[C].apply(t,r)}function processSegments(e,t){for(let i=0,a=e.length;i>3,i=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&i.fill(255);this.buffer=i}drawBitmap(e,t){const i=this.currentPageInfo,a=e.width,s=e.height,r=i.width+7>>3,n=i.combinationOperatorOverride?e.combinationOperator:i.combinationOperator,g=this.buffer,o=128>>(7&e.x);let c,C,h,l,Q=e.y*r+(e.x>>3);switch(n){case 0:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;case 2:for(c=0;c>=1;if(!h){h=128;l++}}Q+=r}break;default:throw new Jbig2Error(`operator ${n} is not supported`)}}onImmediateGenericRegion(e,t,i,a){const s=e.info,r=new DecodingContext(t,i,a),n=decodeBitmap(e.mmr,s.width,s.height,e.template,e.prediction,null,e.at,r);this.drawBitmap(s,n)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,i,a,s,r){let n,g;if(e.huffman){n=function getSymbolDictionaryHuffmanTables(e,t,i){let a,s,r,n,g=0;switch(e.huffmanDHSelector){case 0:case 1:a=getStandardTable(e.huffmanDHSelector+4);break;case 3:a=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:s=getStandardTable(e.huffmanDWSelector+2);break;case 3:s=getCustomHuffmanTable(g,t,i);g++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){r=getCustomHuffmanTable(g,t,i);g++}else r=getStandardTable(1);n=e.aggregationInstancesSelector?getCustomHuffmanTable(g,t,i):getStandardTable(1);return{tableDeltaHeight:a,tableDeltaWidth:s,tableBitmapSize:r,tableAggregateInstances:n}}(e,i,this.customTables);g=new Reader(a,s,r)}let o=this.symbols;o||(this.symbols=o={});const c=[];for(const e of i){const t=o[e];t&&c.push(...t)}const C=new DecodingContext(a,s,r);o[t]=function decodeSymbolDictionary(e,t,i,a,s,r,n,g,o,c,C,h){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const l=[];let Q=0,E=log2(i.length+a);const u=C.decoder,d=C.contextCache;let f,p;if(e){f=getStandardTable(1);p=[];E=Math.max(E,1)}for(;l.length1)m=decodeTextRegion(e,t,a,Q,0,s,1,i.concat(l),E,0,0,1,0,r,o,c,C,0,h);else{const e=decodeIAID(d,u,E),t=decodeInteger(d,"IARDX",u),s=decodeInteger(d,"IARDY",u);m=decodeRefinement(a,Q,o,e=32){let i,a,n;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");a=s.readBits(2)+3;i=r[e-1].prefixLength;break;case 33:a=s.readBits(3)+3;i=0;break;case 34:a=s.readBits(7)+11;i=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(n=0;n=0;d--){R=e?decodeMMRBitmap(k,o,c,!0):decodeBitmap(!1,o,c,i,!1,null,F,E);S[d]=R}for(N=0;N=0;f--){M^=S[f][N][G];U|=M<>8;H=h+N*l-G*Q>>8;if(L>=0&&L+w<=a&&H>=0&&H+D<=s)for(d=0;d=s)){Y=u[t];J=x[d];for(f=0;f=0&&e>1&7),o=1+(a>>4&7),c=[];let C,h,l=s;do{C=n.readBits(g);h=n.readBits(o);c.push(new HuffmanLine([l,C,h,0]));l+=1<>t&1;if(t<=0)this.children[i]=new HuffmanTreeNode(e);else{let a=this.children[i];a||(this.children[i]=a=new HuffmanTreeNode(null));a.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,i=e.length;t0&&this.rootNode.buildTree(i,i.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let i=0;for(let a=0;a=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,i=0;for(t=e-1;t>=0;t--)i|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,i){let a=0;for(let s=0,r=t.length;s>i&1;i--}}if(a&&!g){const e=5;for(let t=0;t>2,c=new Uint32Array(e.buffer,t,o);if(FeatureTest.isLittleEndian){for(;n>>24|t<<8|4278190080;i[a+2]=t>>>16|s<<16|4278190080;i[a+3]=s>>>8|4278190080}for(let s=4*n,r=t+g;s>>8|255;i[a+2]=t<<16|s>>>16|255;i[a+3]=s<<8|255}for(let s=4*n,r=t+g;s>3,h=7&a,l=e.length;i=new Uint32Array(i.buffer);let Q=0;for(let a=0;a0&&!e[r-1];)r--;const n=[{children:[],index:0}];let g,o=n[0];for(i=0;i0;)o=n.pop();o.index++;n.push(o);for(;n.length<=i;){n.push(g={children:[],index:0});o.children[o.index]=g.children;o=g}s++}if(i+10){E--;return Q>>E&1}Q=e[t++];if(255===Q){const a=e[t++];if(a){if(220===a&&c){const a=readUint16(e,t+=2);t+=2;if(a>0&&a!==i.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",a)}else if(217===a){if(c){const e=p*(8===i.precision?8:0);if(e>0&&Math.round(i.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(Q<<8|a).toString(16)}`)}}E=7;return Q>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){u--;return}let i=r;const a=n;for(;i<=a;){const a=decodeHuffman(e.huffmanTableAC),s=15&a,r=a>>4;if(0===s){if(r<15){u=receive(r)+(1<>4;if(0===s)if(c<15){u=receive(c)+(1<>4;if(0===a){if(r<15)break;s+=16;continue}s+=r;const n=Wt[s];e.blockData[t+n]=receiveAndExtend(a);s++}};let k,R=0;const N=1===m?a[0].blocksPerLine*a[0].blocksPerColumn:C*i.mcusPerColumn;let G,M;for(;R<=N;){const i=s?Math.min(N-R,s):N;if(i>0){for(w=0;w0?"unexpected":"excessive"} MCU data, current marker is: ${k.invalid}`);t=k.offset}if(!(k.marker>=65488&&k.marker<=65495))break;t+=2}return t-l}function quantizeAndInverse(e,t,i){const a=e.quantizationTable,s=e.blockData;let r,n,g,o,c,C,h,l,Q,E,u,d,f,p,m,y,w;if(!a)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){Q=s[t+e];E=s[t+e+1];u=s[t+e+2];d=s[t+e+3];f=s[t+e+4];p=s[t+e+5];m=s[t+e+6];y=s[t+e+7];Q*=a[e];if(E|u|d|f|p|m|y){E*=a[e+1];u*=a[e+2];d*=a[e+3];f*=a[e+4];p*=a[e+5];m*=a[e+6];y*=a[e+7];r=$t*Q+128>>8;n=$t*f+128>>8;g=u;o=m;c=Ai*(E-y)+128>>8;l=Ai*(E+y)+128>>8;C=d<<4;h=p<<4;r=r+n+1>>1;n=r-n;w=g*_t+o*zt+128>>8;g=g*zt-o*_t+128>>8;o=w;c=c+h+1>>1;h=c-h;l=l+C+1>>1;C=l-C;r=r+o+1>>1;o=r-o;n=n+g+1>>1;g=n-g;w=c*Vt+l*Zt+2048>>12;c=c*Zt-l*Vt+2048>>12;l=w;w=C*Xt+h*jt+2048>>12;C=C*jt-h*Xt+2048>>12;h=w;i[e]=r+l;i[e+7]=r-l;i[e+1]=n+h;i[e+6]=n-h;i[e+2]=g+C;i[e+5]=g-C;i[e+3]=o+c;i[e+4]=o-c}else{w=$t*Q+512>>10;i[e]=w;i[e+1]=w;i[e+2]=w;i[e+3]=w;i[e+4]=w;i[e+5]=w;i[e+6]=w;i[e+7]=w}}for(let e=0;e<8;++e){Q=i[e];E=i[e+8];u=i[e+16];d=i[e+24];f=i[e+32];p=i[e+40];m=i[e+48];y=i[e+56];if(E|u|d|f|p|m|y){r=$t*Q+2048>>12;n=$t*f+2048>>12;g=u;o=m;c=Ai*(E-y)+2048>>12;l=Ai*(E+y)+2048>>12;C=d;h=p;r=4112+(r+n+1>>1);n=r-n;w=g*_t+o*zt+2048>>12;g=g*zt-o*_t+2048>>12;o=w;c=c+h+1>>1;h=c-h;l=l+C+1>>1;C=l-C;r=r+o+1>>1;o=r-o;n=n+g+1>>1;g=n-g;w=c*Vt+l*Zt+2048>>12;c=c*Zt-l*Vt+2048>>12;l=w;w=C*Xt+h*jt+2048>>12;C=C*jt-h*Xt+2048>>12;h=w;Q=r+l;y=r-l;E=n+h;m=n-h;u=g+C;p=g-C;d=o+c;f=o-c;Q<16?Q=0:Q>=4080?Q=255:Q>>=4;E<16?E=0:E>=4080?E=255:E>>=4;u<16?u=0:u>=4080?u=255:u>>=4;d<16?d=0:d>=4080?d=255:d>>=4;f<16?f=0:f>=4080?f=255:f>>=4;p<16?p=0:p>=4080?p=255:p>>=4;m<16?m=0:m>=4080?m=255:m>>=4;y<16?y=0:y>=4080?y=255:y>>=4;s[t+e]=Q;s[t+e+8]=E;s[t+e+16]=u;s[t+e+24]=d;s[t+e+32]=f;s[t+e+40]=p;s[t+e+48]=m;s[t+e+56]=y}else{w=$t*Q+8192>>14;w=w<-2040?0:w>=2024?255:w+2056>>4;s[t+e]=w;s[t+e+8]=w;s[t+e+16]=w;s[t+e+24]=w;s[t+e+32]=w;s[t+e+40]=w;s[t+e+48]=w;s[t+e+56]=w}}}function buildComponentData(e,t){const i=t.blocksPerLine,a=t.blocksPerColumn,s=new Int16Array(64);for(let e=0;e=a)return null;const r=readUint16(e,t);if(r>=65472&&r<=65534)return{invalid:null,marker:r,offset:t};let n=readUint16(e,s);for(;!(n>=65472&&n<=65534);){if(++s>=a)return null;n=readUint16(e,s)}return{invalid:r.toString(16),marker:n,offset:s}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),i=Math.ceil(e.scanLines/8/e.maxV);for(const a of e.components){const s=Math.ceil(Math.ceil(e.samplesPerLine/8)*a.h/e.maxH),r=Math.ceil(Math.ceil(e.scanLines/8)*a.v/e.maxV),n=t*a.h,g=64*(i*a.v)*(n+1);a.blockData=new Int16Array(g);a.blocksPerLine=s;a.blocksPerColumn=r}e.mcusPerLine=t;e.mcusPerColumn=i}function readDataBlock(e,t){const i=readUint16(e,t);let a=(t+=2)+i-2;const s=findNextFileMarker(e,a,t);if(s?.invalid){warn("readDataBlock - incorrect length, current marker is: "+s.invalid);a=s.offset}const r=e.subarray(t,a);return{appData:r,newOffset:t+=r.length}}function skipData(e,t){const i=readUint16(e,t),a=(t+=2)+i-2,s=findNextFileMarker(e,a,t);return s?.invalid?s.offset:a}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let i=0,a=null,s=readUint16(e,i);i+=2;if(65496!==s)throw new JpegError("SOI not found");s=readUint16(e,i);i+=2;A:for(;65497!==s;){switch(s){case 65472:case 65473:case 65474:a=e[i+7];break A;case 65535:255!==e[i]&&i--}i=skipData(e,i);s=readUint16(e,i);i+=2}return 4!==a&&(3!==a||0!==t)}parse(e,{dnlScanLines:t=null}={}){let i,a,s=0,r=null,n=null,g=0;const o=[],c=[],C=[];let h=readUint16(e,s);s+=2;if(65496!==h)throw new JpegError("SOI not found");h=readUint16(e,s);s+=2;A:for(;65497!==h;){let l,Q,E;switch(h){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const{appData:u,newOffset:d}=readDataBlock(e,s);s=d;65504===h&&74===u[0]&&70===u[1]&&73===u[2]&&70===u[3]&&0===u[4]&&(r={version:{major:u[5],minor:u[6]},densityUnits:u[7],xDensity:u[8]<<8|u[9],yDensity:u[10]<<8|u[11],thumbWidth:u[12],thumbHeight:u[13],thumbData:u.subarray(14,14+3*u[12]*u[13])});65518===h&&65===u[0]&&100===u[1]&&111===u[2]&&98===u[3]&&101===u[4]&&(n={version:u[5]<<8|u[6],flags0:u[7]<<8|u[8],flags1:u[9]<<8|u[10],transformCode:u[11]});break;case 65499:const f=readUint16(e,s);s+=2;const p=f+s-2;let m;for(;s>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=readUint16(e,s);s+=2}}else for(Q=0;Q<64;Q++){m=Wt[Q];i[m]=e[s++]}o[15&t]=i}break;case 65472:case 65473:case 65474:if(i)throw new JpegError("Only single frame JPEGs supported");s+=2;i={};i.extended=65473===h;i.progressive=65474===h;i.precision=e[s++];const y=readUint16(e,s);s+=2;i.scanLines=t||y;i.samplesPerLine=readUint16(e,s);s+=2;i.components=[];i.componentIds={};const w=e[s++];let D=0,b=0;for(l=0;l>4,r=15&e[s+1];D>4?c:C)[15&t]=buildHuffmanTable(i,r)}break;case 65501:s+=2;a=readUint16(e,s);s+=2;break;case 65498:const S=1==++g&&!t;s+=2;const k=e[s++],R=[];for(l=0;l>4];r.huffmanTableAC=c[15&n];R.push(r)}const N=e[s++],G=e[s++],M=e[s++];try{s+=decodeScan(e,s,i,R,a,N,G,M>>4,15&M,S)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break A}throw t}break;case 65500:s+=4;break;case 65535:255!==e[s]&&s--;break;default:const U=findNextFileMarker(e,s-2,s-3);if(U?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+U.invalid);s=U.offset;break}if(!U||s>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break A}throw new JpegError("JpegImage.parse - unknown marker: "+h.toString(16))}h=readUint16(e,s);s+=2}if(!i)throw new JpegError("JpegImage.parse - no frame data found.");this.width=i.samplesPerLine;this.height=i.scanLines;this.jfif=r;this.adobe=n;this.components=[];for(const e of i.components){const t=o[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/i.maxH,scaleY:e.v/i.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,i=!1){const a=this.width/e,s=this.height/t;let r,n,g,o,c,C,h,l,Q,E,u,d=0;const f=this.components.length,p=e*t*f,m=new Uint8ClampedArray(p),y=new Uint32Array(e),w=4294967288;let D;for(h=0;h>8)+b[Q+1];return m}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,i,a;for(let s=0,r=e.length;s4)throw new JpegError("Unsupported color mode");const r=this._getLinearizedBlockData(e,t,s);if(1===this.numComponents&&(i||a)){const e=r.length*(i?4:3),t=new Uint8ClampedArray(e);let a=0;if(i)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let i=0,a=e.length;i0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#w(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const i=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=i;this.bufferLength=i.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const i=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!i)return null;const a=this.#w(i);if(!JpegImage.canUseImageDecoder(a,e.colorTransform))return null;t=new ImageDecoder({data:a,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}}var ei,ti=(ei="undefined"!=typeof document?document.currentScript?.src:void 0,function(e={}){var t,i,a=e;new Promise(((e,a)=>{t=e;i=a}));a.decode=function(e,{numComponents:t=4,isIndexedColormap:i=!1,smaskInData:s=!1}){const r=e.length,n=a._malloc(r);a.HEAPU8.set(e,n);const g=a._jp2_decode(n,r,t>0?t:0,!!i,!!s);a._free(n);if(g){const{errorMessages:e}=a;if(e){delete a.errorMessages;return e}return"Unknown error"}const{imageData:o}=a;a.imageData=null;return o};var s=Object.assign({},a),r="./this.program",quit_=(e,t)=>{throw t},n="";"undefined"!=typeof document&&document.currentScript&&(n=document.currentScript.src);ei&&(n=ei);n=n.startsWith("blob:")?"":n.substr(0,n.replace(/[?#].*/,"").lastIndexOf("/")+1);var g=a.print||console.log.bind(console),o=a.printErr||console.error.bind(console);Object.assign(a,s);s=null;a.arguments&&a.arguments;a.thisProgram&&(r=a.thisProgram);var c,C=a.wasmBinary;function tryParseAsDataURI(e){if(isDataURI(e))return function intArrayFromBase64(e){for(var t=atob(e),i=new Uint8Array(t.length),a=0;ae.startsWith(b);function instantiateSync(e,t){var i,a=function getBinarySync(e){if(e==d&&C)return new Uint8Array(C);var t=tryParseAsDataURI(e);if(t)return t;throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}(e);i=new WebAssembly.Module(a);return[new WebAssembly.Instance(i,t),i]}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var F,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(a)},S=a.noExitRuntime||!0,k=0,R={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return h;quit_(0,e)},keepRuntimeAlive=()=>S||k>0,_proc_exit=e=>{h=e;if(!keepRuntimeAlive()){a.onExit?.(e);u=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{h=e;_proc_exit(e)},callUserCallback=e=>{if(!u)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(h)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},growMemory=e=>{var t=(e-c.buffer.byteLength+65535)/65536|0;try{c.grow(t);updateMemoryViews();return 1}catch(e){}},N={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:r||"./this.program"};for(var t in N)void 0===N[t]?delete e[t]:e[t]=N[t];var i=[];for(var t in e)i.push(`${t}=${e[t]}`);getEnvStrings.strings=i}return getEnvStrings.strings},G=[null,[],[]],M="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,i=NaN)=>{for(var a=t+i,s=t;e[s]&&!(s>=a);)++s;if(s-t>16&&e.buffer&&M)return M.decode(e.subarray(t,s));for(var r="";t>10,56320|1023&c)}}else r+=String.fromCharCode((31&n)<<6|g)}else r+=String.fromCharCode(n)}return r},printChar=(e,t)=>{var i=G[e];if(0===t||10===t){(1===e?g:o)(UTF8ArrayToString(i));i.length=0}else i.push(t)},UTF8ToString=(e,t)=>e?UTF8ArrayToString(Q,e,t):"",U={m:()=>function abort(e){a.onAbort?.(e);o(e="Aborted("+e+")");u=!0;e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);i(t);throw t}(""),c:(e,t,i)=>Q.copyWithin(e,t,t+i),l:()=>{S=!1;k=0},n:(e,t)=>{if(R[e]){clearTimeout(R[e].id);delete R[e]}if(!t)return 0;var i=setTimeout((()=>{delete R[e];callUserCallback((()=>L(e,performance.now())))}),t);R[e]={id:i,timeout_ms:t};return 0},g:function _copy_pixels_1(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(t),s=a.HEAP32.subarray(e,e+t);i.set(s)},f:function _copy_pixels_3(e,t,i,s){e>>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(3*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e>=2;t>>=2;i>>=2;s>>=2;const n=a.imageData=new Uint8ClampedArray(4*r),g=a.HEAP32.subarray(e,e+r),o=a.HEAP32.subarray(t,t+r),c=a.HEAP32.subarray(i,i+r),C=a.HEAP32.subarray(s,s+r);for(let e=0;e{var t,i,a=Q.length,s=2147483648;if((e>>>=0)>s)return!1;for(var r=1;r<=4;r*=2){var n=a*(1+.2/r);n=Math.min(n,e+100663296);var g=Math.min(s,(t=Math.max(e,n),i=65536,Math.ceil(t/i)*i));if(growMemory(g))return!0}return!1},p:(e,t)=>{var i=0;getEnvStrings().forEach(((a,s)=>{var r=t+i;E[e+4*s>>2]=r;((e,t)=>{for(var i=0;i{var i=getEnvStrings();E[e>>2]=i.length;var a=0;i.forEach((e=>a+=e.length+1));E[t>>2]=a;return 0},r:e=>52,j:function _fd_seek(e,t,i,a,s){return 70},b:(e,t,i,a)=>{for(var s=0,r=0;r>2],g=E[t+4>>2];t+=8;for(var o=0;o>2]=s;return 0},s:function _gray_to_rgba(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(4*t),s=a.HEAP32.subarray(e,e+t);for(let e=0;e>=2;t>>=2;const s=a.imageData=new Uint8ClampedArray(4*i),r=a.HEAP32.subarray(e,e+i),n=a.HEAP32.subarray(t,t+i);for(let e=0;e>=2;t>>=2;i>>=2;const r=a.imageData=new Uint8ClampedArray(4*s),n=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),o=a.HEAP32.subarray(i,i+s);for(let e=0;e0)){!function preRun(){if(a.preRun){"function"==typeof a.preRun&&(a.preRun=[a.preRun]);for(;a.preRun.length;)e=a.preRun.shift(),f.unshift(e)}var e;callRuntimeCallbacks(f)}();if(!(y>0))if(a.setStatus){a.setStatus("Running...");setTimeout((()=>{setTimeout((()=>a.setStatus("")),1);doRun()}),1)}else doRun()}function doRun(){if(!F){F=!0;a.calledRun=!0;if(!u){!function initRuntime(){callRuntimeCallbacks(p)}();t(a);a.onRuntimeInitialized?.();!function postRun(){if(a.postRun){"function"==typeof a.postRun&&(a.postRun=[a.postRun]);for(;a.postRun.length;)e=a.postRun.shift(),m.unshift(e)}var e;callRuntimeCallbacks(m)}()}}}}if(a.preInit){"function"==typeof a.preInit&&(a.preInit=[a.preInit]);for(;a.preInit.length>0;)a.preInit.pop()()}run();return a});const ii=ti;class JpxError extends ot{constructor(e){super(e,"JpxError")}}class JpxImage{static#D=null;static decode(e,t){t||={};this.#D||=ii({warn});const i=this.#D.decode(e,t);if("string"==typeof i)throw new JpxError(i);return i}static cleanup(){this.#D=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const i=t;t=e.getByte();if(65361===(i<<8|t)){e.skip(4);const t=e.getInt32()>>>0,i=e.getInt32()>>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0;e.skip(16);return{width:t-a,height:i-s,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}class JpxStream extends DecodeStream{constructor(e,t,i){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=i}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(e){this.decodeImage(null,e)}decodeImage(e,t){if(this.eof)return this.buffer;e||=this.bytes;this.buffer=JpxImage.decode(e,t);this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class LZWStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.cachedData=0;this.bitsCached=0;const a=4096,s={earlyChange:i,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(a),dictionaryLengths:new Uint16Array(a),dictionaryPrevCodes:new Uint16Array(a),currentSequence:new Uint8Array(a),currentSequenceLength:0};for(let e=0;e<256;++e){s.dictionaryValues[e]=e;s.dictionaryLengths[e]=1}this.lzwState=s}readBits(e){let t=this.bitsCached,i=this.cachedData;for(;t>>t&(1<0;if(e<256){l[0]=e;Q=1}else{if(!(e>=258)){if(256===e){C=9;n=258;Q=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){l[t]=g[i];i=c[i]}}else l[Q++]=l[0]}if(s){c[n]=h;o[n]=o[h]+1;g[n]=l[0];n++;C=n+r&n+r-1?C:0|Math.min(Math.log(n+r)/.6931471805599453+1,12)}h=e;E+=Q;if(a15))throw new FormatError(`Unsupported predictor: ${a}`);this.readBlock=2===a?this.readBlockTiff:this.readBlockPng;this.str=e;this.dict=e.dict;const s=this.colors=i.get("Colors")||1,r=this.bits=i.get("BPC","BitsPerComponent")||8,n=this.columns=i.get("Columns")||1;this.pixBytes=s*r+7>>3;this.rowBytes=n*s*r+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,i=this.ensureBuffer(t+e),a=this.bits,s=this.colors,r=this.str.getBytes(e);this.eof=!r.length;if(this.eof)return;let n,g=0,o=0,c=0,C=0,h=t;if(1===a&&1===s)for(n=0;n>1;e^=e>>2;e^=e>>4;g=(1&e)<<7;i[h++]=e}else if(8===a){for(n=0;n>8&255;i[h++]=255&e}}else{const e=new Uint8Array(s+1),h=(1<>c-a)&h;c-=a;o=o<=8){i[Q++]=o>>C-8&255;C-=8}}C>0&&(i[Q++]=(o<<8-C)+(g&(1<<8-C)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,i=this.str.getByte(),a=this.str.getBytes(e);this.eof=!a.length;if(this.eof)return;const s=this.bufferLength,r=this.ensureBuffer(s+e);let n=r.subarray(s-e,s);0===n.length&&(n=new Uint8Array(e));let g,o,c,C=s;switch(i){case 0:for(g=0;g>1)+a[g];for(;g>1)+a[g]&255;C++}break;case 4:for(g=0;g0){const e=this.str.getBytes(a);t.set(e,i);i+=a}}else{a=257-a;const s=e[1];t=this.ensureBuffer(i+a+1);for(let e=0;e>")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a.set(t,this.getObj(e))}if(this.buf1===Bt){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(a,e):a;this.shift();return a;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,i=e.pos;let a,s,r=0;for(;-1!==(a=e.getByte());)if(0===r)r=69===a?1:0;else if(1===r)r=73===a?2:0;else if(32===a||10===a||13===a){s=e.pos;const i=e.peekBytes(15),n=i.length;if(0===n)break;for(let e=0;e127))){r=0;break}}if(2!==r)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const g=new Lexer(new Stream(i.slice()),t);g._hexStringWarn=()=>{};let o=0;for(;;){const e=g.getObj();if(e===Bt){r=0;break}if(e instanceof Cmd){const i=t[e.cmd];if(!i){r=0;break}if(i.variableArgs?o<=i.numArgs:o===i.numArgs)break;o=0}else o++}if(2===r)break}else r=0;if(-1===a){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(s){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-s))}}let n=4;e.skip(-n);a=e.peekByte();e.skip(n);isWhiteSpace(a)||n--;return e.pos-n-i}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let i,a,s=!1;for(;-1!==(i=e.getByte());)if(255===i){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:s=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:a=e.getUint16();a>2?e.skip(a-2):e.skip(-2)}if(s)break}const r=e.pos-t;if(-1===i){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte());)if(126===i){const t=e.pos;i=e.peekByte();for(;isWhiteSpace(i);){e.skip();i=e.peekByte()}if(62===i){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const a=e.pos-t;if(-1===i){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte())&&62!==i;);const a=e.pos-t;if(-1===i){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}inlineStreamSkipEI(e){let t,i=0;for(;-1!==(t=e.getByte());)if(0===i)i=69===t?1:0;else if(1===i)i=73===t?2:0;else if(2===i)break}makeInlineImage(e){const t=this.lexer,i=t.stream,a=Object.create(null);let s;for(;!isCmd(this.buf1,"ID")&&this.buf1!==Bt;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===Bt)break;a[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(s=i.pos-t.beginInlineImagePos);const r=this.xref.fetchIfRef(a.F||a.Filter);let n;if(r instanceof Name)n=r.name;else if(Array.isArray(r)){const e=this.xref.fetchIfRef(r[0]);e instanceof Name&&(n=e.name)}const g=i.pos;let o,c;switch(n){case"DCT":case"DCTDecode":o=this.findDCTDecodeInlineStreamEnd(i);break;case"A85":case"ASCII85Decode":o=this.findASCII85DecodeInlineStreamEnd(i);break;case"AHx":case"ASCIIHexDecode":o=this.findASCIIHexDecodeInlineStreamEnd(i);break;default:o=this.findDefaultInlineStreamEnd(i)}if(o<1e3&&s>0){const e=i.pos;i.pos=t.beginInlineImagePos;c=function getInlineImageCacheKey(e){const t=[],i=e.length;let a=0;for(;a=a){let a=!1;for(const e of s){const t=e.length;let s=0;for(;s=r){a=!0;break}if(s>=t){if(isWhiteSpace(n[o+g+s])){info(`Found "${bytesToString([...i,...e])}" when searching for endstream command.`);a=!0}break}}if(a){t.pos+=o;return t.pos-e}}o++}t.pos+=g}return-1}makeStream(e,t){const i=this.lexer;let a=i.stream;i.skipToNextLine();const s=a.pos-1;let r=e.get("Length");if(!Number.isInteger(r)){info(`Bad length "${r&&r.toString()}" in stream.`);r=0}a.pos=s+r;i.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{r=this.#b(s);if(r<0)throw new FormatError("Missing endstream command.");i.nextChar();this.shift();this.shift()}this.shift();a=a.makeSubStream(s,r,e);t&&(a=t.createStream(a,r));a=this.filter(a,e,r);a.dict=e;return a}filter(e,t,i){let a=t.get("F","Filter"),s=t.get("DP","DecodeParms");if(a instanceof Name){Array.isArray(s)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,a.name,i,s)}let r=i;if(Array.isArray(a)){const t=a,i=s;for(let n=0,g=t.length;n=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,i=0,a=1;if(45===e){a=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){i=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let s=e-48,r=0,n=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const a=e-48;if(t)r=10*r+a;else{0!==i&&(i*=10);s=10*s+a}}else if(46===e){if(0!==i)break;i=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){n=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==i&&(s/=i);t&&(s*=10**(n*r));return a*s}getString(){let e=1,t=!1;const i=this.strBuf;i.length=0;let a=this.nextChar();for(;;){let s=!1;switch(0|a){case-1:warn("Unterminated string");t=!0;break;case 40:++e;i.push("(");break;case 41:if(0==--e){this.nextChar();t=!0}else i.push(")");break;case 92:a=this.nextChar();switch(a){case-1:warn("Unterminated string");t=!0;break;case 110:i.push("\n");break;case 114:i.push("\r");break;case 116:i.push("\t");break;case 98:i.push("\b");break;case 102:i.push("\f");break;case 92:case 40:case 41:i.push(String.fromCharCode(a));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&a;a=this.nextChar();s=!0;if(a>=48&&a<=55){e=(e<<3)+(15&a);a=this.nextChar();if(a>=48&&a<=55){s=!1;e=(e<<3)+(15&a)}}i.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:i.push(String.fromCharCode(a))}break;default:i.push(String.fromCharCode(a))}if(t)break;s||(a=this.nextChar())}return i.join("")}getName(){let e,t;const i=this.strBuf;i.length=0;for(;(e=this.nextChar())>=0&&!ai[e];)if(35===e){e=this.nextChar();if(ai[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");i.push("#");break}const a=toHexDigit(e);if(-1!==a){t=e;e=this.nextChar();const s=toHexDigit(e);if(-1===s){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);i.push("#",String.fromCharCode(t));if(ai[e])break;i.push(String.fromCharCode(e));continue}i.push(String.fromCharCode(a<<4|s))}else i.push("#",String.fromCharCode(e))}else i.push(String.fromCharCode(e));i.length>127&&warn(`Name token is longer than allowed by the spec: ${i.length}`);return Name.get(i.join(""))}_hexStringWarn(e){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,i=-1,a=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==ai[t]){a=toHexDigit(t);if(-1===a)this._hexStringWarn(t);else if(-1===i)i=a;else{e.push(String.fromCharCode(i<<4|a));i=-1}t=this.nextChar()}else t=this.nextChar()}-1!==i&&e.push(String.fromCharCode(i<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==ai[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let i=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(i)}}const a=this.knownCommands;let s=void 0!==a?.[i];for(;(t=this.nextChar())>=0&&!ai[t];){const e=i+String.fromCharCode(t);if(s&&void 0===a[e])break;if(128===i.length)throw new FormatError(`Command token too long: ${i.length}`);i=e;s=void 0!==a?.[i]}if("true"===i)return!0;if("false"===i)return!1;if("null"===i)return null;"BI"===i&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(i)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,i=!1){const a=e.get(t);if(Number.isInteger(a)&&(i?a>=0:a>0))return a;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),i=t.getObj(),a=t.getObj(),s=t.getObj(),r=t.getObj();let n,g;if(!(Number.isInteger(i)&&Number.isInteger(a)&&isCmd(s,"obj")&&r instanceof Dict&&"number"==typeof(n=r.get("Linearized"))&&n>0))return null;if((g=getInt(r,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:g,hints:function getHints(e){const t=e.get("H");let i;if(Array.isArray(t)&&(2===(i=t.length)||4===i)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(r),objectNumberFirst:getInt(r,"O"),endFirst:getInt(r,"E"),numPages:getInt(r,"N"),mainXRefEntriesOffset:getInt(r,"T"),pageFirst:r.has("P")?getInt(r,"P",!0):0}}}const si=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],ri=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,i){this.codespaceRanges[e-1].push(t,i);this.numCodespaceRanges++}mapCidRange(e,t,i){if(t-e>ri)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=i++}mapBfRange(e,t,i){if(t-e>ri)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const a=i.length-1;for(;e<=t;){this._map[e++]=i;const t=i.charCodeAt(a)+1;t>255?i=i.substring(0,a-1)+String.fromCharCode(i.charCodeAt(a-1)+1)+"\0":i=i.substring(0,a)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,i){if(t-e>ri)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const a=i.length;let s=0;for(;e<=t&&s>>0;const n=s[r];for(let e=0,t=n.length;e=t&&a<=s){i.charcode=a;i.length=r+1;return}}}i.charcode=0;i.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let i=0,a=t.length;i=s&&e<=r)return i+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,i){unreachable("should not call mapCidRange")}mapBfRange(e,t,i){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,i){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let i=0;i>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=i;e.mapOne(a,s)}}function parseBfRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endbfrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();if(Number.isInteger(i)||"string"==typeof i){const t=Number.isInteger(i)?String.fromCharCode(i):i;e.mapBfRange(a,s,t)}else{if(!isCmd(i,"["))break;{i=t.getObj();const r=[];for(;!isCmd(i,"]")&&i!==Bt;){r.push(i);i=t.getObj()}e.mapBfRangeToArray(a,s,r)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectInt(i);const s=i;e.mapOne(a,s)}}function parseCidRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcidrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const s=strToInt(i);i=t.getObj();expectInt(i);const r=i;e.mapCidRange(a,s,r)}}function parseCodespaceRange(e,t){for(;;){let i=t.getObj();if(i===Bt)break;if(isCmd(i,"endcodespacerange"))return;if("string"!=typeof i)break;const a=strToInt(i);i=t.getObj();if("string"!=typeof i)break;const s=strToInt(i);e.addCodespaceRange(i.length,a,s)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const i=t.getObj();Number.isInteger(i)&&(e.vertical=!!i)}function parseCMapName(e,t){const i=t.getObj();i instanceof Name&&(e.name=i.name)}async function parseCMap(e,t,i,a){let s,r;A:for(;;)try{const i=t.getObj();if(i===Bt)break;if(i instanceof Name){"WMode"===i.name?parseWMode(e,t):"CMapName"===i.name&&parseCMapName(e,t);s=i}else if(i instanceof Cmd)switch(i.cmd){case"endcmap":break A;case"usecmap":s instanceof Name&&(r=s.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!a&&r&&(a=r);return a?extendCMap(e,i,a):e}async function extendCMap(e,t,i){e.useCMap=await createBuiltInCMap(i,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let i=0;iextendCMap(s,t,e)));const r=new Lexer(new Stream(i));return parseCMap(s,r,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:i}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const a=await parseCMap(new CMap,new Lexer(e),t,i);return a.isIdentityCMap?createBuiltInCMap(a.name,t):a}throw new Error("Encoding required.")}}const ni=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],gi=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],oi=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Ii=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],Ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],hi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],li=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],Bi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],Qi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return li;case"StandardEncoding":return hi;case"MacRomanEncoding":return Ci;case"SymbolSetEncoding":return Bi;case"ZapfDingbatsEncoding":return Qi;case"ExpertEncoding":return Ii;case"MacExpertEncoding":return ci;default:return null}}const Ei=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],ui=391,di=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],fi=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,i){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!i}parse(){const e=this.properties,t=new CFF;this.cff=t;const i=this.parseHeader(),a=this.parseIndex(i.endPos),s=this.parseIndex(a.endPos),r=this.parseIndex(s.endPos),n=this.parseIndex(r.endPos),g=this.parseDict(s.obj.get(0)),o=this.createDict(CFFTopDict,g,t.strings);t.header=i.obj;t.names=this.parseNameIndex(a.obj);t.strings=this.parseStringIndex(r.obj);t.topDict=o;t.globalSubrIndex=n.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=o.hasName("ROS");const c=o.getByName("CharStrings"),C=this.parseIndex(c).obj,h=o.getByName("FontMatrix");h&&(e.fontMatrix=h);const l=o.getByName("FontBBox");if(l){e.ascent=Math.max(l[3],l[1]);e.descent=Math.min(l[1],l[3]);e.ascentScaled=!0}let Q,E;if(t.isCIDFont){const e=this.parseIndex(o.getByName("FDArray")).obj;for(let i=0,a=e.count;i=t)throw new FormatError("Invalid CFF header");if(0!==i){info("cff data is shifted");e=e.subarray(i);this.bytes=e}const a=e[0],s=e[1],r=e[2],n=e[3];return{obj:new CFFHeader(a,s,r,n),endPos:r}}parseDict(e){let t=0;function parseOperand(){let i=e[t++];if(30===i)return function parseFloatOperand(){let i="";const a=15,s=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],r=e.length;for(;t>4,g=15&r;if(n===a)break;i+=s[n];if(g===a)break;i+=s[g]}return parseFloat(i)}();if(28===i){i=e[t++];i=(i<<24|e[t++]<<16)>>16;return i}if(29===i){i=e[t++];i=i<<8|e[t++];i=i<<8|e[t++];i=i<<8|e[t++];return i}if(i>=32&&i<=246)return i-139;if(i>=247&&i<=250)return 256*(i-247)+e[t++]+108;if(i>=251&&i<=254)return-256*(i-251)-e[t++]-108;warn('CFFParser_parseDict: "'+i+'" is a reserved command.');return NaN}let i=[];const a=[];t=0;const s=e.length;for(;t10)return!1;let s=e.stackSize;const r=e.stack;let n=t.length;for(let g=0;g>16;g+=2;s++}else if(14===o){if(s>=4){s-=4;if(this.seacAnalysisEnabled){e.seac=r.slice(s,s+4);return!1}}c=di[o]}else if(o>=32&&o<=246){r[s]=o-139;s++}else if(o>=247&&o<=254){r[s]=o<251?(o-247<<8)+t[g]+108:-(o-251<<8)-t[g]-108;g++;s++}else if(255===o){r[s]=(t[g]<<24|t[g+1]<<16|t[g+2]<<8|t[g+3])/65536;g+=4;s++}else if(19===o||20===o){e.hints+=s>>1;if(0===e.hints){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}g+=e.hints+7>>3;s%=2;c=di[o]}else{if(10===o||29===o){const t=10===o?i:a;if(!t){c=di[o];warn("Missing subrsIndex for "+c.id);return!1}let n=32768;t.count<1240?n=107:t.count<33900&&(n=1131);const g=r[--s]+n;if(g<0||g>=t.count||isNaN(g)){c=di[o];warn("Out of bounds subrIndex for "+c.id);return!1}e.stackSize=s;e.callDepth++;if(!this.parseCharString(e,t.get(g),i,a))return!1;e.callDepth--;s=e.stackSize;continue}if(11===o){e.stackSize=s;return!0}if(0===o&&g===t.length){t[g-1]=14;c=di[14]}else{if(9===o){t.copyWithin(g-1,g,-1);g-=1;n-=1;continue}c=di[o]}}if(c){if(c.stem){e.hints+=s>>1;if(3===o||23===o)e.hasVStems=!0;else if(e.hasVStems&&(1===o||18===o)){warn("CFF stem hints are in wrong order");t[g-1]=1===o?3:23}}if("min"in c&&!e.undefStack&&s=2&&c.stem?s%=2:s>1&&warn("Found too many parameters for stack-clearing command");s>0&&(e.width=r[s-1])}if("stackDelta"in c){"stackFn"in c&&c.stackFn(r,s);s+=c.stackDelta}else if(c.stackClearing)s=0;else if(c.resetStack){s=0;e.undefStack=!1}else if(c.undefStack){s=0;e.undefStack=!0;e.firstStackClearing=!1}}}n=s.length){warn("Invalid fd index for glyph index.");h=!1}if(h){Q=s[e].privateDict;l=Q.subrsIndex}}else t&&(l=t);h&&(h=this.parseCharString(C,o,l,i));if(null!==C.width){const e=Q.getByName("nominalWidthX");g[c]=e+C.width}else{const e=Q.getByName("defaultWidthX");g[c]=e}null!==C.seac&&(n[c]=C.seac);h||e.set(c,new Uint8Array([14]))}return{charStrings:e,seacs:n,widths:g}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const i=t[0],a=t[1];if(0===i||a>=this.bytes.length){this.emptyPrivateDictionary(e);return}const s=a+i,r=this.bytes.subarray(a,s),n=this.parseDict(r),g=this.createDict(CFFPrivateDict,n,e.strings);e.privateDict=g;0===g.getByName("ExpansionFactor")&&g.setByName("ExpansionFactor",.06);if(!g.getByName("Subrs"))return;const o=g.getByName("Subrs"),c=a+o;if(0===o||c>=this.bytes.length){this.emptyPrivateDictionary(e);return}const C=this.parseIndex(c);g.subrsIndex=C.obj}parseCharsets(e,t,i,a){if(0===e)return new CFFCharset(!0,yi.ISO_ADOBE,ni);if(1===e)return new CFFCharset(!0,yi.EXPERT,gi);if(2===e)return new CFFCharset(!0,yi.EXPERT_SUBSET,oi);const s=this.bytes,r=e,n=s[e++],g=[a?0:".notdef"];let o,c,C;t-=1;switch(n){case 0:for(C=0;C=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,i,a){this.major=e;this.minor=t;this.hdrSize=i;this.offSize=a}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?Ei[e]:e-ui<=this.strings.length?this.strings[e-ui]:Ei[0]}getSID(e){let t=Ei.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+ui:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const i of t)if(isNaN(i)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const i=this.types[e];"num"!==i&&"sid"!==i&&"offset"!==i||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const i of e){const e=Array.isArray(i[0])?(i[0][0]<<8)+i[0][1]:i[0];t.keyToNameMap[e]=i[1];t.nameToKeyMap[i[1]]=e;t.types[e]=i[2];t.defaults[e]=i[3];t.opcodes[e]=Array.isArray(i[0])?i[0]:[i[0]];t.order.push(e)}return t}}const pi=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(pi))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const mi=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(mi))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const yi={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,i,a){this.predefined=e;this.format=t;this.charset=i;this.raw=a}}class CFFEncoding{constructor(e,t,i,a){this.predefined=e;this.format=t;this.encoding=i;this.raw=a}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,i){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const a=i.data,s=this.offsets[e];for(let e=0,i=t.length;e>24&255;a[n]=c>>16&255;a[g]=c>>8&255;a[o]=255&c}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},i=this.compileHeader(e.header);t.add(i);const a=this.compileNameIndex(e.names);t.add(a);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const i of e.fdArray){let e=t.slice(0);i.hasName("FontMatrix")&&(e=Util.transform(e,i.getByName("FontMatrix")));i.setByName("FontMatrix",e)}}const s=e.topDict.getByName("XUID");s?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let r=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(r.output);const n=r.trackers[0],g=this.compileStringIndex(e.strings.strings);t.add(g);const o=this.compileIndex(e.globalSubrIndex);t.add(o);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)n.setEntryLocation("Encoding",[e.encoding.format],t);else{const i=this.compileEncoding(e.encoding);n.setEntryLocation("Encoding",[t.length],t);t.add(i)}const c=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);n.setEntryLocation("charset",[t.length],t);t.add(c);const C=this.compileCharStrings(e.charStrings);n.setEntryLocation("CharStrings",[t.length],t);t.add(C);if(e.isCIDFont){n.setEntryLocation("FDSelect",[t.length],t);const i=this.compileFDSelect(e.fdSelect);t.add(i);r=this.compileTopDicts(e.fdArray,t.length,!0);n.setEntryLocation("FDArray",[t.length],t);t.add(r.output);const a=r.trackers;this.compilePrivateDicts(e.fdArray,a,t)}this.compilePrivateDicts([e.topDict],[n],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const i=CFFCompiler.EncodeFloatRegExp.exec(t);if(i){const a=parseFloat("1e"+((i[2]?+i[2]:0)+i[1].length));t=(Math.round(e*a)/a).toString()}let a,s,r="";for(a=0,s=t.length;a=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const i of e){const e=Math.min(i.length,127);let a=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");a[t]=e}a=a.join("");""===a&&(a="Bad_Font_Name");t.add(stringToBytes(a))}return this.compileIndex(t)}compileTopDicts(e,t,i){const a=[];let s=new CFFIndex;for(const r of e){if(i){r.removeByName("CIDFontVersion");r.removeByName("CIDFontRevision");r.removeByName("CIDFontType");r.removeByName("CIDCount");r.removeByName("UIDBase")}const e=new CFFOffsetTracker,n=this.compileDict(r,e);a.push(e);s.add(n);e.offset(t)}s=this.compileIndex(s,a);return{trackers:a,output:s}}compilePrivateDicts(e,t,i){for(let a=0,s=e.length;a>8&255,255&r]);else{s=new Uint8Array(1+2*r);s[0]=0;let t=0;const a=e.charset.length;let n=!1;for(let r=1;r>8&255;s[r+1]=255&g}}return this.compileTypedArray(s)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let i,a;switch(t){case 0:i=new Uint8Array(1+e.fdSelect.length);i[0]=t;for(a=0;a>8&255,255&s,r];for(a=1;a>8&255,255&a,t);r=t}}const g=(n.length-3)/3;n[1]=g>>8&255;n[2]=255&g;n.push(a>>8&255,255&a);i=new Uint8Array(n)}return this.compileTypedArray(i)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const i=e.objects,a=i.length;if(0===a)return[0,0];const s=[a>>8&255,255&a];let r,n,g=1;for(r=0;r>8&255,255&o):3===n?s.push(o>>16&255,o>>8&255,255&o):s.push(o>>>24&255,o>>16&255,o>>8&255,255&o);i[r]&&(o+=i[r].length)}for(r=0;r=5&&t<=7))return-1;a=e.substring(1)}if(a===a.toUpperCase()){i=parseInt(a,16);if(i>=0)return i}}return-1}const Fi=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const i=Fi[t];for(let a=0,s=i.length;a=i[a]&&e<=i[a+1])return t}for(let t=0,i=Fi.length;t=i[a]&&e<=i[a+1])return t}return-1}const Si=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),ki=new Map;const Ri=!0,Ni=1,Gi=2,Mi=4,xi=32,Hi=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const i=getUnicodeForGlyph(e,t);if(-1!==i)for(const e in t)if(t[e]===i)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,i){const a=Object.create(null);let s,r,n;const g=!!(e.flags&Mi);if(e.isInternalFont){n=t;for(r=0;r=0?s:0}}else if(e.baseEncodingName){n=getEncoding(e.baseEncodingName);for(r=0;r=0?s:0}}else if(g)for(r in t)a[r]=t[r];else{n=hi;for(r=0;r=0?s:0}}const o=e.differences;let c;if(o)for(r in o){const e=o[r];s=i.indexOf(e);if(-1===s){c||(c=wi());const t=recoverGlyphName(e,c);t!==e&&(s=i.indexOf(t))}a[r]=s>=0?s:0}return a}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Ji=getLookupTableFactory((e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080})),Yi=getLookupTableFactory((function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["HelveticaLTStd-Bold"]="Helvetica-Bold";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"})),vi=getLookupTableFactory((function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),Ki=getLookupTableFactory((function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.GillSansMT="Helvetica";e["GillSansMT-Bold"]="Helvetica-Bold";e["GillSansMT-BoldItalic"]="Helvetica-BoldOblique";e["GillSansMT-Italic"]="Helvetica-Oblique";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"})),Ti=getLookupTableFactory((function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0})),qi=getLookupTableFactory((function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0})),Oi=getLookupTableFactory((function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377})),Pi=getLookupTableFactory((function(e){e[227]=322;e[264]=261;e[291]=346})),Wi=getLookupTableFactory((function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45}));function getStandardFontName(e){const t=normalizeFontName(e);return Yi()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Yi()[t]||Ki()[t]||Ti()[t]||qi()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].codePointAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const i in t)if(t[i]===e)return 0|i;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,i=this.lastChar;t<=i;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const i=new CFFParser(e,t,Ri);this.cff=i.parse();this.cff.duplicateFirstGlyph();const a=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=a.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:i,cMap:a}=t,s=e.charset.charset;let r,n;if(t.composite){let t,g;if(i?.length>0){t=Object.create(null);for(let e=0,a=i.length;e=0){const a=i[t];a&&(s[e]=a)}}s.length>0&&(this.properties.builtInEncoding=s)}}function getUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function getUint16(e,t){return e[t]<<8|e[t+1]}function getInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function getInt8(e,t){return e[t]<<24>>24}function getFloat214(e,t){return getInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let i=32768;t<1240?i=107:t<33900&&(i=1131);return i}function parseCmap(e,t,i){const a=1===getUint16(e,t+2)?getUint32(e,t+8):getUint32(e,t+16),s=getUint16(e,t+a);let r,n,g;if(4===s){getUint16(e,t+a+2);const i=getUint16(e,t+a+6)>>1;n=t+a+14;r=[];for(g=0;g>1;i0;)C.push({flags:r})}for(i=0;i>1;p=!0;break;case 4:n+=s.pop();moveTo(r,n);p=!0;break;case 5:for(;s.length>0;){r+=s.shift();n+=s.shift();lineTo(r,n)}break;case 6:for(;s.length>0;){r+=s.shift();lineTo(r,n);if(0===s.length)break;n+=s.shift();lineTo(r,n)}break;case 7:for(;s.length>0;){n+=s.shift();lineTo(r,n);if(0===s.length)break;r+=s.shift();lineTo(r,n)}break;case 8:for(;s.length>0;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 10:d=s.pop();f=null;if(i.isCFFCIDFont){const e=i.fdSelect.getFDIndex(a);if(e>=0&&eMath.abs(n-t)?r+=s.shift():n+=s.shift();bezierCurveTo(c,h,C,l,r,n);break;default:throw new FormatError(`unknown operator: 12 ${m}`)}break;case 14:if(s.length>=4){const e=s.pop(),a=s.pop();n=s.pop();r=s.pop();t.save();t.translate(r,n);let g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[e]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId);t.restore();g=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[hi[a]]));compileCharString(i.glyphs[g.glyphId],t,i,g.glyphId)}return;case 19:case 20:g+=s.length>>1;o+=g+7>>3;p=!0;break;case 21:n+=s.pop();r+=s.pop();moveTo(r,n);p=!0;break;case 22:r+=s.pop();moveTo(r,n);p=!0;break;case 24:for(;s.length>2;){c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}r+=s.shift();n+=s.shift();lineTo(r,n);break;case 25:for(;s.length>6;){r+=s.shift();n+=s.shift();lineTo(r,n)}c=r+s.shift();h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+s.shift();bezierCurveTo(c,h,C,l,r,n);break;case 26:s.length%2&&(r+=s.shift());for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C;n=l+s.shift();bezierCurveTo(c,h,C,l,r,n)}break;case 27:s.length%2&&(n+=s.shift());for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l;bezierCurveTo(c,h,C,l,r,n)}break;case 28:s.push((e[o]<<24|e[o+1]<<16)>>16);o+=2;break;case 29:d=s.pop()+i.gsubrsBias;f=i.gsubrs[d];f&&parse(f);break;case 30:for(;s.length>0;){c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;case 31:for(;s.length>0;){c=r+s.shift();h=n;C=c+s.shift();l=h+s.shift();n=l+s.shift();r=C+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n);if(0===s.length)break;c=r;h=n+s.shift();C=c+s.shift();l=h+s.shift();r=C+s.shift();n=l+(1===s.length?s.shift():0);bezierCurveTo(c,h,C,l,r,n)}break;default:if(m<32)throw new FormatError(`unknown operator: ${m}`);if(m<247)s.push(m-139);else if(m<251)s.push(256*(m-247)+e[o++]+108);else if(m<255)s.push(256*-(m-251)-e[o++]-108);else{s.push((e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])/65536);o+=4}}p&&(s.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const[i,a,s,r,n,g]=this.currentTransform;for(let e=0,o=t.length;e=0&&e2*getUint16(e,t)}const r=[];let n=s(t,0);for(let i=a;ie+(t.getSize()+3&-4)),0)}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),i=e>131070,a=i?4:2,s=new DataView(new ArrayBuffer((this.glyphs.length+1)*a));i?s.setUint32(0,0):s.setUint16(0,0);let r=0,n=0;for(const e of this.glyphs){r+=e.write(r,t);r=r+3&-4;n+=a;i?s.setUint32(n,r):s.setUint16(n,r>>1)}return{isLocationLong:i,loca:new Uint8Array(s.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,i=this.glyphs.length;te+t.getSize()),0);return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const i=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const i of this.composites)e+=i.write(e,t);return e-i}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const i of this.composites)i.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:i,xMax:a,yMax:s}){this.numberOfContours=e;this.xMin=t;this.yMin=i;this.xMax=a;this.yMax=s}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:i}){this.xCoordinates=t;this.yCoordinates=i;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,i){const a=[];for(let s=0;s255?e+=2:g>0&&(e+=1);t=r;g=Math.abs(n-i);g>255?e+=2:g>0&&(e+=1);i=n}}return e}write(e,t){const i=e,a=[],s=[],r=[];let n=0,g=0;for(const i of this.contours){for(let e=0,t=i.xCoordinates.length;e=0?18:2;a.push(e)}else a.push(c)}n=o;const C=i.yCoordinates[e];c=C-g;if(0===c){t|=32;s.push(0)}else{const e=Math.abs(c);if(e<=255){t|=c>=0?36:4;s.push(e)}else s.push(c)}g=C;r.push(t)}t.setUint16(e,a.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const i of r)t.setUint8(e++,i);for(let i=0,s=a.length;i=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const i=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-i}scale(e,t){}}function writeInt16(e,t,i){e[t]=i>>8&255;e[t+1]=255&i}function writeInt32(e,t,i){e[t]=i>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}function writeData(e,t,i){if(i instanceof Uint8Array)e.set(i,t);else if("string"==typeof i)for(let a=0,s=i.length;ai;){i<<=1;a++}const s=i*t;return{range:s,entry:a,rangeShift:t*e-s}}toArray(){let e=this.sfnt;const t=this.tables,i=Object.keys(t);i.sort();const a=i.length;let s,r,n,g,o,c=12+16*a;const C=[c];for(s=0;s>>0;C.push(c)}const h=new Uint8Array(c);for(s=0;s>>0}writeInt32(h,c+4,e);writeInt32(h,c+8,C[s]);writeInt32(h,c+12,t[o].length);c+=16}return h}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const Zi=[4],Vi=[5],zi=[6],_i=[7],$i=[8],Aa=[12,35],ea=[14],ta=[21],ia=[22],aa=[30],sa=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,i){const a=e.length;let s,r,n,g=!1;for(let o=0;oa)return!0;const s=a-e;for(let e=s;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);i?this.stack.splice(s,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,i){if(i>=e.length)return new Uint8Array(0);let a,s,r=0|t;for(a=0;a>8;r=52845*(t+r)+22719&65535}return g}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,i){if(t){const t=e.getBytes(),i=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(i?decrypt(t,55665,4):function decryptAscii(e,t,i){let a=0|t;const s=e.length,r=new Uint8Array(s>>>1);let n,g;for(n=0,g=0;n>8;a=52845*(e+a)+22719&65535}}return r.slice(i,g)}(t,55665,4))}this.seacAnalysisEnabled=!!i;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let i="";do{i+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return i}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,i=[],a=[],s=Object.create(null);s.lenIV=4;const r={subrs:[],charstrings:[],properties:{privateData:s}};let n,g,o,c;for(;null!==(n=this.getToken());)if("/"===n){n=this.getToken();switch(n){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){n=this.getToken();if(null===n||"end"===n)break;if("/"!==n)continue;const e=this.getToken();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const i=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n?this.getToken():"/"===n&&this.prevChar();a.push({glyph:e,encoded:i})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();g=this.readInt();this.getToken();o=g>0?t.getBytes(g):new Uint8Array(0);c=r.properties.privateData.lenIV;const a=this.readCharStrings(o,c);this.nextChar();n=this.getToken();"noaccess"===n&&this.getToken();i[e]=a}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":r.properties.privateData[n]=this.readNumberArray();break;case"StdHW":case"StdVW":r.properties.privateData[n]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":r.properties.privateData[n]=this.readNumber();break;case"ExpansionFactor":r.properties.privateData[n]=this.readNumber()||.06;break;case"ForceBold":r.properties.privateData[n]=this.readBoolean()}}for(const{encoded:t,glyph:s}of a){const a=new Type1CharString,n=a.convert(t,i,this.seacAnalysisEnabled);let g=a.output;n&&(g=[14]);const o={glyphName:s,charstring:g,width:a.width,lsb:a.lsb,seac:a.seac};".notdef"===s?r.charstrings.unshift(o):r.charstrings.push(o);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(s);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=a.width)}}return r}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const i=this.readNumberArray();e.fontMatrix=i;break;case"Encoding":const a=this.getToken();let s;if(/^\d+$/.test(a)){s=[];const e=0|parseInt(a,10);this.getToken();for(let i=0;i=s){n+=i;for(;n=0&&(a[e]=s)}}return type1FontGlyphMapping(e,a,i)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let i=0,a=e.length;i0;e--)t[e]-=t[e-1];Q.setByName(e,t)}r.topDict.privateDict=Q;const u=new CFFIndex;for(C=0,h=a.length;C0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,i,a,s,r,n,g,o){this.originalCharCode=e;this.fontChar=t;this.unicode=i;this.accent=a;this.width=s;this.vmetric=r;this.operatorListId=n;this.isSpace=g;this.isInFont=o}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=ki.get(e);if(t)return t;const i=e.match(Si),a={isWhitespace:!!i?.[1],isZeroWidthDiacritic:!!i?.[2],isInvisibleFormatMark:!!i?.[3]};ki.set(e,a);return a}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,i){e[t+1]=i;e[t]=i>>>8}function signedInt16(e,t){const i=(e<<8)+t;return 32768&i?i-65536:i}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:i,composite:a}){let s,r;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))s=a?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))s=a?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))s=a?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(a){s="CIDFontType0";r="CIDFontType0C"}else{s="MMType1"===t?"MMType1":"Type1";r="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");s=t;r=i}return[s,r]}function applyStandardFontGlyphMap(e,t){for(const i in t)e[+i]=t[i]}function buildToFontChar(e,t,i){const a=[];let s;for(let i=0,r=e.length;iC){o++;if(o>=ra.length){warn("Ran out of space in font private use area.");break}c=ra[o][0];C=ra[o][1]}const E=c++;0===Q&&(Q=i);let u=a.get(l);"string"==typeof u&&(u=u.codePointAt(0));if(u&&!(h=u,ra[0][0]<=h&&h<=ra[0][1]||ra[1][0]<=h&&h<=ra[1][1])&&!g.has(Q)){r.set(u,Q);g.add(Q)}s[E]=Q;n[l]=E}var h;return{toFontChar:n,charCodeToGlyphId:s,toUnicodeExtraMap:r,nextAvailableFontCharCode:c}}function createCmapTable(e,t,i){const a=function getRanges(e,t,i){const a=[];for(const t in e)e[t]>=i||a.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,s]of t)s>=i||a.push({fontCharCode:e,glyphId:s});0===a.length&&a.push({fontCharCode:0,glyphId:0});a.sort((function fontGetRangesSort(e,t){return e.fontCharCode-t.fontCharCode}));const s=[],r=a.length;for(let e=0;e65535?2:1;let r,n,g,o,c="\0\0"+string16(s)+"\0\0"+string32(4+8*s);for(r=a.length-1;r>=0&&!(a[r][0]<=65535);--r);const C=r+1;a[r][0]<65535&&65535===a[r][1]&&(a[r][1]=65534);const h=a[r][1]<65535?1:0,l=C+h,Q=OpenTypeFileBuilder.getSearchParams(l,2);let E,u,d,f,p="",m="",y="",w="",D="",b=0;for(r=0,n=C;r0){m+="ÿÿ";p+="ÿÿ";y+="\0";w+="\0\0"}const F="\0\0"+string16(2*l)+string16(Q.range)+string16(Q.entry)+string16(Q.rangeShift)+m+"\0\0"+p+y+w+D;let S="",k="";if(s>1){c+="\0\0\n"+string32(4+8*s+4+F.length);S="";for(r=0,n=a.length;re||!g)&&(g=e);o 123 are reserved for internal usage");n|=1<65535&&(o=65535)}else{g=0;o=255}const C=e.bbox||[0,0,0,0],h=i.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),l=e.ascentScaled?1:h/na,Q=i.ascent||Math.round(l*(e.ascent||C[3]));let E=i.descent||Math.round(l*(e.descent||C[1]));E>0&&e.descent>0&&C[1]<0&&(E=-E);const u=i.yMax||Q,d=-i.yMin||-E;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(a)+string32(s)+string32(r)+string32(n)+"*21*"+string16(e.italicAngle?1:0)+string16(g||e.firstChar)+string16(o||e.lastChar)+string16(Q)+string16(E)+"\0d"+string16(u)+string16(d)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(g||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const i=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],a=[];let s,r,n,g,o;for(s=0,r=i.length;s0;if((n||g)&&"CIDFontType2"===i&&this.cidEncoding.startsWith("Identity-")){const i=e.cidToGidMap,a=[];applyStandardFontGlyphMap(a,Oi());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(a,Pi()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(a,Wi());if(i){for(const e in a){const t=a[e];void 0!==i[t]&&(a[+e]=i[t])}i.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach((function(e,t){const s=a[e];void 0===i[s]&&(a[+e]=t)}))}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(e,t){a[+e]=t}));this.toFontChar=a;this.toUnicode=new ToUnicodeMap(a)}else if(/Symbol/i.test(a))this.toFontChar=buildToFontChar(Bi,wi(),this.differences);else if(/Dingbats/i.test(a))this.toFontChar=buildToFontChar(Qi,Di(),this.differences);else if(n||g){const e=buildToFontChar(this.defaultEncoding,wi(),this.differences);"CIDFontType2"!==i||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(t,i){e[+t]=i}));this.toFontChar=e}else{const e=wi(),i=[];this.toUnicode.forEach(((t,a)=>{if(!this.composite){const i=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==i&&(a=i)}i[+t]=a}));this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(i,Oi());this.toFontChar=i}amendFallbackToUnicode(e);this.loadedName=a.split("-",1)[0]}checkAndRepair(e,t,i){const a=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const i=Object.create(null);i["OS/2"]=null;i.cmap=null;i.head=null;i.hhea=null;i.hmtx=null;i.maxp=null;i.name=null;i.post=null;for(let s=0;s>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0,r=e.pos;e.pos=e.start||0;e.skip(a);const n=e.getBytes(s);e.pos=r;if("head"===t){n[8]=n[9]=n[10]=n[11]=0;n[17]|=32}return{tag:t,checksum:i,length:s,offset:a,data:n}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,i,a,s,r){const n={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||i>e.length||i-t<=12)return n;const g=e.subarray(t,i),o=signedInt16(g[2],g[3]),c=signedInt16(g[4],g[5]),C=signedInt16(g[6],g[7]),h=signedInt16(g[8],g[9]);if(o>C){writeSignedInt16(g,2,C);writeSignedInt16(g,6,o)}if(c>h){writeSignedInt16(g,4,h);writeSignedInt16(g,8,c)}const l=signedInt16(g[0],g[1]);if(l<0){if(l<-1)return n;a.set(g,s);n.length=g.length;return n}let Q,E=10,u=0;for(Q=0;Qg.length)return n;if(!r&&f>0){a.set(g.subarray(0,d),s);a.set([0,0],s+d);a.set(g.subarray(p,y),s+d+2);y-=f;g.length-y>3&&(y=y+3&-4);n.length=y;return n}if(g.length-y>3){y=y+3&-4;a.set(g.subarray(0,y),s);n.length=y;return n}a.set(g,s);n.length=g.length;return n}function readNameTable(e){const i=(t.start||0)+e.offset;t.pos=i;const a=[[],[]],s=[],r=e.length,n=i+r;if(0!==t.getUint16()||r<6)return[a,s];const g=t.getUint16(),o=t.getUint16();let c,C;for(c=0;cn)continue;t.pos=r;const g=e.name;if(e.encoding){let i="";for(let a=0,s=e.length;a0&&(c+=e-1)}}else{if(d||p){warn("TT: nested FDEFs not allowed");u=!0}d=!0;h=c;n=l.pop();t.functionsDefined[n]={data:o,i:c}}else if(!d&&!p){n=l.at(-1);if(isNaN(n))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[n]=!0;if(n in t.functionsStackDeltas){const e=l.length+t.functionsStackDeltas[n];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}l.length=e}else if(n in t.functionsDefined&&!E.includes(n)){Q.push({data:o,i:c,stackTop:l.length-1});E.push(n);g=t.functionsDefined[n];if(!g){warn("TT: CALL non-existent function");t.hintsValid=!1;return}o=g.data;c=g.i}}}if(!d&&!p){let t=0;e<=142?t=s[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){a=l.pop();isNaN(a)||(t=2*-a)}for(;t<0&&l.length>0;){l.pop();t++}for(;t>0;){l.push(NaN);t--}}}t.tooComplexToFollowFunctions=u;const m=[o];c>o.length&&m.push(new Uint8Array(c-o.length));if(h>C){warn("TT: complementing a missing function tail");m.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let i,a,s=0;for(i=0,a=t.length;i>>0,r=[];for(let t=0;t>>0);const n={ttcTag:t,majorVersion:i,minorVersion:a,numFonts:s,offsetTable:r};switch(i){case 1:return n;case 2:n.dsigTag=e.getInt32()>>>0;n.dsigLength=e.getInt32()>>>0;n.dsigOffset=e.getInt32()>>>0;return n}throw new FormatError(`Invalid TrueType Collection majorVersion: ${i}.`)}(e),s=t.split("+");let r;for(let n=0;n0||!(i.cMap instanceof IdentityCMap));if("OTTO"===r.version&&!t||!n.head||!n.hhea||!n.maxp||!n.post){o=new Stream(n["CFF "].data);g=new CFFFont(o,i);adjustWidths(i);return this.convert(e,g,i)}delete n.glyf;delete n.loca;delete n.fpgm;delete n.prep;delete n["cvt "];this.isOpenType=!0}if(!n.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+n.maxp.offset;let C=t.getInt32();const h=t.getUint16();if(65536!==C&&20480!==C){if(6===n.maxp.length)C=20480;else{if(!(n.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');C=65536}!function writeUint32(e,t,i){e[t+3]=255&i;e[t+2]=i>>>8;e[t+1]=i>>>16;e[t]=i>>>24}(n.maxp.data,0,C)}if(i.scaleFactors?.length===h&&c){const{scaleFactors:e}=i,t=int16(n.head.data[50],n.head.data[51]),a=new GlyfTable({glyfTable:n.glyf.data,isGlyphLocationsLong:t,locaTable:n.loca.data,numGlyphs:h});a.scale(e);const{glyf:s,loca:r,isLocationLong:g}=a.write();n.glyf.data=s;n.loca.data=r;if(g!==!!t){n.head.data[50]=0;n.head.data[51]=g?1:0}const o=n.hmtx.data;for(let t=0;t>8&255;o[i+1]=255&a;writeSignedInt16(o,i+2,Math.round(e[t]*signedInt16(o[i+2],o[i+3])))}}let l=h+1,Q=!0;if(l>65535){Q=!1;l=h;warn("Not enough space in glyfs to duplicate first glyph.")}let E=0,u=0;if(C>=65536&&n.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){n.maxp.data[14]=0;n.maxp.data[15]=2}t.pos+=4;E=t.getUint16();t.pos+=4;u=t.getUint16()}n.maxp.data[4]=l>>8;n.maxp.data[5]=255&l;const d=function sanitizeTTPrograms(e,t,i,a){const s={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,s);t&&sanitizeTTProgram(t,s);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let i=0,a=e.functionsUsed.length;it){warn("TT: invalid function id: "+i);e.hintsValid=!1;return}if(e.functionsUsed[i]&&!e.functionsDefined[i]){warn("TT: undefined function: "+i);e.hintsValid=!1;return}}}(s,a);if(i&&1&i.length){const e=new Uint8Array(i.length+1);e.set(i.data);i.data=e}return s.hintsValid}(n.fpgm,n.prep,n["cvt "],E);if(!d){delete n.fpgm;delete n.prep;delete n["cvt "]}!function sanitizeMetrics(e,t,i,a,s,r){if(!t){i&&(i.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const n=e.getUint16();e.pos+=8;e.pos+=2;let g=e.getUint16();if(0!==n){if(!(2&int16(a.data[44],a.data[45]))){t.data[22]=0;t.data[23]=0}}if(g>s){info(`The numOfMetrics (${g}) should not be greater than the numGlyphs (${s}).`);g=s;t.data[34]=(65280&g)>>8;t.data[35]=255&g}const o=s-g-(i.length-4*g>>1);if(o>0){const e=new Uint8Array(i.length+2*o);e.set(i.data);if(r){e[i.length]=i.data[2];e[i.length+1]=i.data[3]}i.data=e}}(t,n.hhea,n.hmtx,n.head,l,Q);if(!n.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,i){const a=e.data,s=function int32(e,t,i,a){return(e<<24)+(t<<16)+(i<<8)+a}(a[0],a[1],a[2],a[3]);if(s>>16!=1){info("Attempting to fix invalid version in head table: "+s);a[0]=0;a[1]=1;a[2]=0;a[3]=0}const r=int16(a[50],a[51]);if(r<0||r>1){info("Attempting to fix invalid indexToLocFormat in head table: "+r);const e=t+1;if(i===e<<1){a[50]=0;a[51]=0}else{if(i!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+r);a[50]=0;a[51]=1}}}(n.head,h,c?n.loca.length:0);let f=Object.create(null);if(c){const e=int16(n.head.data[50],n.head.data[51]),t=function sanitizeGlyphLocations(e,t,i,a,s,r,n){let g,o,c;if(a){g=4;o=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};c=function fontItemEncodeLong(e,t,i){e[t]=i>>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}}else{g=2;o=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};c=function fontItemEncode(e,t,i){e[t]=i>>9&255;e[t+1]=i>>1&255}}const C=r?i+1:i,h=g*(1+C),l=new Uint8Array(h);l.set(e.data.subarray(0,h));e.data=l;const Q=t.data,E=Q.length,u=new Uint8Array(E);let d,f;const p=[];for(d=0,f=0;dE&&(e=E);p.push({index:d,offset:e,endOffset:0})}p.sort(((e,t)=>e.offset-t.offset));for(d=0;de.index-t.index));for(d=0;dn&&(n=e.sizeOfInstructions);w+=t;c(l,f,w)}if(0===w){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(d=0,f=g;di+w)t.data=u.subarray(0,i+w);else{t.data=new Uint8Array(i+w);t.data.set(u.subarray(0,w))}t.data.set(u.subarray(0,i),w);c(e.data,l.length-g,w+i)}else t.data=u.subarray(0,w);return{missingGlyphs:y,maxSizeOfInstructions:n}}(n.loca,n.glyf,h,e,d,Q,u);f=t.missingGlyphs;if(C>=65536&&n.maxp.length>=32){n.maxp.data[26]=t.maxSizeOfInstructions>>8;n.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!n.hhea)throw new FormatError('Required "hhea" table is not found');if(0===n.hhea.data[10]&&0===n.hhea.data[11]){n.hhea.data[10]=255;n.hhea.data[11]=255}const p={unitsPerEm:int16(n.head.data[18],n.head.data[19]),yMax:signedInt16(n.head.data[42],n.head.data[43]),yMin:signedInt16(n.head.data[38],n.head.data[39]),ascent:signedInt16(n.hhea.data[4],n.hhea.data[5]),descent:signedInt16(n.hhea.data[6],n.hhea.data[7]),lineGap:signedInt16(n.hhea.data[8],n.hhea.data[9])};this.ascent=p.ascent/p.unitsPerEm;this.descent=p.descent/p.unitsPerEm;this.lineGap=p.lineGap/p.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;n.post&&function readPostScriptTable(e,i,a){const s=(t.start||0)+e.offset;t.pos=s;const r=s+e.length,n=t.getInt32();t.skip(28);let g,o,c=!0;switch(n){case 65536:g=Hi;break;case 131072:const e=t.getUint16();if(e!==a){c=!1;break}const s=[];for(o=0;o=32768){c=!1;break}s.push(e)}if(!c)break;const C=[],h=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let s=-1;t?s=a:void 0!==e[a]&&(s=e[a]);s>=0&&s>>0;let C=!1;if(g?.platformId!==s||g?.encodingId!==r){if(0!==s||0!==r&&1!==r&&3!==r)if(1===s&&0===r)C=!0;else if(3!==s||1!==r||!a&&g){if(i&&3===s&&0===r){C=!0;let i=!0;if(e>3;e.push(a);i=Math.max(a,i)}const a=[];for(let e=0;e<=i;e++)a.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let i=0;i<256;i++)if(0===e[i]){t.pos=a[0].idRangePos+2*i;Q=t.getUint16();h.push({charCode:i,glyphId:Q})}else{const s=a[e[i]];for(l=0;l>1;t.skip(6);const i=[];let a;for(a=0;a>1)-(e-a);s.offsetIndex=n;g=Math.max(g,n+s.end-s.start+1)}else s.offsetIndex=-1}const o=[];for(l=0;l>>0;for(l=0;l>>0,i=t.getInt32()>>>0;let a=t.getInt32()>>>0;for(let t=e;t<=i;t++)h.push({charCode:t,glyphId:a++})}}}h.sort((function(e,t){return e.charCode-t.charCode}));for(let e=1;e=61440&&t<=61695&&(t&=255);m[t]=e.glyphId}else for(const e of r)m[e.charCode]=e.glyphId;if(i.glyphNames&&(g.length||this.differences.length))for(let e=0;e<256;++e){if(!o&&void 0!==m[e])continue;const t=this.differences[e]||g[e];if(!t)continue;const a=i.glyphNames.indexOf(t);a>0&&hasGlyph(a)&&(m[e]=a)}}0===m.length&&(m[0]=0);let y=l-1;Q||(y=0);if(!i.cssFontInfo){const e=adjustMapping(m,hasGlyph,y,this.toUnicode);this.toFontChar=e.toFontChar;n.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,l)};n["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const i=t.getUint16();t.skip(60);const a=t.getUint16();if(i<4&&768&a)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(n["OS/2"],t)||(n["OS/2"]={tag:"OS/2",data:createOS2Table(i,e.charCodeToGlyphId,p)})}if(!c)try{o=new Stream(n["CFF "].data);g=new CFFParser(o,i,Ri).parse();g.duplicateFirstGlyph();const e=new CFFCompiler(g);n["CFF "].data=e.compile()}catch{warn("Failed to compile font "+i.loadedName)}if(n.name){const[t,a]=readNameTable(n.name);n.name.data=createNameTable(e,t);this.psName=t[0][6]||null;i.composite||function adjustTrueTypeToUnicode(e,t,i){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===i.length)return;if(e.defaultEncoding===li)return;for(const e of i)if(!isWinNameRecord(e))return;const a=li,s=[],r=wi();for(const e in a){const t=a[e];if(""===t)continue;const i=r[t];void 0!==i&&(s[e]=String.fromCharCode(i))}s.length>0&&e.toUnicode.amend(s)}(i,this.isSymbolicFont,a)}else n.name={tag:"name",data:createNameTable(this.name)};const w=new OpenTypeFileBuilder(r.version);for(const e in n)w.addTable(e,n[e].data);return w.toArray()}convert(e,t,i){i.fixedPitch=!1;i.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const i=[],a=wi();for(const s in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[s]))continue;const r=getUnicodeForGlyph(t[s],a);-1!==r&&(i[s]=String.fromCharCode(r))}i.length>0&&e.toUnicode.amend(i)}(i,i.builtInEncoding);let s=1;t instanceof CFFFont&&(s=t.numGlyphs-1);const r=t.getGlyphMapping(i);let n=null,g=r,o=null;if(!i.cssFontInfo){n=adjustMapping(r,t.hasGlyphId.bind(t),s,this.toUnicode);this.toFontChar=n.toFontChar;g=n.charCodeToGlyphId;o=n.toUnicodeExtraMap}const c=t.numGlyphs;function getCharCodes(e,t){let i=null;for(const a in e)t===e[a]&&(i||=[]).push(0|a);return i}function createCharCode(e,t){for(const i in e)if(t===e[i])return 0|i;n.charCodeToGlyphId[n.nextAvailableFontCharCode]=t;return n.nextAvailableFontCharCode++}const C=t.seacs;if(n&&C?.length){const e=i.fontMatrix||a,s=t.getCharset(),g=Object.create(null);for(let t in C){t|=0;const i=C[t],a=hi[i[2]],o=hi[i[3]],c=s.indexOf(a),h=s.indexOf(o);if(c<0||h<0)continue;const l={x:i[0]*e[0]+i[1]*e[2]+e[4],y:i[0]*e[1]+i[1]*e[3]+e[5]},Q=getCharCodes(r,t);if(Q)for(const e of Q){const t=n.charCodeToGlyphId,i=createCharCode(t,c),a=createCharCode(t,h);g[e]={baseFontCharCode:i,accentFontCharCode:a,accentOffset:l}}}i.seacMap=g}const h=i.fontMatrix?1/Math.max(...i.fontMatrix.slice(0,4).map(Math.abs)):1e3,l=new OpenTypeFileBuilder("OTTO");l.addTable("CFF ",t.data);l.addTable("OS/2",createOS2Table(i,g));l.addTable("cmap",createCmapTable(g,o,c));l.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(h)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(i.descent)+"ÿ"+safeString16(i.ascent)+string16(i.italicAngle?2:0)+"\0\0\0\0\0\0\0");l.addTable("hhea","\0\0\0"+safeString16(i.ascent)+safeString16(i.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(i.capHeight)+safeString16(Math.tan(i.italicAngle)*i.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(c));l.addTable("hmtx",function fontFieldsHmtx(){const e=t.charstrings,i=t.cff?t.cff.widths:null;let a="\0\0\0\0";for(let t=1,s=c;t=65520&&e<=65535?0:e>=62976&&e<=63743?bi()[e]||e:173===e?45:e}(i)}this.isType3Font&&(s=i);let C=null;if(this.seacMap?.[e]){c=!0;const t=this.seacMap[e];i=t.baseFontCharCode;C={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let h="";"number"==typeof i&&(i<=1114111?h=String.fromCodePoint(i):warn(`charToGlyph - invalid fontCharCode: ${i}`));if(this.missingFile&&this.vertical&&1===h.length){const e=Ji()[h.charCodeAt(0)];e&&(h=o=String.fromCharCode(e))}r=new fonts_Glyph(e,h,o,C,a,g,s,t,c);return this._glyphCache[e]=r}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const i=Object.create(null),a=e.length;let s=0;for(;st.length%2==1,a=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let s=0,r=e.length;s55295&&(r<57344||r>65533)&&s++;if(this.toUnicode){const e=a(r);if(-1!==e){if(hasCurrentBufErrors()){t.push(i.join(""));i.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)i.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(i.join(""));i.length=0}i.push(String.fromCodePoint(r))}t.push(i.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(e=!1){return{error:this.error}}}const Ia=2,ca=3,Ca=4,ha=5,la=6,Ba=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,i,a,s){const r=e instanceof BaseStream?e.dict:e,n=r.get("ShadingType");try{switch(n){case Ia:case ca:return new RadialAxialShading(r,t,i,a,s);case Ca:case ha:case la:case Ba:return new MeshShading(e,t,i,a,s);default:throw new FormatError("Unsupported ShadingType: "+n)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,i,a,s){super();this.shadingType=e.get("ShadingType");let r=0;this.shadingType===Ia?r=4:this.shadingType===ca&&(r=6);this.coordsArr=e.getArray("Coords");if(!isNumberArray(this.coordsArr,r))throw new FormatError("RadialAxialShading: Invalid /Coords array.");const n=ColorSpace.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:i,pdfFunctionFactory:a,localColorSpaceCache:s});this.bbox=lookupNormalRect(e.getArray("BBox"),null);let g=0,o=1;const c=e.getArray("Domain");isNumberArray(c,2)&&([g,o]=c);let C=!1,h=!1;const l=e.getArray("Extend");(function isBooleanArray(e,t){return Array.isArray(e)&&(null===t||e.length===t)&&e.every((e=>"boolean"==typeof e))})(l,2)&&([C,h]=l);if(!(this.shadingType!==ca||C&&h)){const[e,t,i,a,s,r]=this.coordsArr,n=Math.hypot(e-a,t-s);i<=r+n&&r<=i+n&&warn("Unsupported radial gradient.")}this.extendStart=C;this.extendEnd=h;const Q=e.getRaw("Function"),E=a.createFromArray(Q),u=(o-g)/840,d=this.colorStops=[];if(g>=o||u<=0){info("Bad shading domain.");return}const f=new Float32Array(n.numComps),p=new Float32Array(1);let m,y=0;p[0]=g;E(p,0,f,0);let w=n.getRgb(f,0);const D=Util.makeHexColor(w[0],w[1],w[2]);d.push([0,D]);let b=1;p[0]=g+u;E(p,0,f,0);let F=n.getRgb(f,0),S=F[0]-w[0]+1,k=F[1]-w[1]+1,R=F[2]-w[2]+1,N=F[0]-w[0]-1,G=F[1]-w[1]-1,M=F[2]-w[2]-1;for(let e=2;e<840;e++){p[0]=g+e*u;E(p,0,f,0);m=n.getRgb(f,0);const t=e-y;S=Math.min(S,(m[0]-w[0]+1)/t);k=Math.min(k,(m[1]-w[1]+1)/t);R=Math.min(R,(m[2]-w[2]+1)/t);N=Math.max(N,(m[0]-w[0]-1)/t);G=Math.max(G,(m[1]-w[1]-1)/t);M=Math.max(M,(m[2]-w[2]-1)/t);if(!(N<=S&&G<=k&&M<=R)){const e=Util.makeHexColor(F[0],F[1],F[2]);d.push([b/840,e]);S=m[0]-F[0]+1;k=m[1]-F[1]+1;R=m[2]-F[2]+1;N=m[0]-F[0]-1;G=m[1]-F[1]-1;M=m[2]-F[2]-1;y=b;w=F}b=e;F=m}const U=Util.makeHexColor(F[0],F[1],F[2]);d.push([1,U]);let x="transparent";if(e.has("Background")){m=n.getRgb(e.get("Background"),0);x=Util.makeHexColor(m[0],m[1],m[2])}if(!C){d.unshift([0,x]);d[1][0]+=BaseShading.SMALL_NUMBER}if(!h){d.at(-1)[0]-=BaseShading.SMALL_NUMBER;d.push([1,x])}this.colorStops=d}getIR(){const{coordsArr:e,shadingType:t}=this;let i,a,s,r,n;if(t===Ia){a=[e[0],e[1]];s=[e[2],e[3]];r=null;n=null;i="axial"}else if(t===ca){a=[e[0],e[1]];s=[e[3],e[4]];r=e[2];n=e[5];i="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",i,this.bbox,this.colorStops,a,s,r,n]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const i=t.numComps;this.tmpCompsBuf=new Float32Array(i);const a=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(a):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){let t=this.buffer,i=this.bufferLength;if(32===e){if(0===i)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;t=t<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const e=this.stream.getByte();this.buffer=e&(1<>i)>>>0}if(8===e&&0===i)return this.stream.getByte();for(;i>i}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const e=this.context.bitsPerCoordinate,t=this.readBits(e),i=this.readBits(e),a=this.context.decode,s=e<32?1/((1<r?r:e;t=t>n?n:t;i=ie*s[t])):i;let n,g=-2;const o=[];for(const[e,t]of a.map(((e,t)=>[e,t])).sort((([e],[t])=>e-t)))if(-1!==e)if(e===g+1){n.push(r[t]);g+=1}else{g=e;n=[r[t]];o.push(e,n)}return o}(e),i=new Dict(null);i.set("BaseFont",Name.get(e));i.set("Type",Name.get("Font"));i.set("Subtype",Name.get("CIDFontType2"));i.set("Encoding",Name.get("Identity-H"));i.set("CIDToGIDMap",Name.get("Identity"));i.set("W",t);i.set("FirstChar",t[0]);i.set("LastChar",t.at(-2)+t.at(-1).length-1);const a=new Dict(null);i.set("FontDescriptor",a);const s=new Dict(null);s.set("Ordering","Identity");s.set("Registry","Adobe");s.set("Supplement",0);i.set("CIDSystemInfo",s);return i}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(as.LBRACE);this.parseBlock();this.expect(as.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(as.NUMBER))this.operators.push(this.prev.value);else if(this.accept(as.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(as.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(as.RBRACE);if(this.accept(as.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(as.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const i=this.operators.length;this.parseBlock();this.expect(as.RBRACE);this.expect(as.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=i;this.operators[e+1]="jz"}}}}const as={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(as.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(as.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(as.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(as.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(as.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Bt;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(as.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const i=this.strBuf;i.length=0;i[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)i.push(String.fromCharCode(t));const a=i.join("");switch(a.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(a)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const i=parseFloat(t.join(""));if(isNaN(i))throw new FormatError(`Invalid floating point number: ${i}`);return i}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,i){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,i){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#F=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#S(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#k(){return!(this._imageCache.size+e)):null}class PDFFunction{static getSampleArray(e,t,i,a){let s,r,n=1;for(s=0,r=e.length;s>o)*C;c&=(1<i?e=i:e0&&(l=r[h-1]);let Q=a[1];h>1,c=s.length>>1,C=new PostScriptEvaluator(g),h=Object.create(null);let l=8192;const Q=new Float32Array(c);return function constructPostScriptFn(e,t,i,a){let s,n,g="";const E=Q;for(s=0;se&&(n=e)}d[s]=n}if(l>0){l--;h[g]=d}i.set(d,a)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let i=t.length-e,a=e-1;a>=0;a--,i++)t.push(t[i])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const i=this.stack,a=i.length-e,s=i.length-1,r=a+(t-Math.floor(t/e)*e);for(let e=a,t=s;e0?t.push(n<>g);break;case"ceiling":n=t.pop();t.push(Math.ceil(n));break;case"copy":n=t.pop();t.copy(n);break;case"cos":n=t.pop();t.push(Math.cos(n%360/180*Math.PI));break;case"cvi":n=0|t.pop();t.push(n);break;case"cvr":break;case"div":g=t.pop();n=t.pop();t.push(n/g);break;case"dup":t.copy(1);break;case"eq":g=t.pop();n=t.pop();t.push(n===g);break;case"exch":t.roll(2,1);break;case"exp":g=t.pop();n=t.pop();t.push(n**g);break;case"false":t.push(!1);break;case"floor":n=t.pop();t.push(Math.floor(n));break;case"ge":g=t.pop();n=t.pop();t.push(n>=g);break;case"gt":g=t.pop();n=t.pop();t.push(n>g);break;case"idiv":g=t.pop();n=t.pop();t.push(n/g|0);break;case"index":n=t.pop();t.index(n);break;case"le":g=t.pop();n=t.pop();t.push(n<=g);break;case"ln":n=t.pop();t.push(Math.log(n));break;case"log":n=t.pop();t.push(Math.log10(n));break;case"lt":g=t.pop();n=t.pop();t.push(n=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,i){const a=[],s=[],r=t.length>>1,n=i.length>>1;let g,o,c,C,h,l,Q,E,u=0;for(let e=0;et.min){g.unshift("Math.max(",r,", ");g.push(")")}if(n4){a=!0;t=0}else{a=!1;t=1}const o=[];for(r=0;r=0&&"ET"===gs[e];--e)gs[e]="EN";for(let e=r+1;e0&&(t=gs[r-1]);let i=h;e+1E&&isOdd(E)&&(d=E)}for(E=u;E>=d;--E){let e=-1;for(r=0,n=o.length;r=0){reverseValues(ns,e,r);e=-1}}else e<0&&(e=r);e>=0&&reverseValues(ns,e,o.length)}for(r=0,n=ns.length;r"!==e||(ns[r]="")}return createBidiText(ns.join(""),a)}const os={style:"normal",weight:"normal"},Is={style:"normal",weight:"bold"},cs={style:"italic",weight:"normal"},Cs={style:"italic",weight:"bold"},hs=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:os,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:Is,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:cs,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:Cs,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:os,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:Is,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:cs,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:Cs,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:os,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:Is,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:cs,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:Cs,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:os,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:Is,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:cs,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:Cs,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:os,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:Is,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:cs,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:Cs,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:os}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),ls=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter((e=>!t.has(e.toLowerCase()))).join(" ")}function generateFont({alias:e,local:t,path:i,fallback:a,style:s,ultimate:r},n,g,o=!0,c=!0,C=""){const h={style:null,ultimate:null};if(t){const e=C?` ${C}`:"";for(const i of t)n.push(`local(${i}${e})`)}if(e){const t=hs.get(e),r=C||function getStyleToAppend(e){switch(e){case Is:return"Bold";case cs:return"Italic";case Cs:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(s);Object.assign(h,generateFont(t,n,g,o&&!a,c&&!i,r))}s&&(h.style=s);r&&(h.ultimate=r);if(o&&a){const e=hs.get(a),{ultimate:t}=generateFont(e,n,g,o,c&&!i,C);h.ultimate||=t}c&&i&&g&&n.push(`url(${g}${i})`);return h}function getFontSubstitution(e,t,i,a,s,r){if(a.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==r&&"Type1"!==r||!/^[A-Z]{6}\+/.test(a)||(a=a.slice(7));const n=a=normalizeFontName(a);let g=e.get(n);if(g)return g;let o=hs.get(a);if(!o)for(const[e,t]of ls)if(a.startsWith(e)){a=`${t}${a.substring(e.length)}`;o=hs.get(a);break}let c=!1;if(!o){o=hs.get(s);c=!0}const C=`${t.getDocId()}_s${t.createFontId()}`;if(!o){if(!validateFontName(a)){warn(`Cannot substitute the font because of its name: ${a}`);e.set(n,null);return null}const t=/bold/gi.test(a),i=/oblique|italic/gi.test(a),s=t&&i&&Cs||t&&Is||i&&cs||os;g={css:`"${getFamilyName(a)}",${C}`,guessFallback:!0,loadedName:C,baseFontName:a,src:`local(${a})`,style:s};e.set(n,g);return g}const h=[];c&&validateFontName(a)&&h.push(`local(${a})`);const{style:l,ultimate:Q}=generateFont(o,h,i),E=null===Q,u=E?"":`,${Q}`;g={css:`"${getFamilyName(a)}",${C}${u}`,guessFallback:E,loadedName:C,baseFontName:a,src:h.join(","),style:l};e.set(n,g);return g}class ImageResizer{static#R=2048;static#y=FeatureTest.isImageDecoderSupported;constructor(e,t){this._imgData=e;this._isMask=t}static get canUseImageDecoder(){return shadow(this,"canUseImageDecoder",this.#y?ImageDecoder.isTypeSupported("image/bmp"):Promise.resolve(!1))}static needsToBeResized(e,t){if(e<=this.#R&&t<=this.#R)return!1;const{MAX_DIM:i}=this;if(e>i||t>i)return!0;const a=e*t;if(this._hasMaxArea)return a>this.MAX_AREA;if(a(this.MAX_AREA=this.#R**2)}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#R,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#y=t}static _areGoodDims(e,t){try{const i=new OffscreenCanvas(e,t),a=i.getContext("2d");a.fillRect(0,0,1,1);const s=a.getImageData(0,0,1,1).data[3];i.width=i.height=1;return 0!==s}catch{return!1}}static _guessMax(e,t,i,a){for(;e+i+1pt){const e=this.#N();if(e)return e}const a=this._encodeBMP();let s,r;if(await ImageResizer.canUseImageDecoder){s=new ImageDecoder({data:a,type:"image/bmp",preferAnimation:!1,transfer:[a.buffer]});r=s.decode().catch((e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))})).finally((()=>{s.close()}))}else r=createImageBitmap(new Blob([a.buffer],{type:"image/bmp"}));const{MAX_AREA:n,MAX_DIM:g}=ImageResizer,o=Math.max(t/g,i/g,Math.sqrt(t*i/n)),c=Math.max(o,2),C=Math.round(10*(o+1.25))/10/c,h=Math.floor(Math.log2(C)),l=new Array(h+2).fill(2);l[0]=c;l.splice(-1,1,C/(1<>n,o=a>>n;let c,C=a;try{c=new Uint8Array(r)}catch{let e=Math.floor(Math.log2(r+1));for(;;)try{c=new Uint8Array(2**e-1);break}catch{e-=1}C=Math.floor((2**e-1)/(4*i));const t=i*C*4;t>n;e>3,n=i+3&-4;if(i!==n){const e=new Uint8Array(n*t);let a=0;for(let r=0,g=t*i;r>>8;t[i++]=255&s}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();i=t.byteLength}const a=i>>2,s=i-4*a,r=new Uint32Array(t.buffer,0,a);let n=0,g=0,o=this.h1,c=this.h2;const C=3432918353,h=461845907,l=11601,Q=13715;for(let e=0;e>>17;n=n*h&Qs|n*Q&Es;o^=n;o=o<<13|o>>>19;o=5*o+3864292196}else{g=r[e];g=g*C&Qs|g*l&Es;g=g<<15|g>>>17;g=g*h&Qs|g*Q&Es;c^=g;c=c<<13|c>>>19;c=5*c+3864292196}n=0;switch(s){case 3:n^=t[4*a+2]<<16;case 2:n^=t[4*a+1]<<8;case 1:n^=t[4*a];n=n*C&Qs|n*l&Es;n=n<<15|n>>>17;n=n*h&Qs|n*Q&Es;1&a?o^=n:c^=n}this.h1=o;this.h2=c}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&Qs|36045*e&Es;t=4283543511*t&Qs|(2950163797*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;e=444984403*e&Qs|60499*e&Es;t=3301882366*t&Qs|(3120437893*(t<<16|e>>>16)&Qs)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function addState(e,t,i,a,s){let r=e;for(let e=0,i=t.length-1;e1e3){c=Math.max(c,l);Q+=h+2;l=0;h=0}C.push({transform:t,x:l,y:Q,w:i.width,h:i.height});l+=i.width+2;h=Math.max(h,i.height)}const E=Math.max(c,l)+1,u=Q+h+1,d=new Uint8Array(E*u*4),f=E<<2;for(let e=0;e=0;){t[r-4]=t[r];t[r-3]=t[r+1];t[r-2]=t[r+2];t[r-1]=t[r+3];t[r+i]=t[r+i-4];t[r+i+1]=t[r+i-3];t[r+i+2]=t[r+i-2];t[r+i+3]=t[r+i-1];r-=f}}const p={width:E,height:u};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(E,u);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(d.buffer),E,u),0,0);p.bitmap=e.transferToImageBitmap();p.data=null}else{p.kind=S;p.data=d}i.splice(r,4*o,$e);a.splice(r,4*o,[p,C]);return r+1}));addState(us,[MA,xA,Ze,UA],null,(function iterateImageMaskGroup(e,t){const i=e.fnArray,a=(t-(e.iCurr-3))%4;switch(a){case 0:return i[t]===MA;case 1:return i[t]===xA;case 2:return i[t]===Ze;case 3:return i[t]===UA}throw new Error(`iterateImageMaskGroup - invalid pos: ${a}`)}),(function foundImageMaskGroup(e,t){const i=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-3,n=s-2,g=s-1;let o=Math.floor((t-r)/4);if(o<10)return t-(t-r)%4;let c,C,h=!1;const l=a[g][0],Q=a[n][0],E=a[n][1],u=a[n][2],d=a[n][3];if(E===u){h=!0;c=n+4;let e=g+4;for(let t=1;t=4&&i[r-4]===i[n]&&i[r-3]===i[g]&&i[r-2]===i[o]&&i[r-1]===i[c]&&a[r-4][0]===C&&a[r-4][1]===h){l++;Q-=5}let E=Q+4;for(let e=1;e=i)break}a=(a||us)[e[t]];if(a&&!Array.isArray(a)){r.iCurr=t;t++;if(!a.checkFn||(0,a.checkFn)(r)){s=a;a=null}else a=null}else t++}this.state=a;this.match=s;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&E?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}set isOffscreenCanvasSupported(e){this.optimizer.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===UA||e===ee))&&this.flush()}addImageOps(e,t,i,a=!1){if(a){this.addOp(MA);this.addOp(GA,[[["SMask",!1]]])}void 0!==i&&this.addOp(Ye,["OC",i]);this.addOp(e,t);void 0!==i&&this.addOp(ve,[]);a&&this.addOp(UA)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(wA,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,i=e.length;ta&&(e=a);return e}function resizeImageMask(e,t,i,a,s,r){const n=s*r;let g;g=t<=8?new Uint8Array(n):t<=16?new Uint16Array(n):new Uint32Array(n);const o=i/s,c=a/r;let C,h,l,Q,E=0;const u=new Uint16Array(s),d=i;for(C=0;C0&&Number.isInteger(i.height)&&i.height>0&&(i.width!==l||i.height!==Q)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");l=i.width;Q=i.height}if(l<1||Q<1)throw new FormatError(`Invalid image width: ${l} or height: ${Q}`);this.width=l;this.height=Q;this.interpolate=c.get("I","Interpolate");this.imageMask=c.get("IM","ImageMask")||!1;this.matte=c.get("Matte")||!1;let E=i.bitsPerComponent;if(!E){E=c.get("BPC","BitsPerComponent");if(!E){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);E=1}}this.bpc=E;if(!this.imageMask){let s=c.getRaw("CS")||c.getRaw("ColorSpace");const r=!!s;if(r)this.jpxDecoderOptions?.smaskInData&&(s=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)s=Name.get("DeviceRGBA");else switch(i.numComps){case 1:s=Name.get("DeviceGray");break;case 3:s=Name.get("DeviceRGB");break;case 4:s=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${i.numComps} color components not supported.`)}this.colorSpace=ColorSpace.parse({cs:s,xref:e,resources:a?t:null,pdfFunctionFactory:g,localColorSpaceCache:o});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=r?this.numComp:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=c.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,E)||n&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<>3)*i,g=e.byteLength;let o,c;if(!a||s&&!(n===g))if(s){o=new Uint8Array(n);o.set(e);o.fill(255,g)}else o=new Uint8Array(e);else o=e;if(s)for(c=0;c>7&1;n[l+1]=h>>6&1;n[l+2]=h>>5&1;n[l+3]=h>>4&1;n[l+4]=h>>3&1;n[l+5]=h>>2&1;n[l+6]=h>>1&1;n[l+7]=1&h;l+=8}if(l>=1}}}}else{let i=0;h=0;for(l=0,C=r;l>a;s<0?s=0:s>c&&(s=c);n[l]=s;h&=(1<n[a+1]){t=255;break}}g[C]=t}}}if(g)for(C=0,l=3,h=t*a;C>3,C=t&&ImageResizer.needsToBeResized(i,a);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){s.kind=S;const e=s.data=await this.getImageBytes(g*n*4,{});return t?C?ImageResizer.createImage(s,!1):this.createBitmap(S,i,a,e):s}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===o?e=b:"DeviceRGB"!==this.colorSpace.name||8!==o||this.needsDecode||(e=F);if(e&&!this.smask&&!this.mask&&i===n&&a===g){const r=await this.#G(n,g);if(r)return r;const o=await this.getImageBytes(g*c,{});if(t)return C?ImageResizer.createImage({data:o,kind:e,width:i,height:a,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,n,g,o);s.kind=e;s.data=o;if(this.needsDecode){assert(e===b,"PDFImage.createImageData: The image must be grayscale.");const t=s.data;for(let e=0,i=t.length;e>3,n=await this.getImageBytes(a*r,{internal:!0}),g=this.getComponents(n);let o,c;if(1===s){c=i*a;if(this.needsDecode)for(o=0;o0&&t.args[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedh){const e="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors){warn(e);return}throw new Error(e)}let l;g.has("OC")&&(l=await this.parseMarkedContentProps(g.get("OC"),e));let Q,E;if(g.get("IM","ImageMask")||!1){const e=g.get("I","Interpolate"),i=c+7>>3,n=t.getBytes(i*C),h=g.getArray("D","Decode");if(this.parsingType3Font){Q=PDFImage.createRawMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e});Q.cached=!!s;E=[Q];a.addImageOps(Ze,E,l);if(s){const e={fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}Q=await PDFImage.createMask({imgArray:n,width:c,height:C,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported});if(Q.isSingleOpaquePixel){a.addImageOps(tt,[],l);if(s){const e={fn:tt,args:[],optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=`mask_${this.idFactory.createObjId()}`;a.addDependency(u);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;this._sendImgData(u,Q);E=[{data:u,width:Q.width,height:Q.height,interpolate:Q.interpolate,count:1}];a.addImageOps(Ze,E,l);if(s){const e={objId:u,fn:Ze,args:E,optionalContent:l};r.set(s,o,e);o&&this._regionalImageCache.set(null,o,e)}return}const u=g.has("SMask")||g.has("Mask");if(i&&c+C<200&&!u){try{const s=new PDFImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n});Q=await s.createImageData(!0,!1);a.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported;a.addImageOps(_e,[Q],l)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!this.options.ignoreErrors)throw new Error(t);warn(t)}return}let d=`img_${this.idFactory.createObjId()}`,f=!1;if(this.parsingType3Font)d=`${this.idFactory.getDocId()}_type3_${d}`;else if(s&&o){f=this.globalImageCache.shouldCache(o,this.pageIndex);if(f){assert(!i,"Cannot cache an inline image globally.");d=`${this.idFactory.getDocId()}_${d}`}}a.addDependency(d);E=[d,c,C];a.addImageOps(ze,E,l,u);if(f){if(this.globalImageCache.hasDecodeFailed(o)){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this._sendImgData(d,null,f);return}if(c*C>25e4||u){const e=await this.handler.sendWithPromise("commonobj",[d,"CopyLocalImage",{imageRef:o}]);if(e){this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0});this.globalImageCache.addByteSize(o,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n}).then((async e=>{Q=await e.createImageData(!1,this.options.isOffscreenCanvasSupported);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;Q.ref=o;f&&this.globalImageCache.addByteSize(o,Q.dataLen);return this._sendImgData(d,Q,f)})).catch((e=>{warn(`Unable to decode image "${d}": "${e}".`);o&&this.globalImageCache.addDecodeFailed(o);return this._sendImgData(d,null,f)}));if(s){const e={objId:d,fn:ze,args:E,optionalContent:l,hasMask:u};r.set(s,o,e);if(o){this._regionalImageCache.set(null,o,e);f&&this.globalImageCache.setData(o,{objId:d,fn:ze,args:E,optionalContent:l,hasMask:u,byteSize:0})}}}handleSMask(e,t,i,a,s,r){const n=e.get("G"),g={subtype:e.get("S").name,backdrop:e.get("BC")},o=e.get("TR");if(isPDFFunction(o)){const e=this._pdfFunctionFactory.create(o),t=new Uint8Array(256),i=new Float32Array(1);for(let a=0;a<256;a++){i[0]=a/255;e(i,0,i,0);t[a]=255*i[0]|0}g.transferMap=t}return this.buildFormXObject(t,n,g,i,a,s.state.clone(),r)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const i=[];let a=0,s=0;for(const e of t){const t=this.xref.fetchIfRef(e);a++;if(isName(t,"Identity")){i.push(null);continue}if(!isPDFFunction(t))return null;const r=this._pdfFunctionFactory.create(t),n=new Uint8Array(256),g=new Float32Array(1);for(let e=0;e<256;e++){g[0]=e/255;r(g,0,g,0);n[e]=255*g[0]|0}i.push(n);s++}return 1!==a&&4!==a||0===s?null:i}handleTilingType(e,t,i,a,s,r,n,g){const o=new OperatorList,c=Dict.merge({xref:this.xref,dictArray:[s.get("Resources"),i]});return this.getOperatorList({stream:a,task:n,resources:c,operatorList:o}).then((function(){const i=o.getIR(),a=getTilingPatternIR(i,s,t);r.addDependencies(o.dependencies);r.addOp(e,a);s.objId&&g.set(null,s.objId,{operatorListIR:i,dict:s})})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}}))}async handleSetFont(e,t,i,a,s,r,n=null,g=null){const o=t?.[0]instanceof Name?t[0].name:null;let c=await this.loadFont(o,i,e,n,g);if(c.font.isType3Font)try{await c.loadType3Data(this,e,s);a.addDependencies(c.type3Dependencies)}catch(e){c=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Type3 font load error: ${e}`),dict:c.font,evaluatorOptions:this.options})}r.font=c.font;c.send(this.handler);return c.loadedName}handleText(e,t){const i=t.font,a=i.charsToGlyphs(e);if(i.data){(!!(t.textRenderingMode&D)||"Pattern"===t.fillColorSpace.name||i.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(i,a,this.handler,this.options)}return a}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:i,cacheKey:a,task:s,stateManager:r,localGStateCache:n,localColorSpaceCache:g}){const o=t.objId;let c=!0;const C=[];let h=Promise.resolve();for(const a of t.getKeys()){const n=t.get(a);switch(a){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":C.push([a,n]);break;case"Font":c=!1;h=h.then((()=>this.handleSetFont(e,null,n[0],i,s,r.state).then((function(e){i.addDependency(e);C.push([a,[e,n[1]]])}))));break;case"BM":C.push([a,normalizeBlendMode(n)]);break;case"SMask":if(isName(n,"None")){C.push([a,!1]);break}if(n instanceof Dict){c=!1;h=h.then((()=>this.handleSMask(n,e,i,s,r,g)));C.push([a,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(n);C.push([a,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+a);break;default:info("Unknown graphic state operator "+a)}}await h;C.length>0&&i.addOp(GA,[C]);c&&n.set(a,o,C)}loadFont(e,t,i,a=null,s=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t,evaluatorOptions:this.options});let r;if(t)t instanceof Ref&&(r=t);else{const t=i.get("Font");t&&(r=t.getRaw(e))}if(r){if(this.type3FontRefs?.has(r))return errorFont();if(this.fontCache.has(r))return this.fontCache.get(r);try{t=this.xref.fetchIfRef(r)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=a||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:n,resolve:g}=Promise.withResolvers();let o;try{o=this.preEvaluateFont(t);o.cssFontInfo=s}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:c,hash:C}=o,h=r instanceof Ref;let l;if(C&&c instanceof Dict){const e=c.fontAliases||=Object.create(null);if(e[C]){const t=e[C].aliasRef;if(h&&t&&this.fontCache.has(t)){this.fontCache.putAlias(r,t);return this.fontCache.get(r)}}else e[C]={fontID:this.idFactory.createFontId()};h&&(e[C].aliasRef=r);l=e[C].fontID}else l=this.idFactory.createFontId();assert(l?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(h)this.fontCache.put(r,n);else{t.cacheKey=`cacheKey_${l}`;this.fontCache.put(t.cacheKey,n)}t.loadedName=`${this.idFactory.getDocId()}_${l}`;this.translateFont(o).then((e=>{g(new TranslatedFont({loadedName:t.loadedName,font:e,dict:t,evaluatorOptions:this.options}))})).catch((e=>{warn(`loadFont - translateFont failed: "${e}".`);g(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e instanceof Error?e.message:e),dict:t,evaluatorOptions:this.options}))}));return n}buildPath(e,t,i,a=!1){const s=e.length-1;i||(i=[]);if(s<0||e.fnArray[s]!==it){if(a){warn(`Encountered path operator "${t}" inside of a text object.`);e.addOp(MA,null)}let s;switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];s=[Math.min(i[0],e),Math.min(i[1],t),Math.max(i[0],e),Math.max(i[1],t)];break;case LA:case HA:s=[i[0],i[1],i[0],i[1]];break;default:s=[1/0,1/0,-1/0,-1/0]}e.addOp(it,[[t],i,s]);a&&e.addOp(UA,null)}else{const a=e.argsArray[s];a[0].push(t);a[1].push(...i);const r=a[2];switch(t){case TA:const e=i[0]+i[2],t=i[1]+i[3];r[0]=Math.min(r[0],i[0],e);r[1]=Math.min(r[1],i[1],t);r[2]=Math.max(r[2],i[0],e);r[3]=Math.max(r[3],i[1],t);break;case LA:case HA:r[0]=Math.min(r[0],i[0]);r[1]=Math.min(r[1],i[1]);r[2]=Math.max(r[2],i[0]);r[3]=Math.max(r[3],i[1])}}}parseColorSpace({cs:e,resources:t,localColorSpaceCache:i}){return ColorSpace.parseAsync({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:i}).catch((e=>{if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}))}parseShading({shading:e,resources:t,localColorSpaceCache:i,localShadingPatternCache:a}){let s,r=a.get(e);if(r)return r;try{s=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,i).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);a.set(e,null);return null}throw t}r=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(r=`${this.idFactory.getDocId()}_type3_${r}`);a.set(e,r);this.parsingType3Font?this.handler.send("commonobj",[r,"Pattern",s]):this.handler.send("obj",[r,this.pageIndex,"Pattern",s]);return r}handleColorN(e,t,i,a,s,r,n,g,o,c){const C=i.pop();if(C instanceof Name){const h=s.getRaw(C.name),l=h instanceof Ref&&o.getByRef(h);if(l)try{const s=a.base?a.base.getRgb(i,0):null,r=getTilingPatternIR(l.operatorListIR,l.dict,s);e.addOp(t,r);return}catch{}const Q=this.xref.fetchIfRef(h);if(Q){const s=Q instanceof BaseStream?Q.dict:Q,C=s.get("PatternType");if(C===fs){const g=a.base?a.base.getRgb(i,0):null;return this.handleTilingType(t,g,r,Q,s,e,n,o)}if(C===ps){const i=s.get("Shading"),a=this.parseShading({shading:i,resources:r,localColorSpaceCache:g,localShadingPatternCache:c});if(a){const i=lookupMatrix(s.getArray("Matrix"),null);e.addOp(t,["Shading",a,i])}return}throw new FormatError(`Unknown PatternType: ${C}`)}}throw new FormatError(`Unknown PatternName: ${C}`)}_parseVisibilityExpression(e,t,i){if(++t>10){warn("Visibility expression is too deeply nested");return}const a=e.length,s=this.xref.fetchIfRef(e[0]);if(!(a<2)&&s instanceof Name){switch(s.name){case"And":case"Or":case"Not":i.push(s.name);break;default:warn(`Invalid operator ${s.name} in visibility expression`);return}for(let s=1;s0)return{type:"OCMD",expression:t}}const t=i.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const i of t)e.push(i.toString());else e.push(t.objId);return{type:a,ids:e,policy:i.get("P")instanceof Name?i.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:a,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:i,operatorList:a,initialState:s=null,fallbackFontDict:r=null}){i||=Dict.empty;s||=new EvalState;if(!a)throw new Error('getOperatorList: missing "operatorList" parameter');const n=this,g=this.xref;let o=!1;const c=new LocalImageCache,C=new LocalColorSpaceCache,h=new LocalGStateCache,l=new LocalTilingPatternCache,Q=new Map,E=i.get("XObject")||Dict.empty,u=i.get("Pattern")||Dict.empty,d=new StateManager(s),f=new EvaluatorPreprocessor(e,g,d),p=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=f.savedStatesDepth;e0&&a.addOp(GA,[t]);e=null;continue}}next(new Promise((function(e,s){if(!S)throw new FormatError("GState must be referred to by name.");const r=i.get("ExtGState");if(!(r instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const g=r.get(F);if(!(g instanceof Dict))throw new FormatError("GState should be a dictionary.");n.setGState({resources:i,gState:g,operatorList:a,cacheKey:F,task:t,stateManager:d,localGStateCache:h,localColorSpaceCache:C}).then(e,s)})).catch((function(e){if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}})));return;case LA:case HA:case JA:case YA:case vA:case KA:case TA:n.buildPath(a,s,e,o);continue;case Le:case He:case Ke:case Te:continue;case Ye:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);a.addOp(Ye,["OC",null]);continue}if("OC"===e[0].name){next(n.parseMarkedContentProps(e[1],i).then((e=>{a.addOp(Ye,["OC",e])})).catch((e=>{if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);a.addOp(Ye,["OC",null])}})));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(w=0,D=e.length;w{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}}))}getTextContent({stream:e,task:t,resources:s,stateManager:r=null,includeMarkedContent:n=!1,sink:g,seenStyles:o=new Set,viewBox:c,lang:C=null,markedContentData:h=null,disableNormalization:l=!1,keepWhiteSpace:Q=!1}){s||=Dict.empty;r||=new StateManager(new TextState);n&&(h||={level:0});const E={items:[],styles:Object.create(null),lang:C},u={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},d=[" "," "];let f=0;function saveLastChar(e){const t=(f+1)%2,i=" "!==d[f]&&" "===d[t];d[f]=e;f=t;return!Q&&i}function shouldAddWhitepsace(){return!Q&&" "!==d[f]&&" "===d[(f+1)%2]}function resetLastChars(){d[0]=d[1]=" ";f=0}const p=this,m=this.xref,y=[];let w=null;const D=new LocalImageCache,b=new LocalGStateCache,F=new EvaluatorPreprocessor(e,m,r);let S;function pushWhitespace({width:e=0,height:t=0,transform:i=u.prevTransform,fontName:a=u.fontName}){E.items.push({str:" ",dir:"ltr",width:e,height:t,transform:i,fontName:a,hasEOL:!1})}function getCurrentTextTransform(){const e=S.font,t=[S.fontSize*S.textHScale,0,0,S.fontSize,0,S.textRise];if(e.isType3Font&&(S.fontSize<=1||e.isCharBBox)&&!isArrayEqual(S.fontMatrix,a)){const i=e.bbox[3]-e.bbox[1];i>0&&(t[3]*=i*S.fontMatrix[3])}return Util.transform(S.ctm,Util.transform(S.textMatrix,t))}function ensureTextContentItem(){if(u.initialized)return u;const{font:e,loadedName:t}=S;if(!o.has(t)){o.add(t);E.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(p.options.fontExtraProperties&&e.systemFontInfo){const i=E.styles[t];i.fontSubstitution=e.systemFontInfo.css;i.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}u.fontName=t;const i=u.transform=getCurrentTextTransform();if(e.vertical){u.width=u.totalWidth=Math.hypot(i[0],i[1]);u.height=u.totalHeight=0;u.vertical=!0}else{u.width=u.totalWidth=0;u.height=u.totalHeight=Math.hypot(i[2],i[3]);u.vertical=!1}const a=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),s=Math.hypot(S.ctm[0],S.ctm[1]);u.textAdvanceScale=s*a;const{fontSize:r}=S;u.trackingSpaceMin=.102*r;u.notASpace=.03*r;u.negativeSpaceMax=-.2*r;u.spaceInFlowMin=.102*r;u.spaceInFlowMax=.6*r;u.hasEOL=!1;u.initialized=!0;return u}function updateAdvanceScale(){if(!u.initialized)return;const e=Math.hypot(S.textLineMatrix[0],S.textLineMatrix[1]),t=Math.hypot(S.ctm[0],S.ctm[1])*e;if(t!==u.textAdvanceScale){if(u.vertical){u.totalHeight+=u.height*u.textAdvanceScale;u.height=0}else{u.totalWidth+=u.width*u.textAdvanceScale;u.width=0}u.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");l||(t=function normalizeUnicode(e){if(!Ct){Ct=/([\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;ht=new Map([["ſt","ſt"]])}return e.replaceAll(Ct,((e,t,i)=>t?t.normalize("NFKC"):ht.get(i)))}(t));const i=bidi(t,-1,e.vertical);return{str:i.str,dir:i.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,i){const r=await p.loadFont(e,i,s);if(r.font.isType3Font)try{await r.loadType3Data(p,s,t)}catch{}S.loadedName=r.loadedName;S.font=r.font;S.fontMatrix=r.font.fontMatrix||a}function applyInverseRotation(e,t,i){const a=Math.hypot(i[0],i[1]);return[(i[0]*e+i[1]*t)/a,(i[2]*e+i[3]*t)/a]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let i=t[4],a=t[5];if(S.font?.vertical){if(ic[2]||a+ec[3])return!1}else if(i+ec[2]||ac[3])return!1;if(!S.font||!u.prevTransform)return!0;let s=u.prevTransform[4],r=u.prevTransform[5];if(s===i&&r===a)return!0;let n=-1;t[0]&&0===t[1]&&0===t[2]?n=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(n=t[1]>0?90:270);switch(n){case 0:break;case 90:[i,a]=[a,i];[s,r]=[r,s];break;case 180:[i,a,s,r]=[-i,-a,-s,-r];break;case 270:[i,a]=[-a,-i];[s,r]=[-r,-s];break;default:[i,a]=applyInverseRotation(i,a,t);[s,r]=applyInverseRotation(s,r,u.prevTransform)}if(S.font.vertical){const e=(r-a)/u.textAdvanceScale,t=i-s,n=Math.sign(u.height);if(e.5*u.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>u.width){appendEOL();return!0}e<=n*u.notASpace&&resetLastChars();if(e<=n*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else u.height+=e;else if(!addFakeSpaces(e,u.prevTransform,n))if(0===u.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else u.height+=e;Math.abs(t)>.25*u.width&&flushTextContentItem();return!0}const g=(i-s)/u.textAdvanceScale,o=a-r,C=Math.sign(u.width);if(g.5*u.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(o)>u.height){appendEOL();return!0}g<=C*u.notASpace&&resetLastChars();if(g<=C*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(g)})}else u.width+=g;else if(!addFakeSpaces(g,u.prevTransform,C))if(0===u.str.length){resetLastChars();pushWhitespace({width:Math.abs(g)})}else u.width+=g;Math.abs(o)>.25*u.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const i=S.font;if(!e){const e=S.charSpacing+t;e&&(i.vertical?S.translateTextMatrix(0,-e):S.translateTextMatrix(e*S.textHScale,0));Q&&compareWithLastPosition(0);return}const a=i.charsToGlyphs(e),s=S.fontMatrix[0]*S.fontSize;for(let e=0,r=a.length;e0){const e=y.join("");y.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case he:if(!r.state.font){p.ensureStateFont(r.state);continue}buildTextContentItem({chars:N[0],extraSpacing:0});break;case Be:if(!r.state.font){p.ensureStateFont(r.state);continue}S.carriageReturn();buildTextContentItem({chars:N[0],extraSpacing:0});break;case Qe:if(!r.state.font){p.ensureStateFont(r.state);continue}S.wordSpacing=N[0];S.charSpacing=N[1];S.carriageReturn();buildTextContentItem({chars:N[2],extraSpacing:0});break;case xe:flushTextContentItem();w??=s.get("XObject")||Dict.empty;R=N[0]instanceof Name;f=N[0].name;if(R&&D.getByName(f))break;next(new Promise((function(e,i){if(!R)throw new FormatError("XObject must be referred to by name.");let a=w.getRaw(f);if(a instanceof Ref){if(D.getByRef(a)){e();return}if(p.globalImageCache.getData(a,p.pageIndex)){e();return}a=m.fetch(a)}if(!(a instanceof BaseStream))throw new FormatError("XObject should be a stream");const E=a.dict.get("Subtype");if(!(E instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==E.name){D.set(f,a.dict.objId,!0);e();return}const u=r.state.clone(),d=new StateManager(u),y=lookupMatrix(a.dict.getArray("Matrix"),null);y&&d.transform(y);enqueueChunk();const b={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;g.enqueue(e,t)},get desiredSize(){return g.desiredSize},get ready(){return g.ready}};p.getTextContent({stream:a,task:t,resources:a.dict.get("Resources")||s,stateManager:d,includeMarkedContent:n,sink:b,seenStyles:o,viewBox:c,lang:C,markedContentData:h,disableNormalization:l,keepWhiteSpace:Q}).then((function(){b.enqueueInvoked||D.set(f,a.dict.objId,!0);e()}),i)})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}})));return;case GA:R=N[0]instanceof Name;f=N[0].name;if(R&&b.getByName(f))break;next(new Promise((function(e,t){if(!R)throw new FormatError("GState must be referred to by name.");const i=s.get("ExtGState");if(!(i instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const a=i.get(f);if(!(a instanceof Dict))throw new FormatError("GState should be a dictionary.");const r=a.get("Font");if(r){flushTextContentItem();S.fontName=null;S.fontSize=r[1];handleSetFont(null,r[0]).then(e,t)}else{b.set(f,a.objId,!0);e()}})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}})));return;case Je:flushTextContentItem();if(n){h.level++;E.items.push({type:"beginMarkedContent",tag:N[0]instanceof Name?N[0].name:null})}break;case Ye:flushTextContentItem();if(n){h.level++;let e=null;N[1]instanceof Dict&&(e=N[1].get("MCID"));E.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${p.idFactory.getPageObjId()}_mc${e}`:null,tag:N[0]instanceof Name?N[0].name:null})}break;case ve:flushTextContentItem();if(n){if(0===h.level)break;h.level--;E.items.push({type:"endMarkedContent"})}break;case UA:!e||e.font===S.font&&e.fontSize===S.fontSize&&e.fontName===S.fontName||flushTextContentItem()}if(E.items.length>=g.desiredSize){d=!0;break}}if(d)next(ms);else{flushTextContentItem();enqueueChunk();e()}})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${t.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}}))}async extractDataStructures(e,t){const i=this.xref;let a;const s=this.readToUnicode(t.toUnicode);if(t.composite){const i=e.get("CIDSystemInfo");i instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(i.get("Registry")),ordering:stringToPDFString(i.get("Ordering")),supplement:i.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(a=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const r=[];let n,g=null;if(e.has("Encoding")){n=e.get("Encoding");if(n instanceof Dict){g=n.get("BaseEncoding");g=g instanceof Name?g.name:null;if(n.has("Differences")){const e=n.get("Differences");let t=0;for(const a of e){const e=i.fetchIfRef(a);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);r[t++]=e.name}}}}else if(n instanceof Name)g=n.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==g&&"MacExpertEncoding"!==g&&"WinAnsiEncoding"!==g&&(g=null)}const o=!t.file||t.isInternalFont,c=qi()[t.name];g&&o&&c&&(g=null);if(g)t.defaultEncoding=getEncoding(g);else{const e=!!(t.flags&Mi),i=!!(t.flags&xi);n=hi;"TrueType"!==t.type||i||(n=li);if(e||c){n=Ci;o&&(/Symbol/i.test(t.name)?n=Bi:/Dingbats/i.test(t.name)?n=Qi:/Wingdings/i.test(t.name)&&(n=li))}t.defaultEncoding=n}t.differences=r;t.baseEncodingName=g;t.hasEncoding=!!g||r.length>0;t.dict=e;t.toUnicode=await s;const C=await this.buildToUnicode(t);t.toUnicode=C;a&&(t.cidToGidMap=this.readCidToGidMap(a,C));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const i=[],a=e.defaultEncoding.slice(),s=e.baseEncodingName,r=e.differences;for(const e in r){const t=r[e];".notdef"!==t&&(a[e]=t)}const n=wi();for(const r in a){let g=a[r];if(""===g)continue;let o=n[g];if(void 0!==o){i[r]=String.fromCharCode(o);continue}let c=0;switch(g[0]){case"G":3===g.length&&(c=parseInt(g.substring(1),16));break;case"g":5===g.length&&(c=parseInt(g.substring(1),16));break;case"C":case"c":if(g.length>=3&&g.length<=4){const i=g.substring(1);if(t){c=parseInt(i,16);break}c=+i;if(Number.isNaN(c)&&Number.isInteger(parseInt(i,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":o=getUnicodeForGlyph(g,n);-1!==o&&(c=o);break;default:switch(g){case"f_h":case"f_t":case"T_h":i[r]=g.replaceAll("_","");continue}}if(c>0&&c<=1114111&&Number.isInteger(c)){if(s&&c===+r){const e=getEncoding(s);if(e&&(g=e[r])){i[r]=String.fromCharCode(n[g]);continue}}i[r]=String.fromCodePoint(c)}}return i}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:i}=e.cidSystemInfo,a=Name.get(`${t}-${i}-UCS2`),s=await CMapFactory.create({encoding:a,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),r=[],n=[];e.cMap.forEach((function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const i=s.lookup(t);if(i){n.length=0;for(let e=0,t=i.length;e>1;(0!==s||t.has(r))&&(i[r]=s)}return i}extractWidths(e,t,i){const a=this.xref;let s=[],r=0;const n=[];let g;if(i.composite){const t=e.get("DW");r="number"==typeof t?Math.ceil(t):1e3;const o=e.get("W");if(Array.isArray(o))for(let e=0,t=o.length;e{const t=o.get(e),s=new OperatorList;return a.getOperatorList({stream:t,task:i,resources:c,operatorList:s}).then((()=>{s.fnArray[0]===ue&&this._removeType3ColorOperators(s,E);C[e]=s.getIR();for(const e of s.dependencies)n.add(e)})).catch((function(t){warn(`Type3 font resource "${e}" is not available.`);const i=new OperatorList;C[e]=i.getIR()}))}));this.type3Loaded=g.then((()=>{r.charProcOperatorList=C;if(this._bbox){r.isCharBBox=!0;r.bbox=this._bbox}}));return this.type3Loaded}_removeType3ColorOperators(e,t=NaN){const i=Util.normalizeRect(e.argsArray[0].slice(2)),a=i[2]-i[0],s=i[3]-i[1],r=Math.hypot(a,s);if(0===a||0===s){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(r/t)>=10){this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]);this._bbox[0]=Math.min(this._bbox[0],i[0]);this._bbox[1]=Math.min(this._bbox[1],i[1]);this._bbox[2]=Math.max(this._bbox[2],i[2]);this._bbox[3]=Math.max(this._bbox[3],i[3])}let n=0,g=e.length;for(;n=LA&&r<=zA;if(s.variableArgs)g>n&&info(`Command ${a}: expected [0, ${n}] args, but received ${g} args.`);else{if(g!==n){const e=this.nonProcessedArgs;for(;g>n;){e.push(t.shift());g--}for(;gEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(r,t);e.fn=r;e.args=t;return!0}if(i===Bt)return!1;if(null!==i){null===t&&(t=[]);t.push(i);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case MA:this.stateManager.save();break;case UA:this.stateManager.restore();break;case xA:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:i,args:a}=e;switch(0|i){case re:const[e,i]=a;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i);break;case Se:ColorSpace.singletons.rgb.getRgbItem(a,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(a,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(a,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,i){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=i;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpace.singletons.gray},i=!1;const a=[];try{for(;;){e.args.length=0;if(i||!this.read(e))break;const{fn:s,args:r}=e;switch(0|s){case MA:a.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case UA:t=a.pop()||t;break;case ce:t.scaleFactor*=Math.hypot(r[0],r[1]);break;case re:const[e,s]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof s&&s>0&&(t.fontSize=s*t.scaleFactor);break;case fe:t.fillColorSpace=ColorSpace.parse({cs:r[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case ye:t.fillColorSpace.getRgbItem(r,0,t.fontColor,0);break;case Se:ColorSpace.singletons.rgb.getRgbItem(r,0,t.fontColor,0);break;case be:ColorSpace.singletons.gray.getRgbItem(r,0,t.fontColor,0);break;case Re:ColorSpace.singletons.cmyk.getRgbItem(r,0,t.fontColor,0);break;case he:case le:case Be:case Qe:i=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,(e=>numberToString(e/255))).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const i=new OffscreenCanvas(1,1);this.ctxMeasure=i.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.set("Type",Name.get("FontDescriptor"));e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.set("FontStretch",Name.get("Normal"));e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("CIDFontType0"));e.set("CIDToGIDMap",Name.get("Identity"));e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],i=[...this.widths.entries()].sort();let a=null,s=null;for(const[e,r]of i)if(a)if(e===a+s.length)s.push(r);else{t.push(a,s);a=e;s=[r]}else{a=e;s=[r]}a&&t.push(a,s);e.set("W",t);const r=new Dict(this.xref);r.set("Ordering","Identity");r.set("Registry","Adobe");r.set("Supplement",0);e.set("CIDSystemInfo",r);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type0"));e.set("Encoding",Name.get("Identity-H"));e.set("DescendantFonts",[this.descendantFontRef]);e.set("ToUnicode",Name.get("Identity-H"));return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const i of e.split(/\r\n?|\n/))for(const e of i.split("")){const i=e.charCodeAt(0);if(this.widths.has(i))continue;const a=t.measureText(e),s=Math.ceil(a.width);this.widths.set(i,s);this.firstChar=Math.min(i,this.firstChar);this.lastChar=Math.max(i,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,i){const[a,n,g,o]=e;let c=g-a,C=o-n;t%180!=0&&([c,C]=[C,c]);const h=s*i;return{coords:[0,C+r*i-h],bbox:[0,0,c,C],matrix:0!==t?getRotationMatrix(t,C,h):void 0}}createAppearance(e,t,i,a,n,g){const o=this._createContext(),c=[];let C=-1/0;for(const t of e.split(/\r\n?|\n/)){c.push(t);const e=o.measureText(t).width;C=Math.max(C,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let i=this.widths.get(e);if(void 0===i){const a=o.measureText(t);i=Math.ceil(a.width);this.widths.set(e,i);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}C*=a/1e3;const[h,l,Q,E]=t;let u=Q-h,d=E-l;i%180!=0&&([u,d]=[d,u]);let f=1;C>u&&(f=u/C);let p=1;const m=s*a,y=r*a,w=m*c.length;w>d&&(p=d/w);const D=a*Math.min(f,p),b=["q",`0 0 ${numberToString(u)} ${numberToString(d)} re W n`,"BT",`1 0 0 1 0 ${numberToString(d+y)} Tm 0 Tc ${getPdfColor(n,!0)}`,`/${this.fontName.name} ${numberToString(D)} Tf`],{resources:F}=this;if(1!==(g="number"==typeof g&&g>=0&&g<=1?g:1)){b.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",g);t.set("CA",g);t.set("Type",Name.get("ExtGState"));e.set("R0",t);F.set("ExtGState",e)}const S=numberToString(m);for(const e of c)b.push(`0 -${S} Td <${stringToUTF16HexString(e)}> Tj`);b.push("ET","Q");const k=b.join("\n"),R=new Dict(this.xref);R.set("Subtype",Name.get("Form"));R.set("Type",Name.get("XObject"));R.set("BBox",[0,0,u,d]);R.set("Length",k.length);R.set("Resources",F);if(i){const e=getRotationMatrix(i,u,d);R.set("Matrix",e)}const N=new StringStream(k);N.dict=R;return N}}class NameOrNumberTree{constructor(e,t,i){this.root=e;this.xref=t;this._type=i}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,i=new RefSet;i.put(this.root);const a=[this.root];for(;a.length>0;){const s=t.fetchIfRef(a.shift());if(!(s instanceof Dict))continue;if(s.has("Kids")){const e=s.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(i.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);a.push(t);i.put(t)}continue}const r=s.get(this._type);if(Array.isArray(r))for(let i=0,a=r.length;i10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const s=i.get("Kids");if(!Array.isArray(s))return null;let r=0,n=s.length-1;for(;r<=n;){const a=r+n>>1,g=t.fetchIfRef(s[a]),o=g.get("Limits");if(et.fetchIfRef(o[1]))){i=g;break}r=a+1}}if(r>n)return null}const s=i.get(this._type);if(Array.isArray(s)){let i=0,a=s.length-2;for(;i<=a;){const r=i+a>>1,n=r+(1&r),g=t.fetchIfRef(s[n]);if(eg))return s[n+1];i=n+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){Qa=Object.create(null)}();!function clearPrimitiveCaches(){Qt=Object.create(null);Et=Object.create(null);ut=Object.create(null)}();!function clearUnicodeCaches(){ki.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){return e instanceof Dict?e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null:null}class FileSpec{#U=!1;constructor(e,t,i=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");i||(e.has("EF")?this.#U=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){let e="";const t=pickPlatformItem(this.root);t&&"string"==typeof t&&(e=stringToPDFString(t).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"));return shadow(this,"filename",e||"unnamed")}get content(){if(!this.#U)return null;this._contentRef||=pickPlatformItem(this.root?.get("EF"));let e=null;if(this._contentRef){const t=this.xref.fetchIfRef(this._contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have any content");return e}get description(){let e="";const t=this.root?.get("Desc");t&&"string"==typeof t&&(e=stringToPDFString(t));return shadow(this,"description",e)}get serializable(){return{rawFilename:this.filename,filename:(e=this.filename,e.substring(e.lastIndexOf("/")+1)),content:this.content,description:this.description};var e}}const ys=0,ws=-2,Ds=-3,bs=-4,Fs=-5,Ss=-6,ks=-9;function isWhitespace(e,t){const i=e[t];return" "===i||"\n"===i||"\r"===i||"\t"===i}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,((e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)}))}_parseContent(e,t){const i=[];let a=t;function skipWs(){for(;a"!==e[a]&&"/"!==e[a];)++a;const s=e.substring(t,a);skipWs();for(;a"!==e[a]&&"/"!==e[a]&&"?"!==e[a];){skipWs();let t="",s="";for(;a"!==e[i]&&"?"!==e[i]&&"/"!==e[i];)++i;const a=e.substring(t,i);!function skipWs(){for(;i"!==e[i+1]);)++i;return{name:a,value:e.substring(s,i),parsed:i-t}}parseXml(e){let t=0;for(;t",i);if(t<0){this.onError(ks);return}this.onEndElement(e.substring(i,t));i=t+1;break;case"?":++i;const a=this._parseProcessingInstruction(e,i);if("?>"!==e.substring(i+a.parsed,i+a.parsed+2)){this.onError(Ds);return}this.onPi(a.name,a.value);i+=a.parsed+2;break;case"!":if("--"===e.substring(i+1,i+3)){t=e.indexOf("--\x3e",i+3);if(t<0){this.onError(Fs);return}this.onComment(e.substring(i+3,t));i=t+3}else if("[CDATA["===e.substring(i+1,i+8)){t=e.indexOf("]]>",i+8);if(t<0){this.onError(ws);return}this.onCdata(e.substring(i+8,t));i=t+3}else{if("DOCTYPE"!==e.substring(i+1,i+8)){this.onError(Ss);return}{const a=e.indexOf("[",i+8);let s=!1;t=e.indexOf(">",i+8);if(t<0){this.onError(bs);return}if(a>0&&t>a){t=e.indexOf("]>",i+8);if(t<0){this.onError(bs);return}s=!0}const r=e.substring(i+8,t+(s?1:0));this.onDoctype(r);i=t+(s?2:1)}}break;default:const s=this._parseContent(e,i);if(null===s){this.onError(Ss);return}let r=!1;if("/>"===e.substring(i+s.parsed,i+s.parsed+2))r=!0;else if(">"!==e.substring(i+s.parsed,i+s.parsed+1)){this.onError(ks);return}this.onBeginElement(s.name,s.attributes,r);i+=s.parsed+(r?2:1)}}else{for(;i0}searchNode(e,t){if(t>=e.length)return this;const i=e[t];if(i.name.startsWith("#")&&t0){a.push([s,0]);s=s.childNodes[0]}else{if(0===a.length)return null;for(;0!==a.length;){const[e,t]=a.pop(),i=t+1;if(i");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=ys;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=ys;this.parseXml(e);if(this._errorCode!==ys)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,i=e.length;t\\376\\377([^<]+)/g,(function(e,t){const i=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(e,t,i,a){return String.fromCharCode(64*t+8*i+1*a)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)})),a=[">"];for(let e=0,t=i.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?a.push(String.fromCharCode(t)):a.push("&#x"+(65536+t).toString(16).substring(1)+";")}return a.join("")}))}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter((e=>"rdf:li"===e.nodeName))}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,i=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,i.map((e=>e.textContent.trim())))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Rs=1,Ns=2,Gs=3,Ms=4,Us=5;class StructTreeRoot{constructor(e,t){this.dict=e;this.ref=t instanceof Ref?t:null;this.roleMap=new Map;this.structParentIds=null}init(){this.readRoleMap()}#x(e,t,i){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let a=this.structParentIds.get(e);if(!a){a=[];this.structParentIds.put(e,a)}a.push([t,i])}addAnnotationIdToPage(e,t){this.#x(e,t,Ms)}readRoleMap(){const e=this.dict.get("RoleMap");if(e instanceof Dict)for(const[t,i]of e)i instanceof Name&&this.roleMap.set(t,i.name)}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:i}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let a=0,s=!0;for(const[e,r]of i){const{ref:i}=await t.getPage(e);if(!(i instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);s=!0;break}for(const e of r)if(e.accessibilityData?.type){e.parentTreeId=a++;s=!1}}if(s){for(const e of i.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:i,pdfManager:a,changes:s}){const r=a.catalog.cloneDict(),n=new RefSetCache;n.put(i,r);const g=t.getNewTemporaryRef();r.set("StructTreeRoot",g);const o=new Dict(t);o.set("Type",Name.get("StructTreeRoot"));const c=t.getNewTemporaryRef();o.set("ParentTree",c);const C=[];o.set("K",C);n.put(g,o);const h=new Dict(t),l=[];h.set("Nums",l);const Q=await this.#L({newAnnotationsByPage:e,structTreeRootRef:g,structTreeRoot:null,kids:C,nums:l,xref:t,pdfManager:a,changes:s,cache:n});o.set("ParentTreeNextKey",Q);n.put(c,h);for(const[e,t]of n.items())s.put(e,{data:t})}async canUpdateStructTree({pdfManager:e,xref:t,newAnnotationsByPage:i}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let a=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(a)||a<0){warn("Cannot update the struct tree: invalid next key.");return!1}const s=this.dict.get("ParentTree");if(!(s instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const r=s.get("Nums");if(!Array.isArray(r)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const n=new NumberTree(s,t);for(const t of i.keys()){const{pageDict:i}=await e.getPage(t);if(!i.has("StructParents"))continue;const a=i.get("StructParents");if(!Number.isInteger(a)||!Array.isArray(n.get(a))){warn(`Cannot save the struct tree: page ${t} has a wrong id.`);return!1}}let g=!0;for(const[t,s]of i){const{pageDict:i}=await e.getPage(t);StructTreeRoot.#H({elements:s,xref:this.dict.xref,pageDict:i,numberTree:n});for(const e of s)if(e.accessibilityData?.type){e.accessibilityData.structParent>=0||(e.parentTreeId=a++);g=!1}}if(g){for(const e of i.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:i}){const a=this.dict.xref,s=this.dict.clone(),r=this.ref,n=new RefSetCache;n.put(r,s);let g,o=s.getRaw("ParentTree");if(o instanceof Ref)g=a.fetch(o);else{g=o;o=a.getNewTemporaryRef();s.set("ParentTree",o)}g=g.clone();n.put(o,g);let c=g.getRaw("Nums"),C=null;if(c instanceof Ref){C=c;c=a.fetch(C)}c=c.slice();C||g.set("Nums",c);const h=await StructTreeRoot.#L({newAnnotationsByPage:e,structTreeRootRef:r,structTreeRoot:this,kids:null,nums:c,xref:a,pdfManager:t,changes:i,cache:n});if(-1!==h){s.set("ParentTreeNextKey",h);C&&n.put(C,c);for(const[e,t]of n.items())i.put(e,{data:t})}}static async#L({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:i,kids:a,nums:s,xref:r,pdfManager:n,changes:g,cache:o}){const c=Name.get("OBJR");let C,h=-1;for(const[l,Q]of e){const e=await n.getPage(l),{ref:E}=e,u=E instanceof Ref;for(const{accessibilityData:n,ref:d,parentTreeId:f,structTreeParent:p}of Q){if(!n?.type)continue;const{structParent:Q}=n;if(i&&Number.isInteger(Q)&&Q>=0){let t=(C||=new Map).get(l);if(void 0===t){t=new StructTreePage(i,e.pageDict).collectObjects(E);C.set(l,t)}const a=t?.get(Q);if(a){const e=r.fetch(a).clone();StructTreeRoot.#J(e,n);g.put(a,{data:e});continue}}h=Math.max(h,f);const m=r.getNewTemporaryRef(),y=new Dict(r);StructTreeRoot.#J(y,n);await this.#Y({structTreeParent:p,tagDict:y,newTagRef:m,structTreeRootRef:t,fallbackKids:a,xref:r,cache:o});const w=new Dict(r);y.set("K",w);w.set("Type",c);u&&w.set("Pg",E);w.set("Obj",d);o.put(m,y);s.push(f,m)}}return h+1}static#J(e,{type:t,title:i,lang:a,alt:s,expanded:r,actualText:n}){e.set("S",Name.get(t));i&&e.set("T",stringToAsciiOrUTF16BE(i));a&&e.set("Lang",stringToAsciiOrUTF16BE(a));s&&e.set("Alt",stringToAsciiOrUTF16BE(s));r&&e.set("E",stringToAsciiOrUTF16BE(r));n&&e.set("ActualText",stringToAsciiOrUTF16BE(n))}static#H({elements:e,xref:t,pageDict:i,numberTree:a}){const s=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);let i=s.get(e);if(!i){i=[];s.set(e,i)}i.push(t)}const r=i.get("StructParents");if(!Number.isInteger(r))return;const n=a.get(r),updateElement=(e,i,a)=>{const r=s.get(e);if(r){const e=i.getRaw("P"),s=t.fetchIfRef(e);if(e instanceof Ref&&s instanceof Dict){const e={ref:a,dict:i};for(const t of r)t.structTreeParent=e}return!0}return!1};for(const e of n){if(!(e instanceof Ref))continue;const i=t.fetch(e),a=i.get("K");if(Number.isInteger(a))updateElement(a,i,e);else if(Array.isArray(a))for(let s of a){s=t.fetchIfRef(s);if(Number.isInteger(s)&&updateElement(s,i,e))break;if(!(s instanceof Dict))continue;if(!isName(s.get("Type"),"MCR"))break;const a=s.get("MCID");if(Number.isInteger(a)&&updateElement(a,i,e))break}}}static async#Y({structTreeParent:e,tagDict:t,newTagRef:i,structTreeRootRef:a,fallbackKids:s,xref:r,cache:n}){let g,o=null;if(e){({ref:o}=e);g=e.dict.getRaw("P")||a}else g=a;t.set("P",g);const c=r.fetchIfRef(g);if(!c){s.push(i);return}let C=n.get(g);if(!C){C=c.clone();n.put(g,C)}const h=C.getRaw("K");let l=h instanceof Ref?n.get(h):null;if(!l){l=r.fetchIfRef(h);l=Array.isArray(l)?l.slice():[h];const e=r.getNewTemporaryRef();C.set("K",e);n.put(e,l)}const Q=l.indexOf(o);l.splice(Q>=0?Q+1:l.length,0,i)}}class StructElementNode{constructor(e,t){this.tree=e;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:i}=this.tree;return i.roleMap.has(t)?i.roleMap.get(t):t}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const i=this.dict.get("K");if(Array.isArray(i))for(const t of i){const i=this.parseKid(e,t);i&&this.kids.push(i)}else{const t=this.parseKid(e,i);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Rs,mcid:t,pageObjId:e});let i=null;t instanceof Ref?i=this.dict.xref.fetch(t):t instanceof Dict&&(i=t);if(!i)return null;const a=i.getRaw("Pg");a instanceof Ref&&(e=a.toString());const s=i.get("Type")instanceof Name?i.get("Type").name:null;if("MCR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Stm");return new StructElement({type:Ns,refObjId:t instanceof Ref?t.toString():null,pageObjId:e,mcid:i.get("MCID")})}if("OBJR"===s){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Obj");return new StructElement({type:Gs,refObjId:t instanceof Ref?t.toString():null,pageObjId:e})}return new StructElement({type:Us,dict:i})}}class StructElement{constructor({type:e,dict:t=null,mcid:i=null,pageObjId:a=null,refObjId:s=null}){this.type=e;this.dict=t;this.mcid=i;this.pageObjId=a;this.refObjId=s;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.rootDict=e?e.dict:null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const i=this.root.structParentIds?.get(e);if(!i)return null;const a=new Map,s=new NumberTree(t,this.rootDict.xref);for(const[e]of i){const t=s.getRaw(e);t instanceof Ref&&a.set(e,t)}return a}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const t=this.rootDict.get("ParentTree");if(!t)return;const i=this.pageDict.get("StructParents"),a=this.root.structParentIds?.get(e);if(!Number.isInteger(i)&&!a)return;const s=new Map,r=new NumberTree(t,this.rootDict.xref);if(Number.isInteger(i)){const e=r.get(i);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.rootDict.xref.fetch(t),s)}if(a)for(const[e,t]of a){const i=r.get(e);if(i){const e=this.addNode(this.rootDict.xref.fetchIfRef(i),s);1===e?.kids?.length&&e.kids[0].type===Gs&&(e.kids[0].type=t)}}}addNode(e,t,i=0){if(i>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const a=new StructElementNode(this,e);t.set(e,a);const s=e.get("P");if(!s||isName(s.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,a)||t.delete(e);return a}const r=this.addNode(s,t,i+1);if(!r)return a;let n=!1;for(const t of r.kids)if(t.type===Us&&t.dict===e){t.parentNode=a;n=!0}n||t.delete(e);return a}addTopLevelNode(e,t){const i=this.rootDict.get("K");if(!i)return!1;if(i instanceof Dict){if(i.objId!==e.objId)return!1;this.nodes[0]=t;return!0}if(!Array.isArray(i))return!0;let a=!1;for(let s=0;s40){warn("StructTree too deep to be fully serialized.");return}const a=Object.create(null);a.role=e.role;a.children=[];t.children.push(a);let s=e.dict.get("Alt");"string"!=typeof s&&(s=e.dict.get("ActualText"));"string"==typeof s&&(a.alt=stringToPDFString(s));const r=e.dict.get("A");if(r instanceof Dict){const e=lookupNormalRect(r.getArray("BBox"),null);if(e)a.bbox=e;else{const e=r.get("Width"),t=r.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(a.bbox=[0,0,e,t])}}const n=e.dict.get("Lang");"string"==typeof n&&(a.lang=stringToPDFString(n));for(const t of e.kids){const e=t.type===Us?t.parentNode:null;e?nodeToSerializable(e,a,i+1):t.type===Rs||t.type===Ns?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Gs?a.children.push({type:"object",id:t.refObjId}):t.type===Ms&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}function isValidExplicitDest(e){if(!Array.isArray(e)||e.length<2)return!1;const[t,i,...a]=e;if(!(t instanceof Ref||Number.isInteger(t)))return!1;if(!(i instanceof Name))return!1;const s=a.length;let r=!0;switch(i.name){case"XYZ":if(s<2||s>3)return!1;break;case"Fit":case"FitB":return 0===s;case"FitH":case"FitBH":case"FitV":case"FitBV":if(s>1)return!1;break;case"FitR":if(4!==s)return!1;r=!1;break;default:return!1}for(const e of a)if(!("number"==typeof e||r&&null===e))return!1;return!0}function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return isValidExplicitDest(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t);if(isValidExplicitDest(t))return JSON.stringify(t)}return null}class Catalog{constructor(e,t){this.pdfManager=e;this.xref=t;this._catDict=t.getCatalogObj();if(!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict;this._actualNumPages=null;this.fontCache=new RefSetCache;this.builtInCMapCache=new Map;this.standardFontDataCache=new Map;this.globalImageCache=new GlobalImageCache;this.pageKidsCountCache=new RefSetCache;this.pageIndexCache=new RefSetCache;this.pageDictCache=new RefSetCache;this.nonBlendModesSet=new RefSet;this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const e=this._catDict.get("Version");if(e instanceof Name){if(ft.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this._catDict.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this._catDict.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this._catDict.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this._catDict.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this._catDict.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const i=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(i instanceof BaseStream&&i.dict instanceof Dict){const e=i.dict.get("Type"),a=i.dict.get("Subtype");if(isName(e,"Metadata")&&isName(a,"XML")){const e=stringToUTF8String(i.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this._readMarkInfo()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}_readMarkInfo(){const e=this._catDict.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const i in t){const a=e.get(i);"boolean"==typeof a&&(t[i]=a)}return t}get structTreeRoot(){let e=null;try{e=this._readStructTreeRoot()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}_readStructTreeRoot(){const e=this._catDict.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const i=new StructTreeRoot(t,e);i.init();return i}get toplevelPagesDict(){const e=this._catDict.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this._readDocumentOutline()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}_readDocumentOutline(){let e=this._catDict.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},i=[{obj:e,parent:t}],a=new RefSet;a.put(e);const s=this.xref,r=new Uint8ClampedArray(3);for(;i.length>0;){const t=i.shift(),n=s.fetchIfRef(t.obj);if(null===n)continue;n.has("Title")||warn("Invalid outline item encountered.");const g={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:n,resultObj:g,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const o=n.get("Title"),c=n.get("F")||0,C=n.getArray("C"),h=n.get("Count");let l=r;!isNumberArray(C,3)||0===C[0]&&0===C[1]&&0===C[2]||(l=ColorSpace.singletons.rgb.getRgb(C,0));const Q={action:g.action,attachment:g.attachment,dest:g.dest,url:g.url,unsafeUrl:g.unsafeUrl,newWindow:g.newWindow,setOCGState:g.setOCGState,title:"string"==typeof o?stringToPDFString(o):"",color:l,count:Number.isInteger(h)?h:void 0,bold:!!(2&c),italic:!!(1&c),items:[]};t.parent.items.push(Q);e=n.getRaw("First");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:Q});a.put(e)}e=n.getRaw("Next");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:t.parent});a.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this._readPermissions()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}_readPermissions(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const i=[];for(const e in y){const a=y[e];t&a&&i.push(a)}return i}get optionalContentConfig(){let e=null;try{const t=this._catDict.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const i=t.get("D");if(!i)return shadow(this,"optionalContentConfig",null);const a=t.get("OCGs");if(!Array.isArray(a))return shadow(this,"optionalContentConfig",null);const s=new RefSetCache;for(const e of a)e instanceof Ref&&!s.has(e)&&s.put(e,this.#v(e));e=this.#K(i,s)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#v(e){const t=this.xref.fetch(e),i={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},a=t.get("Name");"string"==typeof a&&(i.name=stringToPDFString(a));let s=t.getArray("Intent");Array.isArray(s)||(s=[s]);s.every((e=>e instanceof Name))&&(i.intent=s.map((e=>e.name)));const r=t.get("Usage");if(!(r instanceof Dict))return i;const n=i.usage,g=r.get("Print");if(g instanceof Dict){const e=g.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.print={printState:e.name}}}const o=r.get("View");if(o instanceof Dict){const e=o.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.view={viewState:e.name}}}return i}#K(e,t){function parseOnOff(e){const i=[];if(Array.isArray(e))for(const a of e)a instanceof Ref&&t.has(a)&&i.push(a.toString());return i}function parseOrder(e,i=0){if(!Array.isArray(e))return null;const s=[];for(const r of e){if(r instanceof Ref&&t.has(r)){a.put(r);s.push(r.toString());continue}const e=parseNestedOrder(r,i);e&&s.push(e)}if(i>0)return s;const r=[];for(const[e]of t.items())a.has(e)||r.push(e.toString());r.length&&s.push({name:null,order:r});return s}function parseNestedOrder(e,t){if(++t>s){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const a=i.fetchIfRef(e);if(!Array.isArray(a))return null;const r=i.fetchIfRef(a[0]);if("string"!=typeof r)return null;const n=parseOrder(a.slice(1),t);return n?.length?{name:stringToPDFString(r),order:n}:null}const i=this.xref,a=new RefSet,s=10;!function parseRBGroups(e){if(Array.isArray(e))for(const a of e){const e=i.fetchIfRef(a);if(!Array.isArray(e)||!e.length)continue;const s=new Set;for(const i of e)if(i instanceof Ref&&t.has(i)&&!s.has(i.toString())){s.add(i.toString());t.get(i).rbGroups.push(s)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this._actualNumPages=e}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const e=this._readDests(),t=Object.create(null);if(e instanceof NameTree)for(const[i,a]of e.getAll()){const e=fetchDest(a);e&&(t[stringToPDFString(i)]=e)}else if(e instanceof Dict)for(const[i,a]of e){const e=fetchDest(a);e&&(t[i]=e)}return shadow(this,"destinations",t)}getDestination(e){const t=this._readDests();if(t instanceof NameTree){const i=fetchDest(t.get(e));if(i)return i;const a=this.destinations[e];if(a){warn(`Found "${e}" at an incorrect position in the NameTree.`);return a}}else if(t instanceof Dict){const i=fetchDest(t.get(e));if(i)return i}return null}_readDests(){const e=this._catDict.get("Names");return e?.has("Dests")?new NameTree(e.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let e=null;try{e=this._readPageLabels()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}_readPageLabels(){const e=this._catDict.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let i=null,a="";const s=new NumberTree(e,this.xref).getAll();let r="",n=1;for(let e=0,g=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");n=e}else n=1}switch(i){case"D":r=n;break;case"R":case"r":r=toRomanNumerals(n,"r"===i);break;case"A":case"a":const e=26,t="a"===i?97:65,a=n-1;r=String.fromCharCode(t+a%e).repeat(Math.floor(a/e)+1);break;default:if(i)throw new FormatError(`Invalid style "${i}" in PageLabel dictionary.`);r=""}t[e]=a+r;n++}return t}get pageLayout(){const e=this._catDict.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this._catDict.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this._catDict.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const i of e.getKeys()){const a=e.get(i);let s;switch(i){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof a&&(s=a);break;case"NonFullScreenPageMode":if(a instanceof Name)switch(a.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":s=a.name;break;default:s="UseNone"}break;case"Direction":if(a instanceof Name)switch(a.name){case"L2R":case"R2L":s=a.name;break;default:s="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(a instanceof Name)switch(a.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":s=a.name;break;default:s="CropBox"}break;case"PrintScaling":if(a instanceof Name)switch(a.name){case"None":case"AppDefault":s=a.name;break;default:s="AppDefault"}break;case"Duplex":if(a instanceof Name)switch(a.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":s=a.name;break;default:s="None"}break;case"PrintPageRange":if(Array.isArray(a)&&a.length%2==0){a.every(((e,t,i)=>Number.isInteger(e)&&e>0&&(0===t||e>=i[t-1])&&e<=this.numPages))&&(s=a)}break;case"NumCopies":Number.isInteger(a)&&a>0&&(s=a);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${i}.`);continue}if(void 0!==s){t||(t=Object.create(null));t[i]=s}else warn(`Bad value, for key "${i}", in ViewerPreferences: ${a}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this._catDict.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const i=new Dict(this.xref);i.set("A",e);const a={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:i,resultObj:a});Array.isArray(a.dest)?t.dest=a.dest:a.action&&(t.action=a.action)}else Array.isArray(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const i=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,a]of i.getAll()){const i=new FileSpec(a,this.xref);t||(t=Object.create(null));t[stringToPDFString(e)]=i.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const i=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,a]of i.getAll()){t||(t=new Dict(this.xref));t.set(stringToPDFString(e),a)}}return shadow(this,"xfaImages",t)}_collectJavaScript(){const e=this._catDict.get("Names");let t=null;function appendIfJavaScriptDict(e,i){if(!(i instanceof Dict))return;if(!isName(i.get("S"),"JavaScript"))return;let a=i.get("JS");if(a instanceof BaseStream)a=a.getString();else if("string"!=typeof a)return;a=stringToPDFString(a).replaceAll("\0","");a&&(t||=new Map).set(e,a)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,i]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e),i)}const i=this._catDict.get("OpenAction");i&&appendIfJavaScriptDict("OpenAction",i);return t}get jsActions(){const e=this._collectJavaScript();let t=collectActions(this.xref,this._catDict,fA);if(e){t||=Object.create(null);for(const[i,a]of e)i in t?t[i].push(a):t[i]=[a]}return shadow(this,"jsActions",t)}async fontFallback(e,t){const i=await Promise.all(this.fontCache);for(const a of i)if(a.loadedName===e){a.fallback(t);return}}async cleanup(e=!1){clearGlobalCaches();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();const t=await Promise.all(this.fontCache);for(const{dict:e}of t)delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],i=new RefSet,a=this._catDict.getRaw("Pages");a instanceof Ref&&i.put(a);const s=this.xref,r=this.pageKidsCountCache,n=this.pageIndexCache,g=this.pageDictCache;let o=0;for(;t.length;){const a=t.pop();if(a instanceof Ref){const c=r.get(a);if(c>=0&&o+c<=e){o+=c;continue}if(i.has(a))throw new FormatError("Pages tree contains circular reference.");i.put(a);const C=await(g.get(a)||s.fetchAsync(a));if(C instanceof Dict){let t=C.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!C.has("Kids")){r.has(a)||r.put(a,1);n.has(a)||n.put(a,o);if(o===e)return[C,a];o++;continue}}t.push(C);continue}if(!(a instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:c}=a;let C=a.getRaw("Count");C instanceof Ref&&(C=await s.fetchAsync(C));if(Number.isInteger(C)&&C>=0){c&&!r.has(c)&&r.put(c,C);if(o+C<=e){o+=C;continue}}let h=a.getRaw("Kids");h instanceof Ref&&(h=await s.fetchAsync(h));if(!Array.isArray(h)){let t=a.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!a.has("Kids")){if(o===e)return[a,null];o++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--){const i=h[e];t.push(i);a===this.toplevelPagesDict&&i instanceof Ref&&!g.has(i)&&g.put(i,s.fetchAsync(i))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,i=[{currentNode:this.toplevelPagesDict,posInKids:0}],a=new RefSet,s=this._catDict.getRaw("Pages");s instanceof Ref&&a.put(s);const r=new Map,n=this.xref,g=this.pageIndexCache;let o=0;function addPageDict(e,t){t&&!g.has(t)&&g.put(t,o);r.set(o++,[e,t])}function addPageError(i){if(i instanceof XRefEntryException&&!e)throw i;if(e&&t&&0===o){warn(`getAllPageDicts - Skipping invalid first page: "${i}".`);i=Dict.empty}r.set(o++,[i,null])}for(;i.length>0;){const e=i.at(-1),{currentNode:t,posInKids:s}=e;let r=t.getRaw("Kids");if(r instanceof Ref)try{r=await n.fetchAsync(r)}catch(e){addPageError(e);break}if(!Array.isArray(r)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(s>=r.length){i.pop();continue}const g=r[s];let o;if(g instanceof Ref){if(a.has(g)){addPageError(new FormatError("Pages tree contains circular reference."));break}a.put(g);try{o=await n.fetchAsync(g)}catch(e){addPageError(e);break}}else o=g;if(!(o instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let c=o.getRaw("Type");if(c instanceof Ref)try{c=await n.fetchAsync(c)}catch(e){addPageError(e);break}isName(c,"Page")||!o.has("Kids")?addPageDict(o,g instanceof Ref?g:null):i.push({currentNode:o,posInKids:0});e.posInKids++}return r}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const i=this.xref;let a=0;const next=t=>function pagesBeforeRef(t){let a,s=0;return i.fetchAsync(t).then((function(i){if(isRefsEqual(t,e)&&!isDict(i,"Page")&&!(i instanceof Dict&&!i.has("Type")&&i.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!i)return null;if(!(i instanceof Dict))throw new FormatError("Node must be a dictionary.");a=i.getRaw("Parent");return i.getAsync("Parent")})).then((function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")})).then((function(e){if(!e)return null;const r=[];let n=!1;for(const a of e){if(!(a instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(a,t)){n=!0;break}r.push(i.fetchAsync(a).then((function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?s+=e.get("Count"):s++})))}if(!n)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(r).then((function(){return[s,a]}))}))}(t).then((t=>{if(!t){this.pageIndexCache.put(e,a);return a}const[i,s]=t;a+=i;return next(s)}));return next(e)}get baseUrl(){const e=this._catDict.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:i=null,docAttachments:a=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let s,r,n=e.get("A");if(!(n instanceof Dict))if(e.has("Dest"))n=e.get("Dest");else{n=e.get("AA");n instanceof Dict&&(n.has("D")?n=n.get("D"):n.has("U")&&(n=n.get("U")))}if(n instanceof Dict){const e=n.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const i=e.name;switch(i){case"ResetForm":const e=n.get("Flags"),g=!(1&("number"==typeof e?e:0)),o=[],c=[];for(const e of n.get("Fields")||[])e instanceof Ref?c.push(e.toString()):"string"==typeof e&&o.push(stringToPDFString(e));t.resetForm={fields:o,refs:c,include:g};break;case"URI":s=n.get("URI");s instanceof Name&&(s="/"+s.name);break;case"GoTo":r=n.get("D");break;case"Launch":case"GoToR":const C=n.get("F");if(C instanceof Dict){const e=new FileSpec(C,null,!0),{rawFilename:t}=e.serializable;s=t}else"string"==typeof C&&(s=C);const h=fetchRemoteDest(n);h&&"string"==typeof s&&(s=s.split("#",1)[0]+"#"+h);const l=n.get("NewWindow");"boolean"==typeof l&&(t.newWindow=l);break;case"GoToE":const Q=n.get("T");let E;if(a&&Q instanceof Dict){const e=Q.get("R"),t=Q.get("N");isName(e,"C")&&"string"==typeof t&&(E=a[stringToPDFString(t)])}if(E){t.attachment=E;const e=fetchRemoteDest(n);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const u=n.get("N");u instanceof Name&&(t.action=u.name);break;case"SetOCGState":const d=n.get("State"),f=n.get("PreserveRB");if(!Array.isArray(d)||0===d.length)break;const p=[];for(const e of d)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":p.push(e.name)}else e instanceof Ref&&p.push(e.toString());if(p.length!==d.length)break;t.setOCGState={state:p,preserveRB:"boolean"!=typeof f||f};break;case"JavaScript":const m=n.get("JS");let y;m instanceof BaseStream?y=m.getString():"string"==typeof m&&(y=m);const w=y&&recoverJsURL(stringToPDFString(y));if(w){s=w.url;t.newWindow=w.newWindow;break}default:if("JavaScript"===i||"SubmitForm"===i)break;warn(`parseDestDictionary - unsupported action: "${i}".`)}}else e.has("Dest")&&(r=e.get("Dest"));if("string"==typeof s){const e=createValidAbsoluteUrl(s,i,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=s}if(r){r instanceof Name&&(r=r.name);"string"==typeof r?t.dest=stringToPDFString(r):isValidExplicitDest(r)&&(t.dest=r)}}}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const a of e)((i=a)instanceof Ref||i instanceof Dict||i instanceof BaseStream||Array.isArray(i))&&t.push(a);var i}class ObjectLoader{constructor(e,t,i){this.dict=e;this.keys=t;this.xref=i;this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:e,dict:t}=this;this.refSet=new RefSet;const i=[];for(const a of e){const e=t.getRaw(a);void 0!==e&&i.push(e)}return this._walk(i)}async _walk(e){const t=[],i=[];for(;e.length;){let a=e.pop();if(a instanceof Ref){if(this.refSet.has(a))continue;try{this.refSet.put(a);a=this.xref.fetch(a)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader._walk - requesting all data: "${e}".`);this.refSet=null;const{manager:t}=this.xref.stream;return t.requestAllChunks()}t.push(a);i.push({begin:e.begin,end:e.end})}}if(a instanceof BaseStream){const e=a.getBaseStreams();if(e){let s=!1;for(const t of e)if(!t.isDataLoaded){s=!0;i.push({begin:t.start,end:t.end})}s&&t.push(a)}}addChildren(a,e)}if(i.length){await this.xref.stream.manager.requestRanges(i);for(const e of t)e instanceof Ref&&this.refSet.remove(e);return this._walk(t)}this.refSet=null}}const xs=Symbol(),Ls=Symbol(),Hs=Symbol(),Js=Symbol(),Ys=Symbol(),vs=Symbol(),Ks=Symbol(),Ts=Symbol(),qs=Symbol(),Os=Symbol("content"),Ws=Symbol("data"),js=Symbol(),Xs=Symbol("extra"),Zs=Symbol(),Vs=Symbol(),zs=Symbol(),_s=Symbol(),$s=Symbol(),Ar=Symbol(),er=Symbol(),tr=Symbol(),ir=Symbol(),ar=Symbol(),sr=Symbol(),rr=Symbol(),nr=Symbol(),gr=Symbol(),or=Symbol(),Ir=Symbol(),cr=Symbol(),Cr=Symbol(),hr=Symbol(),lr=Symbol(),Qr=Symbol(),Er=Symbol(),ur=Symbol(),dr=Symbol(),fr=Symbol(),pr=Symbol(),mr=Symbol(),yr=Symbol(),wr=Symbol(),Dr=Symbol(),br=Symbol(),Fr=Symbol(),Sr=Symbol("namespaceId"),kr=Symbol("nodeName"),Rr=Symbol(),Nr=Symbol(),Gr=Symbol(),Mr=Symbol(),Ur=Symbol(),xr=Symbol(),Lr=Symbol(),Hr=Symbol(),Jr=Symbol("root"),Yr=Symbol(),vr=Symbol(),Kr=Symbol(),Tr=Symbol(),qr=Symbol(),Or=Symbol(),Pr=Symbol(),Wr=Symbol(),jr=Symbol(),Xr=Symbol(),Zr=Symbol(),Vr=Symbol("uid"),zr=Symbol(),_r={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},$r={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},An=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseInt(e,10);return!isNaN(a)&&i(a)?a:t}function getFloat({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseFloat(e);return!isNaN(a)&&i(a)?a:t}function getKeyword({data:e,defaultValue:t,validate:i}){return e&&i(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const i=e.trim().match(An);if(!i)return getMeasurement(t);const[,a,s]=i,r=parseFloat(a);if(isNaN(r))return getMeasurement(t);if(0===r)return 0;const n=$r[s];return n?n(r):r}function getRatio(e){if(!e)return{num:1,den:1};const t=e.trim().split(/\s*:\s*/).map((e=>parseFloat(e))).filter((e=>!isNaN(e)));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[i,a]=t;return{num:i,den:a}}function getRelevant(e){return e?e.trim().split(/\s+/).map((e=>({excluded:"-"===e[0],viewname:e.substring(1)}))):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,i,a){this.success=e;this.html=t;this.bbox=i;this.breakNode=a}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const i=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,i)}addPdfFont(e){const t=e.cssFontInfo,i=t.fontFamily;let a=this.fonts.get(i);if(!a){a=Object.create(null);this.fonts.set(i,a);this.defaultFont||(this.defaultFont=a)}let s="";const r=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?s=r>=700?"bolditalic":"italic":r>=700&&(s="bold");if(!s){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(s="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(s+="italic")}s||(s="regular");a[s]=e}getDefault(){return this.defaultFont}find(e,t=!0){let i=this.fonts.get(e)||this.cache.get(e);if(i)return i;const a=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let s=e.replaceAll(a,"");i=this.fonts.get(s);if(i){this.cache.set(e,i);return i}s=s.toLowerCase();const r=[];for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t);if(0===r.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(0===r.length){s=s.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t)}if(0===r.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(r.length>=1){1!==r.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,r[0]);return r[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class FontInfo{constructor(e,t,i,a){this.lineHeight=i;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(a);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const s=a.find(e.typeface);if(s){this.pdfFont=selectFont(e,s);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(a))}else[this.pdfFont,this.xfaFont]=this.defaultFont(a)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,i,a){this.fontFinder=a;this.stack=[new FontInfo(e,t,i,a)]}pushData(e,t,i){const a=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=a.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=a.paraMargin[e]);const s=new FontInfo(e,t,i||a.lineHeight,this.fontFinder);s.pdfFont||(s.pdfFont=a.pdfFont);this.stack.push(s)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,i,a){this.glyphs=[];this.fontSelector=new FontSelector(e,t,i,a);this.extraHeight=0}pushData(e,t,i){this.fontSelector.pushData(e,t,i)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),i=t.xfaFont.size;if(t.pdfFont){const a=t.xfaFont.letterSpacing,s=t.pdfFont,r=s.lineHeight||1.2,n=t.lineHeight||Math.max(1.2,r)*i,g=r-(void 0===s.lineGap?.2:s.lineGap),o=Math.max(1,g)*i,c=i/1e3,C=s.defaultWidth||s.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=s.encodeString(t).join(""),i=s.charsToGlyphs(e);for(const e of i){const t=e.width||C;this.glyphs.push([t*c+a,n,o,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([i,1.2*i,i,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(e){let t=-1,i=0,a=0,s=0,r=0,n=0,g=!1,o=!0;for(let c=0,C=this.glyphs.length;ce){a=Math.max(a,r);r=0;s+=n;n=d;t=-1;i=0;g=!0;o=!1}else{n=Math.max(d,n);i=r;r+=C;t=c}else if(r+C>e){s+=n;n=d;if(-1!==t){c=t;a=Math.max(a,i);r=0;t=-1;i=0}else{a=Math.max(a,r);r=C}g=!0;o=!1}else{r+=C;n=Math.max(d,n)}}a=Math.max(a,r);s+=n+this.extraHeight;return{width:1.02*a,height:s,isBroken:g}}}const en=/^[^.[]+/,tn=/^[^\]]+/,an=0,sn=1,rn=2,nn=3,gn=4,on=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[rr]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),In=new WeakMap;function parseExpression(e,t,i=!0){let a=e.match(en);if(!a)return null;let[s]=a;const r=[{name:s,cacheName:"."+s,index:0,js:null,formCalc:null,operator:an}];let n=s.length;for(;n0&&C.push(e)}if(0!==C.length||g||0!==o)e=isFinite(c)?C.filter((e=>ce[c])):C.flat();else{const i=t[Ir]();if(!(t=i))return null;o=-1;e=[t]}}return 0===e.length?null:e}function createDataNode(e,t,i){const a=parseExpression(i);if(!a)return null;if(a.some((e=>e.operator===sn)))return null;const s=on.get(a[0].name);let r=0;if(s){e=s(e,t);r=1}else e=t||e;for(let t=a.length;re[Pr]())).join("")}get[hn](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,hn,e._attributes)}[pr](e){let t=this;for(;t;){if(t===e)return!0;t=t[Ir]()}return!1}[Ir](){return this[wn]}[or](){return this[Ir]()}[rr](e=null){return e?this[e]:this[ln]}[js](){const e=Object.create(null);this[Os]&&(e.$content=this[Os]);for(const t of Object.getOwnPropertyNames(this)){const i=this[t];null!==i&&(i instanceof XFAObject?e[t]=i[js]():i instanceof XFAObjectArray?i.isEmpty()||(e[t]=i.dump()):e[t]=i)}return e}[Zr](){return null}[jr](){return HTMLResult.EMPTY}*[nr](){for(const e of this[rr]())yield e}*[un](e,t){for(const i of this[nr]())if(!e||t===e.has(i[kr])){const e=this[$s](),t=i[jr](e);t.success||(this[Xs].failingNode=i);yield t}}[Vs](){return null}[Ls](e,t){this[Xs].children.push(e)}[$s](){}[Js]({filter:e=null,include:t=!0}){if(this[Xs].generator){const e=this[$s](),t=this[Xs].failingNode[jr](e);if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox);delete this[Xs].failingNode}else this[Xs].generator=this[un](e,t);for(;;){const e=this[Xs].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Ls](t.html,t.bbox)}this[Xs].generator=null;return HTMLResult.EMPTY}[Tr](e){this[bn]=new Set(Object.keys(e))}[fn](e){const t=this[hn],i=this[bn];return[...e].filter((e=>t.has(e)&&!i.has(e)))}[Yr](e,t=new Set){for(const i of this[ln])i[Dn](e,t)}[Dn](e,t){const i=this[dn](e,t);i?this[cn](i,e,t):this[Yr](e,t)}[dn](e,t){const{use:i,usehref:a}=this;if(!i&&!a)return null;let s=null,r=null,n=null,g=i;if(a){g=a;a.startsWith("#som(")&&a.endsWith(")")?r=a.slice(5,-1):a.startsWith(".#som(")&&a.endsWith(")")?r=a.slice(6,-1):a.startsWith("#")?n=a.slice(1):a.startsWith(".#")&&(n=a.slice(2))}else i.startsWith("#")?n=i.slice(1):r=i;this.use=this.usehref="";if(n)s=e.get(n);else{s=searchNode(e.get(Jr),this,r,!0,!1);s&&(s=s[0])}if(!s){warn(`XFA - Invalid prototype reference: ${g}.`);return null}if(s[kr]!==this[kr]){warn(`XFA - Incompatible prototype: ${s[kr]} !== ${this[kr]}.`);return null}if(t.has(s)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(s);const o=s[dn](e,t);o&&s[cn](o,e,t);s[Yr](e,t);t.delete(s);return s}[cn](e,t,i){if(i.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Os]&&e[Os]&&(this[Os]=e[Os]);new Set(i).add(e);for(const t of this[fn](e[bn])){this[t]=e[t];this[bn]&&this[bn].add(t)}for(const a of Object.getOwnPropertyNames(this)){if(this[hn].has(a))continue;const s=this[a],r=e[a];if(s instanceof XFAObjectArray){for(const e of s[ln])e[Dn](t,i);for(let a=s[ln].length,n=r[ln].length;aXFAObject[Bn](e))):"object"==typeof e&&null!==e?Object.assign({},e):e}[Ts](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Vr]=`${e[kr]}${Sn++}`;e[ln]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[hn].has(t)){e[t]=XFAObject[Bn](this[t]);continue}const i=this[t];e[t]=i instanceof XFAObjectArray?new XFAObjectArray(i[mn]):null}for(const t of this[ln]){const i=t[kr],a=t[Ts]();e[ln].push(a);a[wn]=e;null===e[i]?e[i]=a:e[i][ln].push(a)}return e}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[Ar](e){return this[e]}[er](e,t,i=!0){return Array.from(this[tr](e,t,i))}*[tr](e,t,i=!0){if("parent"!==e){for(const i of this[ln]){i[kr]===e&&(yield i);i.name===e&&(yield i);(t||i[Dr]())&&(yield*i[tr](e,t,!1))}i&&this[hn].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[wn]}}class XFAObjectArray{constructor(e=1/0){this[mn]=e;this[ln]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[ln].length<=this[mn]){this[ln].push(e);return!0}warn(`XFA - node "${e[kr]}" accepts no more than ${this[mn]} children`);return!1}isEmpty(){return 0===this[ln].length}dump(){return 1===this[ln].length?this[ln][0][js]():this[ln].map((e=>e[js]()))}[Ts](){const e=new XFAObjectArray(this[mn]);e[ln]=this[ln].map((e=>e[Ts]()));return e}get children(){return this[ln]}clear(){this[ln].length=0}}class XFAAttribute{constructor(e,t,i){this[wn]=e;this[kr]=t;this[Os]=i;this[qs]=!1;this[Vr]="attribute"+Sn++}[Ir](){return this[wn]}[fr](){return!0}[ir](){return this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[Pr](){return this[Os]}[pr](e){return this[wn]===e||this[wn][pr](e)}}class XmlObject extends XFAObject{constructor(e,t,i={}){super(e,t);this[Os]="";this[Qn]=null;if("#text"!==t){const e=new Map;this[Cn]=e;for(const[t,a]of Object.entries(i))e.set(t,new XFAAttribute(this,t,a));if(i.hasOwnProperty(Rr)){const e=i[Rr].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[Qn]=!1:"dataValue"===e&&(this[Qn]=!0))}}this[qs]=!1}[Xr](e){const t=this[kr];if("#text"===t){e.push(encodeToXmlString(this[Os]));return}const i=utf8StringToString(t),a=this[Sr]===kn?"xfa:":"";e.push(`<${a}${i}`);for(const[t,i]of this[Cn].entries()){const a=utf8StringToString(t);e.push(` ${a}="${encodeToXmlString(i[Os])}"`)}null!==this[Qn]&&(this[Qn]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Os]||0!==this[ln].length){e.push(">");if(this[Os])"string"==typeof this[Os]?e.push(encodeToXmlString(this[Os])):this[Os][Xr](e);else for(const t of this[ln])t[Xr](e);e.push(``)}else e.push("/>")}[Nr](e){if(this[Os]){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];this[Os]=""}this[Hs](e);return!0}[Mr](e){this[Os]+=e}[Zs](){if(this[Os]&&this[ln].length>0){const e=new XmlObject(this[Sr],"#text");this[Hs](e);e[Os]=this[Os];delete this[Os]}}[jr](){return"#text"===this[kr]?HTMLResult.success({name:"#text",value:this[Os]}):HTMLResult.EMPTY}[rr](e=null){return e?this[ln].filter((t=>t[kr]===e)):this[ln]}[_s](){return this[Cn]}[Ar](e){const t=this[Cn].get(e);return void 0!==t?t:this[rr](e)}*[tr](e,t){const i=this[Cn].get(e);i&&(yield i);for(const i of this[ln]){i[kr]===e&&(yield i);t&&(yield*i[tr](e,t))}}*[zs](e,t){const i=this[Cn].get(e);!i||t&&i[qs]||(yield i);for(const i of this[ln])yield*i[zs](e,t)}*[sr](e,t,i){for(const a of this[ln]){a[kr]!==e||i&&a[qs]||(yield a);t&&(yield*a[sr](e,t,i))}}[fr](){return null===this[Qn]?0===this[ln].length||this[ln][0][Sr]===_r.xhtml.id:this[Qn]}[ir](){return null===this[Qn]?0===this[ln].length?this[Os].trim():this[ln][0][Sr]===_r.xhtml.id?this[ln][0][Pr]().trim():null:this[Os].trim()}[qr](e){e=e.value||"";this[Os]=e.toString()}[js](e=!1){const t=Object.create(null);e&&(t.$ns=this[Sr]);this[Os]&&(t.$content=this[Os]);t.$name=this[kr];t.children=[];for(const i of this[ln])t.children.push(i[js](e));t.attributes=Object.create(null);for(const[e,i]of this[Cn])t.attributes[e]=i[Os];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Os]=""}[Mr](e){this[Os]+=e}[Zs](){}}class OptionObject extends ContentObject{constructor(e,t,i){super(e,t);this[yn]=i}[Zs](){this[Os]=getKeyword({data:this[Os],defaultValue:this[yn][0],validate:e=>this[yn].includes(e)})}[Ys](e){super[Ys](e);delete this[yn]}}class StringObject extends ContentObject{[Zs](){this[Os]=this[Os].trim()}}class IntegerObject extends ContentObject{constructor(e,t,i,a){super(e,t);this[En]=i;this[Fn]=a}[Zs](){this[Os]=getInteger({data:this[Os],defaultValue:this[En],validate:this[Fn]})}[Ys](e){super[Ys](e);delete this[En];delete this[Fn]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,(e=>1===e))}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,(e=>0===e))}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Rn={anchorType(e,t){const i=e[or]();if(i&&(!i.layout||"position"===i.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const i=e[or]();let a=e.w;const s=e.h;if(i.layout?.includes("row")){const t=i[Xs],s=e.colSpan;let r;if(-1===s){r=t.columnWidths.slice(t.currentColumn).reduce(((e,t)=>e+t),0);t.currentColumn=0}else{r=t.columnWidths.slice(t.currentColumn,t.currentColumn+s).reduce(((e,t)=>e+t),0);t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(r)||(a=e.w=r)}t.width=""!==a?measureToString(a):"auto";t.height=""!==s?measureToString(s):"auto"},position(e,t){const i=e[or]();if(!i?.layout||"position"===i.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[kr])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Zr]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[or]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,i,a,s,r){const n=new TextMeasure(t,i,a,s);"string"==typeof e?n.addString(e):e[Ur](n);return n.compute(r)}function layoutNode(e,t){let i=null,a=null,s=!1;if((!e.w||!e.h)&&e.value){let r=0,n=0;if(e.margin){r=e.margin.leftInset+e.margin.rightInset;n=e.margin.topInset+e.margin.bottomInset}let g=null,o=null;if(e.para){o=Object.create(null);g=""===e.para.lineHeight?null:e.para.lineHeight;o.top=""===e.para.spaceAbove?0:e.para.spaceAbove;o.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;o.left=""===e.para.marginLeft?0:e.para.marginLeft;o.right=""===e.para.marginRight?0:e.para.marginRight}let c=e.font;if(!c){const t=e[cr]();let i=e[Ir]();for(;i&&i!==t;){if(i.font){c=i.font;break}i=i[Ir]()}}const C=(e.w||t.width)-r,h=e[Cr].fontFinder;if(e.value.exData&&e.value.exData[Os]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Os],c,o,g,h,C);a=t.width;i=t.height;s=t.isBroken}else{const t=e.value[Pr]();if(t){const e=layoutText(t,c,o,g,h,C);a=e.width;i=e.height;s=e.isBroken}}null===a||e.w||(a+=r);null===i||e.h||(i+=n)}return{w:a,h:i,isBroken:s}}function computeBbox(e,t,i){let a;if(""!==e.w&&""!==e.h)a=[e.x,e.y,e.w,e.h];else{if(!i)return null;let s=e.w;if(""===s){if(0===e.maxW){const t=e[or]();s="position"===t.layout&&""!==t.w?0:e.minW}else s=Math.min(e.maxW,i.width);t.attributes.style.width=measureToString(s)}let r=e.h;if(""===r){if(0===e.maxH){const t=e[or]();r="position"===t.layout&&""!==t.h?0:e.minH}else r=Math.min(e.maxH,i.height);t.attributes.style.height=measureToString(r)}a=[e.x,e.y,s,r]}return a}function fixDimensions(e){const t=e[or]();if(t.layout?.includes("row")){const i=t[Xs],a=e.colSpan;let s;s=-1===a?i.columnWidths.slice(i.currentColumn).reduce(((e,t)=>e+t),0):i.columnWidths.slice(i.currentColumn,i.currentColumn+a).reduce(((e,t)=>e+t),0);isNaN(s)||(e.w=s)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=e.columnWidths.reduce(((e,t)=>e+t),0))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const i=Object.create(null);for(const a of t){const t=e[a];if(null!==t)if(Rn.hasOwnProperty(a))Rn[a](e,i);else if(t instanceof XFAObject){const e=t[Zr]();e?Object.assign(i,e):warn(`(DEBUG) - XFA - style for ${a} not implemented yet`)}}return i}function createWrapper(e,t){const{attributes:i}=t,{style:a}=i,s={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};i.class.push("xfaWrapped");if(e.border){const{widths:i,insets:r}=e.border[Xs];let n,g,o=r[0],c=r[3];const C=r[0]+r[2],h=r[1]+r[3];switch(e.border.hand){case"even":o-=i[0]/2;c-=i[3]/2;n=`calc(100% + ${(i[1]+i[3])/2-h}px)`;g=`calc(100% + ${(i[0]+i[2])/2-C}px)`;break;case"left":o-=i[0];c-=i[3];n=`calc(100% + ${i[1]+i[3]-h}px)`;g=`calc(100% + ${i[0]+i[2]-C}px)`;break;case"right":n=h?`calc(100% - ${h}px)`:"100%";g=C?`calc(100% - ${C}px)`:"100%"}const l=["xfaBorder"];isPrintOnly(e.border)&&l.push("xfaPrintOnly");const Q={name:"div",attributes:{class:l,style:{top:`${o}px`,left:`${c}px`,width:n,height:g}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==a[e]){Q.attributes.style[e]=a[e];delete a[e]}s.children.push(Q,t)}else s.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==a[e]){s.attributes.style[e]=a[e];delete a[e]}s.attributes.style.position="absolute"===a.position?"absolute":"relative";delete a.position;if(a.alignSelf){s.attributes.style.alignSelf=a.alignSelf;delete a.alignSelf}return s}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const i="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),a=getMeasurement(e[i],"0px");e[i]=a-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[cr]()[Xs].paraStack;return t.length?t.at(-1):null}function setPara(e,t,i){if(i.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const a=getCurrentPara(e);if(a){const e=i.attributes.style;e.display="flex";e.flexDirection="column";switch(a.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=a[Zr]();for(const[i,a]of Object.entries(t))i in e||(e[i]=a)}}}function setFontFamily(e,t,i,a){if(!i){delete a.fontFamily;return}const s=stripQuotes(e.typeface);a.fontFamily=`"${s}"`;const r=i.find(s);if(r){const{fontFamily:i}=r.regular.cssFontInfo;i!==s&&(a.fontFamily=`"${i}"`);const n=getCurrentPara(t);if(n&&""!==n.lineHeight)return;if(a.lineHeight)return;const g=selectFont(e,r);g&&(a.lineHeight=Math.max(1.2,g.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Xs])return null;const t={name:"div",attributes:e[Xs].attributes,children:e[Xs].children};if(e[Xs].failingNode){const i=e[Xs].failingNode[Vs]();i&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[i])):t.children.push(i))}return 0===t.children.length?null:t}function addHTML(e,t,i){const a=e[Xs],s=a.availableSpace,[r,n,g,o]=i;switch(e.layout){case"position":a.width=Math.max(a.width,r+g);a.height=Math.max(a.height,n+o);a.children.push(t);break;case"lr-tb":case"rl-tb":if(!a.line||1===a.attempt){a.line=createLine(e,[]);a.children.push(a.line);a.numberInLine=0}a.numberInLine+=1;a.line.children.push(t);if(0===a.attempt){a.currentWidth+=g;a.height=Math.max(a.height,a.prevHeight+o)}else{a.currentWidth=g;a.prevHeight=a.height;a.height+=o;a.attempt=0}a.width=Math.max(a.width,a.currentWidth);break;case"rl-row":case"row":{a.children.push(t);a.width+=g;a.height=Math.max(a.height,o);const e=measureToString(a.height);for(const t of a.children)t.attributes.style.height=e;break}case"table":case"tb":a.width=Math.min(s.width,Math.max(a.width,g));a.height+=o;a.children.push(t)}}function getAvailableSpace(e){const t=e[Xs].availableSpace,i=e.margin?e.margin.topInset+e.margin.bottomInset:0,a=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Xs].attempt?{width:t.width-a-e[Xs].currentWidth,height:t.height-i-e[Xs].prevHeight}:{width:t.width-a,height:t.height-i-e[Xs].height};case"rl-row":case"row":return{width:e[Xs].columnWidths.slice(e[Xs].currentColumn).reduce(((e,t)=>e+t)),height:t.height-a};case"table":case"tb":return{width:t.width-a,height:t.height-i-e[Xs].height};default:return t}}function checkDimensions(e,t){if(null===e[cr]()[Xs].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const i=e[or](),a=i[Xs]?.attempt||0,[,s,r,n]=function getTransformedBBox(e){let t,i,a=""===e.w?NaN:e.w,s=""===e.h?NaN:e.h,[r,n]=[0,0];switch(e.anchorType||""){case"bottomCenter":[r,n]=[a/2,s];break;case"bottomLeft":[r,n]=[0,s];break;case"bottomRight":[r,n]=[a,s];break;case"middleCenter":[r,n]=[a/2,s/2];break;case"middleLeft":[r,n]=[0,s/2];break;case"middleRight":[r,n]=[a,s/2];break;case"topCenter":[r,n]=[a/2,0];break;case"topRight":[r,n]=[a,0]}switch(e.rotate||0){case 0:[t,i]=[-r,-n];break;case 90:[t,i]=[-n,r];[a,s]=[s,-a];break;case 180:[t,i]=[r,n];[a,s]=[-a,-s];break;case 270:[t,i]=[n,-r];[a,s]=[-s,a]}return[e.x+t+Math.min(0,a),e.y+i+Math.min(0,s),Math.abs(a),Math.abs(s)]}(e);switch(i.layout){case"lr-tb":case"rl-tb":return 0===a?e[cr]()[Xs].noLayoutFailure?""!==e.w?Math.round(r-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(n-t.height)>2)&&(""!==e.w?Math.round(r-t.width)<=2||0===i[Xs].numberInLine&&t.height>2:t.width>2):!!e[cr]()[Xs].noLayoutFailure||!(""!==e.h&&Math.round(n-t.height)>2)&&((""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2);case"table":case"tb":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||e[yr]()?(""===e.w||Math.round(r-t.width)<=2||!i[wr]())&&t.height>2:Math.round(n-t.height)<=2);case"position":if(e[cr]()[Xs].noLayoutFailure)return!0;if(""===e.h||Math.round(n+s-t.height)<=2)return!0;return n+s>e[cr]()[Xs].currentContentArea.h;case"rl-row":case"row":return!!e[cr]()[Xs].noLayoutFailure||(""===e.h||Math.round(n-t.height)<=2);default:return!0}}const Nn=_r.template.id,Gn="http://www.w3.org/2000/svg",Mn=/^H(\d+)$/,Un=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),xn=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[ar]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[Hs](t);e.value=t}e.value[qr](t)}function*getContainedChildren(e){for(const t of e[rr]())t instanceof SubformSet?yield*t[nr]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[Or]=e[Ir]()[Or];return}if(e[Or])return;let t=null;for(const i of e.traversal[rr]())if("next"===i.operation){t=i;break}if(!t||!t.ref){e[Or]=e[Ir]()[Or];return}const i=e[cr]();e[Or]=++i[Or];const a=i[vr](t.ref,e);if(!a)return;e=a[0]}}function applyAssist(e,t){const i=e.assist;if(i){const e=i[jr]();e&&(t.title=e);const a=i.role.match(Mn);if(a){const e="heading",i=a[1];t.role=e;t["aria-level"]=i}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const i=e[Ir]();"row"===i.layout&&(t.role="TH"===i.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Os]?t.speak[Os]:t.toolTip?t.toolTip[Os]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[cr]();if(null===t[Xs].firstUnsplittable){t[Xs].firstUnsplittable=e;t[Xs].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[cr]();t[Xs].firstUnsplittable===e&&(t[Xs].noLayoutFailure=!1)}function handleBreak(e){if(e[Xs])return!1;e[Xs]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[cr]();let i=null;if(e.target){i=t[vr](e.target,e[Ir]());if(!i)return!1;i=i[0]}const{currentPageArea:a,currentContentArea:s}=t[Xs];if("pageArea"===e.targetType){i instanceof PageArea||(i=null);if(e.startNew){e[Xs].target=i||a;return!0}if(i&&i!==a){e[Xs].target=i;return!0}return!1}i instanceof ContentArea||(i=null);const r=i&&i[Ir]();let n,g=r;if(e.startNew)if(i){const e=r.contentArea.children,t=e.indexOf(s),a=e.indexOf(i);-1!==t&&te;a[Xs].noLayoutFailure=!0;const n=t[jr](i);e[Ls](n.html,n.bbox);a[Xs].noLayoutFailure=s;t[or]=r}class AppearanceFilter extends StringObject{constructor(e){super(Nn,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Nn,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[jr](){const e=this.edge||new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;let a;const s={xmlns:Gn,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)a={name:"ellipse",attributes:{xmlns:Gn,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:i}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,r=this.sweepAngle>180?1:0,[n,g,o,c]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];a={name:"path",attributes:{xmlns:Gn,d:`M ${n} ${g} A 50 50 0 ${r} 0 ${o} ${c}`,vectorEffect:"non-scaling-stroke",style:i}};Object.assign(s,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const r={name:"svg",children:[a],attributes:s};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[r]});r.attributes.style.position="absolute";return HTMLResult.success(r)}}class Area extends XFAObject{constructor(e){super(Nn,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[Dr](){return!0}[dr](){return!0}[Ls](e,t){const[i,a,s,r]=t;this[Xs].width=Math.max(this[Xs].width,i+s);this[Xs].height=Math.max(this[Xs].height,a+r);this[Xs].children.push(e)}[$s](){return this[Xs].availableSpace}[jr](e){const t=toStyle(this,"position"),i={style:t,id:this[Vr],class:["xfaArea"]};isPrintOnly(this)&&i.class.push("xfaPrintOnly");this.name&&(i.xfaName=this.name);const a=[];this[Xs]={children:a,width:0,height:0,availableSpace:e};const s=this[Js]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!s.success){if(s.isBreak())return s;delete this[Xs];return HTMLResult.FAILURE}t.width=measureToString(this[Xs].width);t.height=measureToString(this[Xs].height);const r={name:"div",attributes:i,children:a},n=[this.x,this.y,this[Xs].width,this[Xs].height];delete this[Xs];return HTMLResult.success(r,n)}}class Assist extends XFAObject{constructor(e){super(Nn,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[jr](){return this.toolTip?.[Os]||null}}class Barcode extends XFAObject{constructor(e){super(Nn,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Nn,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Nn,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Nn,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Nn,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[jr](e){return valueToHtml(1===this[Os]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Nn,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[ar](){if(!this[Xs]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let i=e.length;i<4;i++)e.push(t)}const t=e.map((e=>e.thickness)),i=[0,0,0,0];if(this.margin){i[0]=this.margin.topInset;i[1]=this.margin.rightInset;i[2]=this.margin.bottomInset;i[3]=this.margin.leftInset}this[Xs]={widths:t,insets:i,edges:e}}return this[Xs]}[Zr](){const{edges:e}=this[ar](),t=e.map((e=>{const t=e[Zr]();t.color||="#000000";return t})),i=Object.create(null);this.margin&&Object.assign(i,this.margin[Zr]());"visible"===this.fill?.presence&&Object.assign(i,this.fill[Zr]());if(this.corner.children.some((e=>0!==e.radius))){const e=this.corner.children.map((e=>e[Zr]()));if(2===e.length||3===e.length){const t=e.at(-1);for(let i=e.length;i<4;i++)e.push(t)}i.borderRadius=e.map((e=>e.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":i.borderStyle="";break;case"inactive":i.borderStyle="none";break;default:i.borderStyle=t.map((e=>e.style)).join(" ")}i.borderWidth=t.map((e=>e.width)).join(" ");i.borderColor=t.map((e=>e.color)).join(" ");return i}}class Break extends XFAObject{constructor(e){super(Nn,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Nn,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Nn,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[jr](e){this[Xs]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Nn,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[jr](e){const t=this[Ir]()[Ir](),i={name:"button",attributes:{id:this[Vr],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Os]);if(!t)continue;const a=fixURL(t.url);a&&i.children.push({name:"a",attributes:{id:"link"+this[Vr],href:a,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(i)}}class Calculate extends XFAObject{constructor(e){super(Nn,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Nn,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[qr](e){_setValue(this,e)}[ar](e){if(!this[Xs]){let{width:t,height:i}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":i=this.reserve<=0?i:this.reserve}this[Xs]=layoutNode(this,{width:t,height:i})}return this[Xs]}[jr](e){if(!this.value)return HTMLResult.EMPTY;this[Lr]();const t=this.value[jr](e).html;if(!t){this[xr]();return HTMLResult.EMPTY}const i=this.reserve;if(this.reserve<=0){const{w:t,h:i}=this[ar](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=i}}const a=[];"string"==typeof t?a.push({name:"#text",value:t}):a.push(t);const s=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(s.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(s.height=measureToString(this.reserve))}setPara(this,null,t);this[xr]();this.reserve=i;return HTMLResult.success({name:"div",attributes:{style:s,class:["xfaCaption"]},children:a})}}class Certificate extends StringObject{constructor(e){super(Nn,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Nn,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Nn,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle("margin"),i=measureToString(this.size);t.width=t.height=i;let a,s,r;const n=this[Ir]()[Ir](),g=n.items.children.length&&n.items.children[0][jr]().html||[],o={on:(void 0!==g[0]?g[0]:"on").toString(),off:(void 0!==g[1]?g[1]:"off").toString()},c=(n.value?.[Pr]()||"off")===o.on||void 0,C=n[or](),h=n[Vr];let l;if(C instanceof ExclGroup){r=C[Vr];a="radio";s="xfaRadio";l=C[Ws]?.[Vr]||C[Vr]}else{a="checkbox";s="xfaCheckbox";l=n[Ws]?.[Vr]||n[Vr]}const Q={name:"input",attributes:{class:[s],style:t,fieldId:h,dataId:l,type:a,checked:c,xfaOn:o.on,xfaOff:o.off,"aria-label":ariaLabel(n),"aria-required":!1}};r&&(Q.attributes.name=r);if(isRequired(n)){Q.attributes["aria-required"]=!0;Q.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[Q]})}}class ChoiceList extends XFAObject{constructor(e){super(Nn,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","margin"),i=this[Ir]()[Ir](),a={fontSize:`calc(${i.font?.size||10}px * var(--scale-factor))`},s=[];if(i.items.children.length>0){const e=i.items;let t=0,r=0;if(2===e.children.length){t=e.children[0].save;r=1-t}const n=e.children[t][jr]().html,g=e.children[r][jr]().html;let o=!1;const c=i.value?.[Pr]()||"";for(let e=0,t=n.length;eMath.min(Math.max(0,parseInt(e.trim(),10)),255))).map((e=>isNaN(e)?0:e));if(r.length<3)return{r:i,g:a,b:s};[i,a,s]=r;return{r:i,g:a,b:s}}(e.value):"";this.extras=null}[hr](){return!1}[Zr](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Nn,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Nn,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Nn,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[jr](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},i=["xfaContentarea"];isPrintOnly(this)&&i.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:i,id:this[Vr]}})}}class Corner extends XFAObject{constructor(e){super(Nn,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Nn,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Nn,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Nn,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Decimal extends ContentObject{constructor(e){super(Nn,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Nn,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Nn,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Nn,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Nn,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Nn,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Lr]();const t=this.w,i=this.h,{w:a,h:s,isBroken:r}=layoutNode(this,e);if(a&&""===this.w){if(r&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}this.w=a}s&&""===this.h&&(this.h=s);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=i;this[xr]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const n=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,n);if(n.margin){n.padding=n.margin;delete n.margin}const g=["xfaDraw"];this.font&&g.push("xfaFont");isPrintOnly(this)&&g.push("xfaPrintOnly");const o={style:n,id:this[Vr],class:g};this.name&&(o.xfaName=this.name);const c={name:"div",attributes:o,children:[]};applyAssist(this,o);const C=computeBbox(this,c,e),h=this.value?this.value[jr](e).html:null;if(null===h){this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}c.children.push(h);setPara(this,n,h);this.w=t;this.h=i;this[xr]();return HTMLResult.success(createWrapper(this,c),C)}}class Edge extends XFAObject{constructor(e){super(Nn,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Zr]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Nn,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Nn,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Nn,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Nn,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Nn,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Nn,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Nn,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Nn,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Nn,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ur](){return"text/html"===this.contentType}[Nr](e){if("text/html"===this.contentType&&e[Sr]===_r.xhtml.id){this[Os]=e;return!0}if("text/xml"===this.contentType){this[Os]=e;return!0}return!1}[jr](e){return"text/html"===this.contentType&&this[Os]?this[Os][jr](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Nn,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Nn,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[hr](){return!0}[qr](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[Hs](e);t.value=e}t.value[qr](e)}}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[jr](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,attributes:i,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[yr]();a||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["field"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const r=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),n=["xfaExclgroup"],g=layoutClass(this);g&&n.push(g);isPrintOnly(this)&&n.push("xfaPrintOnly");i.style=r;i.class=n;this.name&&(i.xfaName=this.name);this[Lr]();const o="lr-tb"===this.layout||"rl-tb"===this.layout,c=o?2:1;for(;this[Xs].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[dr](){return!0}[qr](e){_setValue(this,e)}[jr](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[Cr]=this[Cr];this[Hs](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[Hs](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Xs];this[Lr]();const t=this.caption?this.caption[jr](e).html:null,i=this.w,a=this.h;let s=0,r=0;if(this.margin){s=this.margin.leftInset+this.margin.rightInset;r=this.margin.topInset+this.margin.bottomInset}let n=null;if(""===this.w||""===this.h){let t=null,i=null,a=0,g=0;if(this.ui.checkButton)a=g=this.ui.checkButton.size;else{const{w:t,h:i}=layoutNode(this,e);if(null!==t){a=t;g=i}else g=function fonts_getMetrics(e,t=!1){let i=null;if(e){const t=stripQuotes(e.typeface),a=e[Cr].fontFinder.find(t);i=selectFont(e,a)}if(!i)return{lineHeight:12,lineGap:2,lineNoGap:10};const a=e.size||10,s=i.lineHeight?Math.max(t?0:1.2,i.lineHeight):1.2,r=void 0===i.lineGap?.2:i.lineGap;return{lineHeight:s*a,lineGap:r*a,lineNoGap:Math.max(1,s-r)*a}}(this.font,!0).lineNoGap}n=getBorderDims(this.ui[ar]());a+=n.w;g+=n.h;if(this.caption){const{w:s,h:r,isBroken:n}=this.caption[ar](e);if(n&&this[or]()[wr]()){this[xr]();return HTMLResult.FAILURE}t=s;i=r;switch(this.caption.placement){case"left":case"right":case"inline":t+=a;break;case"top":case"bottom":i+=g}}else{t=a;i=g}if(t&&""===this.w){t+=s;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Nn,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseFloat(this[Os].trim());this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Nn,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[Ys](e){super[Ys](e);this[Cr].usedTypefaces.add(this.typeface)}[Zr](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[Cr].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Nn,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Nn,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Nn,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Nn,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[jr](){if(this.contentType&&!Un.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[Cr].images&&this[Cr].images.get(this.href);if(!e&&(this.href||!this[Os]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=function fromBase64Util(e){return Uint8Array.fromBase64?Uint8Array.fromBase64(e):stringToBytes(atob(e))}(this[Os]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,i]of xn)if(e.length>t.length&&t.every(((t,i)=>t===e[i]))){this.contentType=i;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let i;switch(this.aspect){case"fit":case"actual":break;case"height":i={height:"100%",objectFit:"fill"};break;case"none":i={width:"100%",height:"100%",objectFit:"fill"};break;case"width":i={width:"100%",objectFit:"fill"}}const a=this[Ir]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:i,src:URL.createObjectURL(t),alt:a?ariaLabel(a[Ir]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Nn,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[jr](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Nn,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=parseInt(this[Os].trim(),10);this[Os]=isNaN(e)?null:e}[jr](e){return valueToHtml(null!==this[Os]?this[Os].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Nn,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Nn,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[jr](){const e=[];for(const t of this[rr]())e.push(t[Pr]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Nn,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Nn,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Nn,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[jr](){const e=this[Ir]()[Ir](),t=this.edge||new Edge({}),i=t[Zr](),a=Object.create(null),s="visible"===t.presence?t.thickness:0;a.strokeWidth=measureToString(s);a.stroke=i.color;let r,n,g,o,c="100%",C="100%";if(e.w<=s){[r,n,g,o]=["50%",0,"50%","100%"];c=a.strokeWidth}else if(e.h<=s){[r,n,g,o]=[0,"50%","100%","50%"];C=a.strokeWidth}else"\\"===this.slope?[r,n,g,o]=[0,0,"100%","100%"]:[r,n,g,o]=[0,"100%","100%",0];const h={name:"svg",children:[{name:"line",attributes:{xmlns:Gn,x1:r,y1:n,x2:g,y2:o,style:a}}],attributes:{xmlns:Gn,width:c,height:C,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[h]});h.attributes.style.position="absolute";return HTMLResult.success(h)}}class Linear extends XFAObject{constructor(e){super(Nn,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Zr]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Nn,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=getStringOption(this[Os],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Nn,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Nn,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Nn,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Nn,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const i=e.trim().split(/\s*,\s*/).map((e=>getMeasurement(e,"-1")));if(i.length<4||i[2]<0||i[3]<0)return{x:t,y:t,width:t,height:t};const[a,s,r,n]=i;return{x:a,y:s,width:r,height:n}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Nn,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Nn,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin"),i=this[Ir]()[Ir](),a={name:"input",attributes:{type:"text",fieldId:i[Vr],dataId:i[Ws]?.[Vr]||i[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Occur extends XFAObject{constructor(e){super(Nn,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](){const e=this[Ir](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[br](){if(!this[Xs]){this[Xs]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Xs].numberOfUsee.oddOrEven===t&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&"any"===e.pagePosition));return a||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Nn,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map(((e,t)=>t%2==1?getMeasurement(e):e));this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Zr](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Zr]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Nn,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Nn,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000",i="repeating-linear-gradient",a=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${i}(to top,${a}) ${i}(to right,${a})`;case"crossDiagonal":return`${i}(45deg,${a}) ${i}(-45deg,${a})`;case"diagonalLeft":return`${i}(45deg,${a})`;case"diagonalRight":return`${i}(-45deg,${a})`;case"horizontal":return`${i}(to top,${a})`;case"vertical":return`${i}(to right,${a})`}return""}}class Picture extends StringObject{constructor(e){super(Nn,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Nn,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Nn,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){e=e?e[Zr]():"#FFFFFF";const t=this.color?this.color[Zr]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Nn,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Nn,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Nn,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[jr](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Zr](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[Zr]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;const a=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Zr](),s={name:"svg",children:[{name:"rect",attributes:{xmlns:Gn,width:"100%",height:"100%",x:0,y:0,rx:a.radius,ry:a.radius,style:i}}],attributes:{xmlns:Gn,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[Ir]()[Ir]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]});s.attributes.style.position="absolute";return HTMLResult.success(s)}}class RefElement extends StringObject{constructor(e){super(Nn,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Nn,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Nn,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Nn,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Nn,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Nn,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Nn,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zr](e){return e?e[Zr]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Nn,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Nn,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zr](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Nn,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map((e=>"-1"===e?-1:getMeasurement(e)));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[or](){const e=this[Ir]();return e instanceof SubformSet?e[or]():e}[dr](){return!0}[wr](){return this.layout.endsWith("-tb")&&0===this[Xs].attempt&&this[Xs].numberInLine>0||this[Ir]()[wr]()}*[nr](){yield*getContainedChildren(this)}[Vs](){return flushHTML(this)}[Ls](e,t){addHTML(this,e,t)}[$s](){return getAvailableSpace(this)}[yr](){const e=this[or]();if(!e[yr]())return!1;if(void 0!==this[Xs]._isSplittable)return this[Xs]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Xs]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Xs]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Xs].numberInLine)return!1;this[Xs]._isSplittable=!0;return!0}[jr](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[Cr]=this[Cr];this[Hs](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[Cr]=this[Cr];this[Hs](e);this.overflow.push(e)}this[Hr](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Xs]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[Vr],class:[]};setAccess(this,i.class);this[Xs]||(this[Xs]=Object.create(null));Object.assign(this[Xs],{children:t,line:null,attributes:i,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[cr](),s=a[Xs].noLayoutFailure,r=this[yr]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const n=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[or]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Xs].columnWidths=e;this[Xs].currentColumn=0}}const g=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),o=["xfaSubform"],c=layoutClass(this);c&&o.push(c);i.style=g;i.class=o;this.name&&(i.xfaName=this.name);if(this.overflow){const t=this.overflow[ar]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Lr]();const C="lr-tb"===this.layout||"rl-tb"===this.layout,h=C?2:1;for(;this[Xs].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Xs].afterBreakAfter=p;return HTMLResult.breakNode(e)}}delete this[Xs];return p}}class SubformSet extends XFAObject{constructor(e){super(Nn,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[nr](){yield*getContainedChildren(this)}[or](){let e=this[Ir]();for(;!(e instanceof Subform);)e=e[Ir]();return e}[dr](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Nn,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){this[Os]=new Map(this[Os].split(this.delimiter).map((e=>{(e=e.split("=",2))[0]=e[0].trim();return e})))}}class SubjectDNs extends XFAObject{constructor(e){super(Nn,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Nn,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Nn,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Zs](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[Or]=5e3}[yr](){return!0}[vr](e,t){return e.startsWith("#")?[this[lr].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Wr](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Xs]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[vs]();const t=e.pageSet.pageArea.children,i={name:"div",children:[]};let a=null,s=null,r=null;if(e.breakBefore.children.length>=1){s=e.breakBefore.children[0];r=s.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){s=e.subform.children[0].breakBefore.children[0];r=s.target}else if(e.break?.beforeTarget){s=e.break;r=s.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){s=e.subform.children[0].break;r=s.beforeTarget}if(s){const e=this[vr](r,s[Ir]());if(e instanceof PageArea){a=e;s[Xs]={}}}a||(a=t[0]);a[Xs]={numberOfUse:1};const n=a[Ir]();n[Xs]={numberOfUse:1,pageIndex:n.pageArea.children.indexOf(a),pageSetIndex:0};let g,o=null,c=null,C=!0,h=0,l=0;for(;;){if(C)h=0;else{i.children.pop();if(3==++h){warn("XFA - Something goes wrong: please file a bug.");return i}}g=null;this[Xs].currentPageArea=a;const t=a[jr]().html;i.children.push(t);if(o){this[Xs].noLayoutFailure=!0;t.children.push(o[jr](a[Xs].space).html);o=null}if(c){this[Xs].noLayoutFailure=!0;t.children.push(c[jr](a[Xs].space).html);c=null}const s=a.contentArea.children,r=t.children.filter((e=>e.attributes.class.includes("xfaContentarea")));C=!1;this[Xs].firstUnsplittable=null;this[Xs].noLayoutFailure=!1;const flush=t=>{const i=e[Vs]();if(i){C||=i.children?.length>0;r[t].children.push(i)}};for(let t=l,a=s.length;t0;r[t].children.push(h.html)}else!C&&i.children.length>1&&i.children.pop();return i}if(h.isBreak()){const e=h.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){o=this[vr](e.leader,e[Ir]());o=o?o[0]:null}if(e.trailer){c=this[vr](e.trailer,e[Ir]());c=c?c[0]:null}if("pageArea"===e.targetType){g=e[Xs].target;t=1/0}else if(e[Xs].target){g=e[Xs].target;l=e[Xs].index+1;t=1/0}else t=e[Xs].index}else if(this[Xs].overflowNode){const e=this[Xs].overflowNode;this[Xs].overflowNode=null;const i=e[ar](),a=i.target;i.addLeader=null!==i.leader;i.addTrailer=null!==i.trailer;flush(t);const r=t;t=1/0;if(a instanceof PageArea)g=a;else if(a instanceof ContentArea){const e=s.indexOf(a);if(-1!==e)e>r?t=e-1:l=e;else{g=a[Ir]();l=g.contentArea.children.indexOf(a)}}}else flush(t)}this[Xs].pageNumber+=1;g&&(g[br]()?g[Xs].numberOfUse+=1:g=null);a=g||a[gr]();yield null}}}class Text extends ContentObject{constructor(e){super(Nn,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[xs](){return!0}[Nr](e){if(e[Sr]===_r.xhtml.id){this[Os]=e;return!0}warn(`XFA - Invalid content in Text: ${e[kr]}.`);return!1}[Mr](e){this[Os]instanceof XFAObject||super[Mr](e)}[Zs](){"string"==typeof this[Os]&&(this[Os]=this[Os].replaceAll("\r\n","\n"))}[ar](){return"string"==typeof this[Os]?this[Os].split(/[\u2029\u2028\n]/).reduce(((e,t)=>{t&&e.push(t);return e}),[]).join("\n"):this[Os][Pr]()}[jr](e){if("string"==typeof this[Os]){const e=valueToHtml(this[Os]).html;if(this[Os].includes("\u2029")){e.name="div";e.children=[];this[Os].split("\u2029").map((e=>e.split(/[\u2028\n]/).reduce(((e,t)=>{e.push({name:"span",value:t},{name:"br"});return e}),[]))).forEach((t=>{e.children.push({name:"p",children:t})}))}else if(/[\u2028\n]/.test(this[Os])){e.name="div";e.children=[];this[Os].split(/[\u2028\n]/).forEach((t=>{e.children.push({name:"span",value:t},{name:"br"})}))}return HTMLResult.success(e)}return this[Os][jr](e)}}class TextEdit extends XFAObject{constructor(e){super(Nn,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[jr](e){const t=toStyle(this,"border","font","margin");let i;const a=this[Ir]()[Ir]();""===this.multiLine&&(this.multiLine=a instanceof Draw?1:0);i=1===this.multiLine?{name:"textarea",attributes:{dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:a[Ws]?.[Vr]||a[Vr],fieldId:a[Vr],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){i.attributes["aria-required"]=!0;i.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class Time extends StringObject{constructor(e){super(Nn,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Zs](){const e=this[Os].trim();this[Os]=e?new Date(e):null}[jr](e){return valueToHtml(this[Os]?this[Os].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Nn,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Nn,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Nn,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Nn,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Dr](){return!1}}class Ui extends XFAObject{constructor(e){super(Nn,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[ar](){if(void 0===this[Xs]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Xs]=t;return t}}this[Xs]=null}return this[Xs]}[jr](e){const t=this[ar]();return t?t[jr](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Nn,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Nn,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[qr](e){const t=this[Ir]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[Hs](this.image)}this.image[Os]=e[Os];return}const i=e[kr];if(null===this[i]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Hr](t)}}this[e[kr]]=e;this[Hs](e)}else this[i][Os]=e[Os]}[Pr](){if(this.exData)return"string"==typeof this.exData[Os]?this.exData[Os].trim():this.exData[Os][Pr]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Os]||"").toString().trim()}return null}[jr](e){for(const t of Object.getOwnPropertyNames(this)){const i=this[t];if(i instanceof XFAObject)return i[jr](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Nn,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Dr](){return!0}}class TemplateNamespace{static[zr](e,t){if(TemplateNamespace.hasOwnProperty(e)){const i=TemplateNamespace[e](t);i[Tr](t);return i}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Ln=_r.datasets.id;function createText(e){const t=new Text({});t[Os]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(_r.datasets.id,"data");this.emptyMerge=0===this.data[rr]().length;this.root.form=this.form=e.template[Ts]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,i){e[Ws]=t;if(e[hr]())if(t[fr]()){const i=t[ir]();e[qr](createText(i))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const i=t[rr]().map((e=>e[Os].trim())).join("\n");e[qr](createText(i))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[fr]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,i,a){if(!e)return null;let s,r;for(let a=0;a<3;a++){s=i[sr](e,!1,!0);for(;;){r=s.next().value;if(!r)break;if(t===r[fr]())return r}if(i[Sr]===_r.datasets.id&&"data"===i[kr])break;i=i[Ir]()}if(!a)return null;s=this.data[sr](e,!0,!1);r=s.next().value;if(r)return r;s=this.data[zs](e,!0);r=s.next().value;return r?.[fr]()?r:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:i,target:a,connection:s}of e.setProperty.children){if(s)continue;if(!i)continue;const r=searchNode(this.root,t,i,!1,!1);if(!r){warn(`XFA - Invalid reference: ${i}.`);continue}const[n]=r;if(!n[pr](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const g=searchNode(this.root,e,a,!1,!1);if(!g){warn(`XFA - Invalid target: ${a}.`);continue}const[o]=g;if(!o[pr](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const c=o[Ir]();if(o instanceof SetProperty||c instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(o instanceof BindItems||c instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const C=n[Pr](),h=o[kr];if(o instanceof XFAAttribute){const e=Object.create(null);e[h]=C;const t=Reflect.construct(Object.getPrototypeOf(c).constructor,[e]);c[h]=t[h]}else if(o.hasOwnProperty(Os)){o[Ws]=n;o[Os]=C;o[Zs]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Hr](t);e.items.clear();const i=new Items({}),a=new Items({});e[Hs](i);e.items.push(i);e[Hs](a);e.items.push(a);for(const{ref:s,labelRef:r,valueRef:n,connection:g}of e.bindItems.children){if(g)continue;if(!s)continue;const e=searchNode(this.root,t,s,!1,!1);if(e)for(const t of e){if(!t[pr](this.datasets)){warn(`XFA - Invalid ref (${s}): must be a datasets child.`);continue}const e=searchNode(this.root,t,r,!0,!1);if(!e){warn(`XFA - Invalid label: ${r}.`);continue}const[g]=e;if(!g[pr](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const o=searchNode(this.root,t,n,!0,!1);if(!o){warn(`XFA - Invalid value: ${n}.`);continue}const[c]=o;if(!c[pr](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const C=createText(g[Pr]()),h=createText(c[Pr]());i[Hs](C);i.text.push(C);a[Hs](h);a.text.push(h)}else warn(`XFA - Invalid reference: ${s}.`)}}_bindOccurrences(e,t,i){let a;if(t.length>1){a=e[Ts]();a[Hr](a.occur);a.occur=null}this._bindValue(e,t[0],i);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const s=e[Ir](),r=e[kr],n=s[Qr](e);for(let e=1,g=t.length;et.name===e.name)).length:i[a].children.length;const r=i[Qr](e)+1,n=t.initial-s;if(n){const t=e[Ts]();t[Hr](t.occur);t.occur=null;i[a].push(t);i[Er](r,t);for(let e=1;e0)this._bindOccurrences(a,[e[0]],null);else if(this.emptyMerge){const e=t[Sr]===Ln?-1:t[Sr],i=a[Ws]=new XmlObject(e,a.name||"root");t[Hs](i);this._bindElement(a,i)}continue}if(!a[dr]())continue;let e=!1,s=null,r=null,n=null;if(a.bind){switch(a.bind.match){case"none":this._setAndBind(a,t);continue;case"global":e=!0;break;case"dataRef":if(!a.bind.ref){warn(`XFA - ref is empty in node ${a[kr]}.`);this._setAndBind(a,t);continue}r=a.bind.ref}a.bind.picture&&(s=a.bind.picture[Os])}const[g,o]=this._getOccurInfo(a);if(r){n=searchNode(this.root,t,r,!0,!1);if(null===n){n=createDataNode(this.data,t,r);if(!n)continue;this._isConsumeData()&&(n[qs]=!0);this._setAndBind(a,n);continue}this._isConsumeData()&&(n=n.filter((e=>!e[qs])));n.length>o?n=n.slice(0,o):0===n.length&&(n=null);n&&this._isConsumeData()&&n.forEach((e=>{e[qs]=!0}))}else{if(!a.name){this._setAndBind(a,t);continue}if(this._isConsumeData()){const i=[];for(;i.length0?i:null}else{n=t[sr](a.name,!1,this.emptyMerge).next().value;if(!n){if(0===g){i.push(a);continue}const e=t[Sr]===Ln?-1:t[Sr];n=a[Ws]=new XmlObject(e,a.name);this.emptyMerge&&(n[qs]=!0);t[Hs](n);this._setAndBind(a,n);continue}this.emptyMerge&&(n[qs]=!0);n=[n]}}n?this._bindOccurrences(a,n,s):g>0?this._setAndBind(a,t):i.push(a)}i.forEach((e=>e[Ir]()[Hr](e)))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[rr]()]];for(;t.length>0;){const i=t.at(-1),[a,s]=i;if(a+1===s.length){t.pop();continue}const r=s[++i[0]],n=e.get(r[Vr]);if(n)r[qr](n);else{const t=r[_s]();for(const i of t.values()){const t=e.get(i[Vr]);if(t){i[qr](t);break}}}const g=r[rr]();g.length>0&&t.push([-1,g])}const i=[''];if(this.dataset)for(const e of this.dataset[rr]())"data"!==e[kr]&&e[Xr](i);this.data[Xr](i);i.push("");return i.join("")}}const Hn=_r.config.id;class Acrobat extends XFAObject{constructor(e){super(Hn,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(Hn,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(Hn,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(Hn,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(Hn,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(Hn,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(Hn,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(Hn,"adobeExtensionLevel",0,(e=>e>=1&&e<=8))}}class Agent extends XFAObject{constructor(e){super(Hn,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(Hn,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(Hn,"amd")}}class config_Area extends XFAObject{constructor(e){super(Hn,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(Hn,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(Hn,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(Hn,"base")}}class BatchOutput extends XFAObject{constructor(e){super(Hn,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(Hn,"behaviorOverride")}[Zs](){this[Os]=new Map(this[Os].trim().split(/\s+/).filter((e=>e.includes(":"))).map((e=>e.split(":",2))))}}class Cache extends XFAObject{constructor(e){super(Hn,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(Hn,"change")}}class Common extends XFAObject{constructor(e){super(Hn,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(Hn,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(Hn,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(Hn,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(Hn,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(Hn,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(Hn,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(Hn,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(Hn,"copies",1,(e=>e>=1))}}class Creator extends StringObject{constructor(e){super(Hn,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(Hn,"currentPage",0,(e=>e>=0))}}class Data extends XFAObject{constructor(e){super(Hn,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(Hn,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(Hn,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(Hn,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(Hn,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(Hn,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(Hn,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(Hn,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(Hn,"embed")}}class config_Encrypt extends Option01{constructor(e){super(Hn,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(Hn,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(Hn,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(Hn,"enforce")}}class Equate extends XFAObject{constructor(e){super(Hn,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(Hn,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,i=this._unicodeRange;for(let a of i.split(",").map((e=>e.trim())).filter((e=>!!e))){a=a.split("-",2).map((e=>{const i=e.match(t);return i?parseInt(i[1],16):0}));1===a.length&&a.push(a[0]);e.push(a)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(Hn,"exclude")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e)))}}class ExcludeNS extends StringObject{constructor(e){super(Hn,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(Hn,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(Hn,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(Hn,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(Hn,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(Hn,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(Hn,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(Hn,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(Hn,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(Hn,"interactive")}}class Jog extends OptionObject{constructor(e){super(Hn,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(Hn,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(Hn,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(Hn,"level",0,(e=>e>0))}}class Linearized extends Option01{constructor(e){super(Hn,"linearized")}}class Locale extends StringObject{constructor(e){super(Hn,"locale")}}class LocaleSet extends StringObject{constructor(e){super(Hn,"localeSet")}}class Log extends XFAObject{constructor(e){super(Hn,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(Hn,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(Hn,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(Hn,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(Hn,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(Hn,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(Hn,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(Hn,"msgId",1,(e=>e>=1))}}class NameAttr extends StringObject{constructor(e){super(Hn,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(Hn,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(Hn,"numberOfCopies",null,(e=>e>=2&&e<=5))}}class OpenAction extends XFAObject{constructor(e){super(Hn,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(Hn,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(Hn,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(Hn,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(Hn,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(Hn,"packets")}[Zs](){"*"!==this[Os]&&(this[Os]=this[Os].trim().split(/\s+/).filter((e=>["config","datasets","template","xfdf","xslt"].includes(e))))}}class PageOffset extends XFAObject{constructor(e){super(Hn,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(Hn,"pageRange")}[Zs](){const e=this[Os].trim().split(/\s+/).map((e=>parseInt(e,10))),t=[];for(let i=0,a=e.length;i!1))}}class Pcl extends XFAObject{constructor(e){super(Hn,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(Hn,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(Hn,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(Hn,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(Hn,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(Hn,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(Hn,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(Hn,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(Hn,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(Hn,"print")}}class PrintHighQuality extends Option01{constructor(e){super(Hn,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(Hn,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(Hn,"printerName")}}class Producer extends StringObject{constructor(e){super(Hn,"producer")}}class Ps extends XFAObject{constructor(e){super(Hn,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(Hn,"range")}[Zs](){this[Os]=this[Os].trim().split(/\s*,\s*/,2).map((e=>e.split("-").map((e=>parseInt(e.trim(),10))))).filter((e=>e.every((e=>!isNaN(e))))).map((e=>{1===e.length&&e.push(e[0]);return e}))}}class Record extends ContentObject{constructor(e){super(Hn,"record")}[Zs](){this[Os]=this[Os].trim();const e=parseInt(this[Os],10);!isNaN(e)&&e>=0&&(this[Os]=e)}}class Relevant extends ContentObject{constructor(e){super(Hn,"relevant")}[Zs](){this[Os]=this[Os].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(Hn,"rename")}[Zs](){this[Os]=this[Os].trim();(this[Os].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Os]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(Hn,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(Hn,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(Hn,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(Hn,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(Hn,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(Hn,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(Hn,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(Hn,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(Hn,"startPage",0,(e=>!0))}}class SubmitFormat extends OptionObject{constructor(e){super(Hn,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(Hn,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(Hn,"subsetBelow",100,(e=>e>=0&&e<=100))}}class SuppressBanner extends Option01{constructor(e){super(Hn,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(Hn,"tagged")}}class config_Template extends XFAObject{constructor(e){super(Hn,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(Hn,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(Hn,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(Hn,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(Hn,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(Hn,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(Hn,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(Hn,"uri")}}class config_Validate extends OptionObject{constructor(e){super(Hn,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(Hn,"validateApprovalSignatures")}[Zs](){this[Os]=this[Os].trim().split(/\s+/).filter((e=>["docReady","postSign"].includes(e)))}}class ValidationMessaging extends OptionObject{constructor(e){super(Hn,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(Hn,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(Hn,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(Hn,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(Hn,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(Hn,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(Hn,"window")}[Zs](){const e=this[Os].trim().split(/\s*,\s*/,2).map((e=>parseInt(e,10)));if(e.some((e=>isNaN(e))))this[Os]=[0,0];else{1===e.length&&e.push(e[0]);this[Os]=e}}}class Xdc extends XFAObject{constructor(e){super(Hn,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(Hn,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(Hn,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(Hn,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[zr](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Jn=_r.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Jn,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Jn,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Jn,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Jn,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Jn,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Jn,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Jn,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Jn,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Jn,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Jn,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Jn,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[zr](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Yn=_r.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Yn,"data",e)}[mr](){return!0}}class Datasets extends XFAObject{constructor(e){super(Yn,"datasets",!0);this.data=null;this.Signature=null}[Nr](e){const t=e[kr];("data"===t&&e[Sr]===Yn||"Signature"===t&&e[Sr]===_r.signature.id)&&(this[t]=e);this[Hs](e)}}class DatasetsNamespace{static[zr](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const vn=_r.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(vn,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(vn,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(vn,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(vn,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(vn,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(vn,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(vn,"day")}}class DayNames extends XFAObject{constructor(e){super(vn,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(vn,"era")}}class EraNames extends XFAObject{constructor(e){super(vn,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(vn,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(vn,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(vn,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(vn,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(vn,"month")}}class MonthNames extends XFAObject{constructor(e){super(vn,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(vn,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(vn,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(vn,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(vn,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(vn,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(vn,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(vn,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(vn,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[zr](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const Kn=_r.signature.id;class signature_Signature extends XFAObject{constructor(e){super(Kn,"signature",!0)}}class SignatureNamespace{static[zr](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const Tn=_r.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(Tn,"stylesheet",!0)}}class StylesheetNamespace{static[zr](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const qn=_r.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(qn,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Gr](e){const t=_r[e[kr]];return t&&e[Sr]===t.id}}class XdpNamespace{static[zr](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const On=_r.xhtml.id,Pn=Symbol(),Wn=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),jn=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Xn=/\s+/g,Zn=/[\r\n]+/g,Vn=/\r\n?/g;function mapStyle(e,t,i){const a=Object.create(null);if(!e)return a;const s=Object.create(null);for(const[t,i]of e.split(";").map((e=>e.split(":",2)))){const e=jn.get(t);if(""===e)continue;let r=i;e&&(r="string"==typeof e?e:e(i,s));t.endsWith("scale")?a.transform=a.transform?`${a[t]} ${r}`:r:a[t.replaceAll(/-([a-zA-Z])/g,((e,t)=>t.toUpperCase()))]=r}a.fontFamily&&setFontFamily({typeface:a.fontFamily,weight:a.fontWeight||"normal",posture:a.fontStyle||"normal",size:s.fontSize||0},t,t[Cr].fontFinder,a);if(i&&a.verticalAlign&&"0px"!==a.verticalAlign&&a.fontSize){const e=.583,t=.333,i=getMeasurement(a.fontSize);a.fontSize=measureToString(i*e);a.verticalAlign=measureToString(Math.sign(getMeasurement(a.verticalAlign))*i*t)}i&&a.fontSize&&(a.fontSize=`calc(${a.fontSize} * var(--scale-factor))`);fixTextIndent(a);return a}const zn=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(On,t);this[Pn]=!1;this.style=e.style||""}[Ys](e){super[Ys](e);this.style=function checkStyle(e){return e.style?e.style.trim().split(/\s*;\s*/).filter((e=>!!e)).map((e=>e.split(/\s*:\s*/,2))).filter((([t,i])=>{"font-family"===t&&e[Cr].usedTypefaces.add(i);return Wn.has(t)})).map((e=>e.join(":"))).join(";"):""}(this)}[xs](){return!zn.has(this[kr])}[Mr](e,t=!1){if(t)this[Pn]=!0;else{e=e.replaceAll(Zn,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Xn," "))}e&&(this[Os]+=e)}[Ur](e,t=!0){const i=Object.create(null),a={top:NaN,bottom:NaN,left:NaN,right:NaN};let s=null;for(const[e,t]of this.style.split(";").map((e=>e.split(":",2))))switch(e){case"font-family":i.typeface=stripQuotes(t);break;case"font-size":i.size=getMeasurement(t);break;case"font-weight":i.weight=t;break;case"font-style":i.posture=t;break;case"letter-spacing":i.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map((e=>getMeasurement(e)));switch(e.length){case 1:a.top=a.bottom=a.left=a.right=e[0];break;case 2:a.top=a.bottom=e[0];a.left=a.right=e[1];break;case 3:a.top=e[0];a.bottom=e[2];a.left=a.right=e[1];break;case 4:a.top=e[0];a.left=e[1];a.bottom=e[2];a.right=e[3]}break;case"margin-top":a.top=getMeasurement(t);break;case"margin-bottom":a.bottom=getMeasurement(t);break;case"margin-left":a.left=getMeasurement(t);break;case"margin-right":a.right=getMeasurement(t);break;case"line-height":s=getMeasurement(t)}e.pushData(i,a,s);if(this[Os])e.addString(this[Os]);else for(const t of this[rr]())"#text"!==t[kr]?t[Ur](e):e.addString(t[Os]);t&&e.popFont()}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length&&!this[Os])return HTMLResult.EMPTY;let i;i=this[Pn]?this[Os]?this[Os].replaceAll(Vn,"\n"):void 0:this[Os]||void 0;return HTMLResult.success({name:this[kr],attributes:{href:this.href,style:mapStyle(this.style,this,this[Pn])},children:t,value:i})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Ur](e){e.pushFont({weight:"bold"});super[Ur](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[jr](e){const t=super[jr](e),{html:i}=t;if(!i)return HTMLResult.EMPTY;i.name="div";i.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[Pr](){return"\n"}[Ur](e){e.addString("\n")}[jr](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[jr](e){const t=[];this[Xs]={children:t};this[Js]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Os]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Ur](e){e.pushFont({posture:"italic"});super[Ur](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Ur](e){super[Ur](e,!1);e.addString("\n");e.addPara();e.popFont()}[Pr](){return this[Ir]()[rr]().at(-1)===this?super[Pr]():super[Pr]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[zr](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const _n={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[zr](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[lr]=e}[Nr](e){this.element=e;return!0}[Zs](){super[Zs]();if(this.element.template instanceof Template){this[lr].set(Jr,this.element);this.element.template[Yr](this[lr]);this.element.template[lr]=this[lr]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Nr](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(_r).map((({id:e})=>e)));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:i,namespace:a,prefixes:s}){const r=null!==a;if(r){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(a)}s&&this._addNamespacePrefix(s);if(i.hasOwnProperty(Rr)){const e=_n.datasets,t=i[Rr];let a=null;for(const[i,s]of Object.entries(t)){if(this._getNamespaceToUse(i)===e){a={xfa:s};break}}a?i[Rr]=a:delete i[Rr]}const n=this._getNamespaceToUse(e),g=n?.[zr](t,i)||new Empty;g[mr]()&&this._nsAgnosticLevel++;(r||s||g[mr]())&&(g[Ks]={hasNamespace:r,prefixes:s,nsAgnostic:g[mr]()});return g}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[i,{check:a}]of Object.entries(_r))if(a(e)){t=_n[i];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:i}of e){const e=this._searchNamespace(i);let a=this._namespacePrefixes.get(t);if(!a){a=[];this._namespacePrefixes.set(t,a)}a.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:i,nsAgnostic:a}=e;t&&(this._currentNamespace=this._namespaceStack.pop());i&&i.forEach((({prefix:e})=>{this._namespacePrefixes.get(e).pop()}));a&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=ys;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===ys){this._current[Zs]();return this._current.element}}onText(e){e=e.replace(this._nbsps,(e=>e.slice(1)+" "));this._richText||this._current[xs]()?this._current[Mr](e,this._richText):this._whiteRegex.test(e)||this._current[Mr](e.trim())}onCdata(e){this._current[Mr](e)}_mkAttributes(e,t){let i=null,a=null;const s=Object.create({});for(const{name:r,value:n}of e)if("xmlns"===r)i?warn(`XFA - multiple namespace definition in <${t}>`):i=n;else if(r.startsWith("xmlns:")){const e=r.substring(6);a||(a=[]);a.push({prefix:e,value:n})}else{const e=r.indexOf(":");if(-1===e)s[r]=n;else{let t=s[Rr];t||(t=s[Rr]=Object.create(null));const[i,a]=[r.slice(0,e),r.slice(e+1)];(t[i]||=Object.create(null))[a]=n}}return[i,a,s]}_getNameAndPrefix(e,t){const i=e.indexOf(":");return-1===i?[e,null]:[e.substring(i+1),t?"":e.substring(0,i)]}onBeginElement(e,t,i){const[a,s,r]=this._mkAttributes(t,e),[n,g]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),o=this._builder.build({nsPrefix:g,name:n,attributes:r,namespace:a,prefixes:s});o[Cr]=this._globalData;if(i){o[Zs]();this._current[Nr](o)&&o[Kr](this._ids);o[Ys](this._builder)}else{this._stack.push(this._current);this._current=o}}onEndElement(e){const t=this._current;if(t[ur]()&&"string"==typeof t[Os]){const e=new XFAParser;e._globalData=this._globalData;const i=e.parse(t[Os]);t[Os]=null;t[Nr](i)}t[Zs]();this._current=this._stack.pop();this._current[Nr](t)&&t[Kr](this._ids);t[Ys](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[Cr].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const e=this.form[Wr]();return new Promise(((t,i)=>{const nextIteration=()=>{try{const i=e.next();i.done?t(i.value):setTimeout(nextIteration,0)}catch(e){i(e)}};setTimeout(nextIteration,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map((e=>{const{width:t,height:i}=e.attributes.style;return[0,0,parseInt(t),parseInt(i)]}))}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[Cr].images=e}setFonts(e){this.form[Cr].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[Cr].usedTypefaces){e=stripQuotes(e);this.form[Cr].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[Cr].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[kr])){const e=XhtmlNamespace.body({});e[Hs](t);t=e}const i=t[jr]();if(!i.success)return null;const{html:a}=i,{attributes:s}=a;if(s){s.class&&(s.class=s.class.filter((e=>!e.startsWith("xfa"))));s.dir="auto"}return{html:a,str:t[Pr]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments")]).then((([t,i,a,s,r])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:i,structTreeRoot:a,baseUrl:s,attachments:r})),(e=>{warn(`createGlobals: "${e}".`);return null}))}static async create(e,t,i,a,s,r,n){const g=s?await this._getPageIndex(e,t,i.pdfManager):null;return i.pdfManager.ensure(this,"_create",[e,t,i,a,s,r,g,n])}static _create(e,t,i,a,s=!1,r=null,n=null,g=null){const o=e.fetchIfRef(t);if(!(o instanceof Dict))return;const{acroForm:c,pdfManager:C}=i,h=t instanceof Ref?t.toString():`annot_${a.createObjId()}`;let l=o.get("Subtype");l=l instanceof Name?l.name:null;const Q={xref:e,ref:t,dict:o,subtype:l,id:h,annotationGlobals:i,collectFields:s,orphanFields:r,needAppearances:!s&&!0===c.get("NeedAppearances"),pageIndex:n,evaluatorOptions:C.evaluatorOptions,pageRef:g};switch(l){case"Link":return new LinkAnnotation(Q);case"Text":return new TextAnnotation(Q);case"Widget":let e=getInheritableProperty({dict:o,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(Q);case"Btn":return new ButtonWidgetAnnotation(Q);case"Ch":return new ChoiceWidgetAnnotation(Q);case"Sig":return new SignatureWidgetAnnotation(Q)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(Q);case"Popup":return new PopupAnnotation(Q);case"FreeText":return new FreeTextAnnotation(Q);case"Line":return new LineAnnotation(Q);case"Square":return new SquareAnnotation(Q);case"Circle":return new CircleAnnotation(Q);case"PolyLine":return new PolylineAnnotation(Q);case"Polygon":return new PolygonAnnotation(Q);case"Caret":return new CaretAnnotation(Q);case"Ink":return new InkAnnotation(Q);case"Highlight":return new HighlightAnnotation(Q);case"Underline":return new UnderlineAnnotation(Q);case"Squiggly":return new SquigglyAnnotation(Q);case"StrikeOut":return new StrikeOutAnnotation(Q);case"Stamp":return new StampAnnotation(Q);case"FileAttachment":return new FileAttachmentAnnotation(Q);default:s||warn(l?`Unimplemented annotation type "${l}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(Q)}}static async _getPageIndex(e,t,i){try{const a=await e.fetchIfRefAsync(t);if(!(a instanceof Dict))return-1;const s=a.getRaw("P");if(s instanceof Ref)try{return await i.ensureCatalog("getPageIndex",[s])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(a.has("Kids"))return-1;const r=await i.ensureDoc("numPages");for(let e=0;ee/255))}function getQuadPoints(e,t){const i=e.getArray("QuadPoints");if(!isNumberArray(i,null)||0===i.length||i.length%8>0)return null;const a=new Float32Array(i.length);for(let e=0,s=i.length;et[2]||Et[3]))return null;a.set([l,u,Q,u,l,E,Q,E],e)}return a}function getTransformMatrix(e,t,i){const[a,s,r,n]=Util.getAxialAlignedBoundingBox(t,i);if(a===r||s===n)return[1,0,0,1,e[0],e[1]];const g=(e[2]-e[0])/(r-a),o=(e[3]-e[1])/(n-s);return[g,0,0,o,e[0]-a*g,e[1]-s*o]}class Annotation{constructor(e){const{dict:t,xref:i,annotationGlobals:a,ref:s,orphanFields:r}=e,n=r?.get(s);n&&t.set("Parent",n);this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const g=t.get("MK");this.setBorderAndBackgroundColors(g);this.setRotation(g,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const o=!!(this.flags&eA),c=!!(this.flags&tA);this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&$),noHTML:o&&c,isEditable:!1,structParent:-1};if(a.structTreeRoot){let i=t.get("StructParent");this.data.structParent=i=Number.isInteger(i)&&i>=0?i:-1;a.structTreeRoot.addAnnotationIdToPage(e.pageRef,i)}if(e.collectFields){const a=t.get("Kids");if(Array.isArray(a)){const e=[];for(const t of a)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(i,t,dA);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}const C=t.get("IT");C instanceof Name&&(this.data.it=C.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:i}=this;if(void 0===e){if(void 0===t)return;return t?i&~_:i&~z|_}if(e){i|=_;return t?i&~AA|z:i&~z|AA}i&=~(z|AA);return t?i&~_:i|_}_isViewable(e){return!this._hasFlag(e,V)&&!this._hasFlag(e,AA)}_isPrintable(e){return this._hasFlag(e,_)&&!this._hasFlag(e,z)&&!this._hasFlag(e,V)}mustBeViewed(e,t){const i=e?.get(this.data.id)?.noView;return void 0!==i?!i:this.viewable&&!this._hasFlag(this.flags,z)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:i}=e,a=getInheritableProperty({dict:t,key:"DA"})||i.acroForm.get("DA");this._defaultAppearance="string"==typeof a?a:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&V&&"Annotation"!==this.constructor.name&&(this.flags^=V)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const i=e[t];if(i instanceof Name)switch(i.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=i.name;continue}warn(`Ignoring invalid lineEnding: ${i}`)}}setRotation(e,t){this.rotation=0;let i=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(i)&&0!==i){i%=360;i<0&&(i+=360);i%90==0&&(this.rotation=i)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(i instanceof BaseStream){this.appearance=i;return}if(!(i instanceof Dict))return;const a=e.get("AS");if(!(a instanceof Name&&i.has(a.name)))return;const s=i.get(a.name);s instanceof BaseStream&&(this.appearance=s)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}loadResources(e,t){return t.dict.getAsync("Resources").then((t=>{if(!t)return;return new ObjectLoader(t,e,t.xref).load().then((function(){return t}))}))}async getOperatorList(e,t,a,s){const{hasOwnCanvas:r,id:n,rect:g}=this.data;let c=this.appearance;const C=!!(r&&a&o);if(C&&(g[0]===g[2]||g[1]===g[3])){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!c){if(!C)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};c=new StringStream("");c.dict=new Dict}const h=c.dict,l=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],c),Q=lookupRect(h.getArray("BBox"),[0,0,1,1]),E=lookupMatrix(h.getArray("Matrix"),i),u=getTransformMatrix(g,Q,E),d=new OperatorList;let f;this.oc&&(f=await e.parseMarkedContentProps(this.oc,null));void 0!==f&&d.addOp(Ye,["OC",f]);d.addOp(je,[n,g,u,E,C]);await e.getOperatorList({stream:c,task:t,resources:l,operatorList:d,fallbackFontDict:this._fallbackFontDict});d.addOp(Xe,[]);void 0!==f&&d.addOp(ve,[]);this.reset();return{opList:d,separateForm:!1,separateCanvas:C}}async save(e,t,i,a){return null}get hasTextContent(){return!1}async extractTextContent(e,t,i){if(!this.appearance)return;const a=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),s=[],r=[];let n=null;const g={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){n||=t.transform.slice(-2);r.push(t.str);if(t.hasEOL){s.push(r.join("").trimEnd());r.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:a,includeMarkedContent:!0,keepWhiteSpace:!0,sink:g,viewBox:i});this.reset();r.length&&s.push(r.join("").trimEnd());if(s.length>1||s[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),i=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(n,t,i);this.data.textContent=s}}_transformPoint(e,t,i){const{rect:a}=this.data;t||=[0,0,1,1];i||=[1,0,0,1,0,0];const s=getTransformMatrix(a,t,i);s[4]-=a[0];s[5]-=a[1];e=Util.applyTransform(e,s);return Util.applyTransform(e,i)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let i=e;const a=new RefSet;e.objId&&a.put(e.objId);for(;i.has("Parent");){i=i.get("Parent");if(!(i instanceof Dict)||i.objId&&a.has(i.objId))break;i.objId&&a.put(i.objId);i.has("T")&&t.unshift(stringToPDFString(i.get("T")))}return t.join(".")}}class AnnotationBorderStyle{constructor(){this.width=1;this.rawWidth=1;this.style=lA;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const i=(t[2]-t[0])/2,a=(t[3]-t[1])/2;if(i>0&&a>0&&(e>i||e>a)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=lA;break;case"D":this.style=BA;break;case"B":this.style=QA;break;case"I":this.style=EA;break;case"U":this.style=uA}}setDashArray(e,t=!1){if(Array.isArray(e)){let i=!0,a=!0;for(const t of e){if(!(+t>=0)){i=!1;break}t>0&&(a=!1)}if(0===e.length||i&&!a){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const i=t.get("RT");this.data.replyType=i instanceof Name?i.name:Z}let i=null;if(this.data.replyType===X){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;i=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;i=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=i instanceof Ref?i.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:i,fillColor:a,blendMode:s,strokeAlpha:r,fillAlpha:n,pointsCallback:g}){let o=Number.MAX_VALUE,c=Number.MAX_VALUE,C=Number.MIN_VALUE,h=Number.MIN_VALUE;const l=["q"];t&&l.push(t);i&&l.push(`${i[0]} ${i[1]} ${i[2]} RG`);a&&l.push(`${a[0]} ${a[1]} ${a[2]} rg`);const Q=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=Q.length;e"string"==typeof e)).map((e=>stringToPDFString(e))):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,AA)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(0===t)return i;return getRotationMatrix(t,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=0===t||180===t?`0 0 ${i} ${a} re`:`0 0 ${a} ${i} re`;let r="";this.backgroundColor&&(r=`${getPdfColor(this.backgroundColor,!0)} ${s} f `);if(this.borderColor){r+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${s} S `}return r}async getOperatorList(e,t,i,a){if(i&h&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,i,a);const s=await this._getAppearance(e,t,i,a);if(this.appearance&&null===s)return super.getOperatorList(e,t,i,a);const r=new OperatorList;if(!this._defaultAppearance||null===s)return{opList:r,separateForm:!1,separateCanvas:!1};const n=!!(this.data.hasOwnCanvas&&i&o),g=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],c=getTransformMatrix(this.data.rect,g,[1,0,0,1,0,0]);let C;this.oc&&(C=await e.parseMarkedContentProps(this.oc,null));void 0!==C&&r.addOp(Ye,["OC",C]);r.addOp(je,[this.data.id,this.data.rect,c,this.getRotationMatrix(a),n]);const l=new StringStream(s);await e.getOperatorList({stream:l,task:t,resources:this._fieldResources.mergedResources,operatorList:r});r.addOp(Xe,[]);void 0!==C&&r.addOp(ve,[]);return{opList:r,separateForm:!1,separateCanvas:n}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);this.borderColor&&t.set("BC",getPdfColorArray(this.borderColor));this.backgroundColor&&t.set("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,i,a){const{dict:s,ref:r}=function getParentToUpdate(e,t,i){const a=new RefSet,s=e,r={dict:null,ref:null};for(;e instanceof Dict&&!a.has(t);){a.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return r;e=i.fetch(t)}if(e instanceof Dict&&e!==s){r.dict=e;r.ref=t}return r}(e,this.ref,i);if(s){if(!a.has(r)){const e=s.clone();e.set("V",t);a.put(r,{data:e});return e}}else e.set("V",t);return null}async save(e,t,a,s){const r=a?.get(this.data.id),n=this._buildFlags(r?.noView,r?.noPrint);let g=r?.value,o=r?.rotation;if(g===this.data.fieldValue||void 0===g){if(!this._hasValueFromXFA&&void 0===o&&void 0===n)return;g||=this.data.fieldValue}if(void 0===o&&!this._hasValueFromXFA&&Array.isArray(g)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(g,this.data.fieldValue)&&void 0===n)return;void 0===o&&(o=this.rotation);let c=null;if(!this._needAppearances){c=await this._getAppearance(e,t,C,a);if(null===c&&void 0===n)return}let h=!1;if(c?.needAppearances){h=!0;c=null}const{xref:l}=e,Q=l.fetchIfRef(this.ref);if(!(Q instanceof Dict))return;const E=new Dict(l);for(const e of Q.getKeys())"AP"!==e&&E.set(e,Q.getRaw(e));if(void 0!==n){E.set("F",n);if(null===c&&!h){const e=Q.getRaw("AP");e&&E.set("AP",e)}}const u={path:this.data.fieldName,value:g},d=this.setValue(E,Array.isArray(g)?g.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(g),l,s);this.amendSavedDict(a,d||E);const f=this._getMKDict(o);f&&E.set("MK",f);s.put(this.ref,{data:E,xfa:u,needAppearances:h});if(null!==c){const e=l.getNewTemporaryRef(),t=new Dict(l);E.set("AP",t);t.set("N",e);const r=this._getSaveFieldResources(l),n=new StringStream(c),g=n.dict=new Dict(l);g.set("Subtype",Name.get("Form"));g.set("Resources",r);g.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const o=this.getRotationMatrix(a);o!==i&&g.set("Matrix",o);s.put(e,{data:n,xfa:null,needAppearances:!1})}E.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,i,a){if(this.hasFieldFlag(rA))return null;const s=a?.get(this.data.id);let r,g;if(s){r=s.formattedValue||s.value;g=s.rotation}if(void 0===g&&void 0===r&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const o=this.getBorderAndBackgroundAppearances(a);if(void 0===r){r=this.data.fieldValue;if(!r)return`/Tx BMC q ${o}Q EMC`}Array.isArray(r)&&1===r.length&&(r=r[0]);assert("string"==typeof r,"Expected `value` to be a string.");r=r.trimEnd();if(this.data.combo){const e=this.data.options.find((({exportValue:e})=>r===e));r=e?.displayValue||r}if(""===r)return`/Tx BMC q ${o}Q EMC`;void 0===g&&(g=this.rotation);let c,h=-1;if(this.data.multiLine){c=r.split(/\r\n?|\n/).map((e=>e.normalize("NFC")));h=c.length}else c=[r.replace(/\r\n?|\n/,"").normalize("NFC")];let l=this.data.rect[3]-this.data.rect[1],Q=this.data.rect[2]-this.data.rect[0];90!==g&&270!==g||([Q,l]=[l,Q]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let E,u,d,f=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const p=[];let m=!1;for(const e of c){const t=f.encodeString(e);t.length>1&&(m=!0);p.push(t.join(""))}if(m&&i&C)return{needAppearances:!0};if(m&&this._isOffscreenCanvasSupported){const i=this.data.comb?"monospace":"sans-serif",a=new FakeUnicodeFont(e.xref,i),s=a.createFontResources(c.join("")),n=s.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of n.getKeys())e.set(t,n.getRaw(t))}else this._fieldResources.mergedResources.set("Font",n);const g=a.fontName.name;f=await WidgetAnnotation._getFontData(e,t,{fontName:g,fontSize:0},s);for(let e=0,t=p.length;e2)return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 ${numberToString(2)} ${numberToString(b)} Tm (${escapeString(p[0])}) Tj ET Q EMC`;return`/Tx BMC q ${o}BT `+E+` 1 0 0 1 0 0 Tm ${this._renderText(p[0],f,u,Q,D,{shift:0},2,b)} ET Q EMC`}static async _getFontData(e,t,i,a){const s=new OperatorList,r={font:null,clone(){return this}},{fontName:n,fontSize:g}=i;await e.handleSetFont(a,[n&&Name.get(n),g],null,s,t,r,null);return r.font}_getTextWidth(e,t){return t.charsToGlyphs(e).reduce(((e,t)=>e+t.width),0)/1e3}_computeFontSize(e,t,i,a,r){let{fontSize:n}=this.data.defaultAppearanceData,g=(n||12)*s,o=Math.round(e/g);if(!n){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===r){const r=this._getTextWidth(i,a);n=roundWithTwoDigits(Math.min(e/s,t/r));o=1}else{const c=i.split(/\r\n?|\n/),C=[];for(const e of c){const t=a.encodeString(e).join(""),i=a.charsToGlyphs(t),s=a.getCharPositions(t);C.push({line:t,glyphs:i,positions:s})}const isTooBig=i=>{let s=0;for(const r of C){s+=this._splitLine(null,a,i,t,r).length*i;if(s>e)return!0}return!1};o=Math.max(o,r);for(;;){g=e/o;n=roundWithTwoDigits(g/s);if(!isTooBig(n))break;o++}}const{fontName:c,fontColor:C}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:i}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(i,!0)}`}({fontSize:n,fontName:c,fontColor:C})}return[this._defaultAppearance,n,e/o]}_renderText(e,t,i,a,s,r,n,g){let o;if(1===s){o=(a-this._getTextWidth(e,t)*i)/2}else if(2===s){o=a-this._getTextWidth(e,t)*i-n}else o=n;const c=numberToString(o-r.shift);r.shift=o;return`${c} ${g=numberToString(g)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:i,acroFormResources:a}=this._fieldResources,s=this.data.defaultAppearanceData?.fontName;if(!s)return t||Dict.empty;for(const e of[t,i])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(s))return e}if(a instanceof Dict){const i=a.get("Font");if(i instanceof Dict&&i.has(s)){const a=new Dict(e);a.set(s,i.getRaw(s));const r=new Dict(e);r.set("Font",a);return Dict.merge({xref:e,dictArray:[r,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=z;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let i=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(i)||i<0||i>2)&&(i=null);this.data.textAlignment=i;let a=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(a)||a<0)&&(a=0);this.data.maxLen=a;this.data.multiLine=this.hasFieldFlag(sA);this.data.comb=this.hasFieldFlag(hA)&&!this.hasFieldFlag(sA)&&!this.hasFieldFlag(rA)&&!this.hasFieldFlag(IA)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(CA)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,i,a,s,r,n,g,o,c,C){const h=s/this.data.maxLen,l=this.getBorderAndBackgroundAppearances(C),Q=[],E=t.getCharPositions(i);for(const[e,t]of E)Q.push(`(${escapeString(i.substring(e,t))}) Tj`);const u=Q.join(` ${numberToString(h)} 0 Td `);return`/Tx BMC q ${l}BT `+e+` 1 0 0 1 ${numberToString(n)} ${numberToString(g+o)} Tm ${u} ET Q EMC`}_getMultilineAppearance(e,t,i,a,s,r,n,g,o,c,C,h){const l=[],Q=s-2*g,E={shift:0};for(let e=0,r=t.length;ea){o.push(e.substring(l,i));l=i;Q=u;c=-1;h=-1}else{Q+=u;c=i;C=s;h=t}else if(Q+u>a)if(-1!==c){o.push(e.substring(l,C));l=C;t=h+1;c=-1;Q=0}else{o.push(e.substring(l,i));l=i;Q=u}else Q+=u}lt?`\\${t}`:"\\s+"));new RegExp(`^\\s*${r}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.hasFieldFlag(rA),charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;this.data.checkBox=!this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.radioButton=this.hasFieldFlag(nA)&&!this.hasFieldFlag(gA);this.data.pushButton=this.hasFieldFlag(gA);this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,a,s){if(this.data.pushButton)return super.getOperatorList(e,t,a,!1,s);let r=null,n=null;if(s){const e=s.get(this.data.id);r=e?e.value:null;n=e?e.rotation:null}if(null===r&&this.appearance)return super.getOperatorList(e,t,a,s);null==r&&(r=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const g=r?this.checkedAppearance:this.uncheckedAppearance;if(g){const r=this.appearance,o=lookupMatrix(g.dict.getArray("Matrix"),i);n&&g.dict.set("Matrix",this.getRotationMatrix(s));this.appearance=g;const c=super.getOperatorList(e,t,a,s);this.appearance=r;g.dict.set("Matrix",o);return c}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,i,a){this.data.checkBox?this._saveCheckbox(e,t,i,a):this.data.radioButton&&this._saveRadioButton(e,t,i,a)}async _saveCheckbox(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.exportValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===n&&(n=this.rotation);void 0===g&&(g=this.data.fieldValue===this.data.exportValue);const c={path:this.data.fieldName,value:g?this.data.exportValue:""},C=Name.get(g?this.data.exportValue:"Off");this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}async _saveRadioButton(e,t,i,a){if(!i)return;const s=i.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let n=s?.rotation,g=s?.value;if(void 0===n&&void 0===r){if(void 0===g)return;if(this.data.fieldValue===this.data.buttonValue===g)return}let o=e.xref.fetchIfRef(this.ref);if(!(o instanceof Dict))return;o=o.clone();void 0===g&&(g=this.data.fieldValue===this.data.buttonValue);void 0===n&&(n=this.rotation);const c={path:this.data.fieldName,value:g?this.data.buttonValue:""},C=Name.get(g?this.data.buttonValue:"Off");g&&this.setValue(o,C,e.xref,a);o.set("AS",C);o.set("M",`D:${getModificationDate()}`);void 0!==r&&o.set("F",r);const h=this._getMKDict(n);h&&o.set("MK",h);a.put(this.ref,{data:o,xfa:c,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],s=[0,0,i,a],r=.8*Math.min(i,a);let n,g;if("check"===t){n={width:.755*r,height:.705*r};g="3"}else if("disc"===t){n={width:.791*r,height:.705*r};g="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const o=`q BT /PdfJsZaDb ${r} Tf 0 g ${numberToString((i-n.width)/2)} ${numberToString((a-n.height)/2)} Td (${g}) Tj ET Q`,c=new Dict(e.xref);c.set("FormType",1);c.set("Subtype",Name.get("Form"));c.set("Type",Name.get("XObject"));c.set("BBox",s);c.set("Matrix",[1,0,0,1,0,0]);c.set("Length",o.length);const C=new Dict(e.xref),h=new Dict(e.xref);h.set("PdfJsZaDb",this.fallbackFontDict);C.set("Font",h);c.set("Resources",C);this.checkedAppearance=new StringStream(o);this.checkedAppearance.dict=c;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(!(i instanceof Dict))return;const a=this._decodeFormValue(e.dict.get("AS"));"string"==typeof a&&(this.data.fieldValue=a);const s=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",r=i.getKeys();if(0===r.length)r.push("Off",s);else if(1===r.length)"Off"===r[0]?r.push(s):r.unshift("Off");else if(r.includes(s)){r.length=0;r.push("Off",s)}else{const e=r.find((e=>"Off"!==e));r.length=0;r.push("Off",e)}r.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=r[1];const n=i.get(this.data.exportValue);this.checkedAppearance=n instanceof BaseStream?n:null;const g=i.get("Off");this.uncheckedAppearance=g instanceof BaseStream?g:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const i=t.get("V");i instanceof Name&&(this.data.fieldValue=this._decodeFormValue(i))}const i=e.dict.get("AP");if(!(i instanceof Dict))return;const a=i.get("N");if(!(a instanceof Dict))return;for(const e of a.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const s=a.get(this.data.buttonValue);this.checkedAppearance=s instanceof BaseStream?s:null;const r=a.get("Off");this.uncheckedAppearance=r instanceof BaseStream?r:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:i}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:i.baseUrl,docAttachments:i.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("ZapfDingbats"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("ZapfDingbatsEncoding"));return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const a=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(a))for(let e=0,t=a.length;e=0&&t0&&(this.data.options=this.data.fieldValue.map((e=>({exportValue:e,displayValue:e}))));this.data.combo=this.hasFieldFlag(oA);this.data.multiSelect=this.hasFieldFlag(cA);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let i=e?.get(this.data.id)?.value;Array.isArray(i)||(i=[i]);const a=[],{options:s}=this.data;for(let e=0,t=0,r=s.length;ei){i=a;t=e}}[Q,E]=this._computeFontSize(e,c-4,t,l,-1)}const u=E*s,d=(u-E)/2,f=Math.floor(o/u);let p=0;if(h.length>0){const e=Math.min(...h),t=Math.max(...h);p=Math.max(0,t-f+1);p>e&&(p=e)}const m=Math.min(p+f+1,C),y=["/Tx BMC q",`1 1 ${c} ${o} re W n`];if(h.length){y.push("0.600006 0.756866 0.854904 rg");for(const e of h)p<=e&&ee.trimEnd()));const{coords:e,bbox:t,matrix:i}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,a);this.data.textPosition=this._transformPoint(e,t,i)}if(this._isOffscreenCanvasSupported){const s=e.dict.get("CA"),r=new FakeUnicodeFont(i,"sans-serif");this.appearance=r.createAppearance(this._contents.str,this.rectangle,this.rotation,a,t,s);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,fontSize:r,oldAnnotation:n,rect:g,rotation:o,user:c,value:C}=e,h=n||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("FreeText"));if(n){h.set("M",`D:${getModificationDate()}`);h.delete("RC")}else h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);const l=`/Helv ${r} Tf ${getPdfColor(s,!0)}`;h.set("DA",l);h.set("Contents",stringToAsciiOrUTF16BE(C));h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);i?e.set("N",i):e.set("N",a)}return h}static async createNewAppearanceStream(e,t,i){const{baseFontRef:a,evaluator:r,task:n}=i,{color:g,fontSize:o,rect:c,rotation:C,value:h}=e,l=new Dict(t),Q=new Dict(t);if(a)Q.set("Helv",a);else{const e=new Dict(t);e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type1"));e.set("Encoding",Name.get("WinAnsiEncoding"));Q.set("Helv",e)}l.set("Font",Q);const E=await WidgetAnnotation._getFontData(r,n,{fontName:"Helv",fontSize:o},l),[u,d,f,p]=c;let m=f-u,y=p-d;C%180!=0&&([m,y]=[y,m]);const w=h.split("\n"),D=o/1e3;let b=-1/0;const F=[];for(let e of w){const t=E.encodeString(e);if(t.length>1)return null;e=t.join("");F.push(e);let i=0;const a=E.charsToGlyphs(e);for(const e of a)i+=e.width*D;b=Math.max(b,i)}let S=1;b>m&&(S=m/b);let k=1;const R=s*o,N=1*o,G=R*w.length;G>y&&(k=y/G);const M=o*Math.min(S,k);let U,x,L;switch(C){case 0:L=[1,0,0,1];x=[c[0],c[1],m,y];U=[c[0],c[3]-N];break;case 90:L=[0,1,-1,0];x=[c[1],-c[2],m,y];U=[c[1],-c[0]-N];break;case 180:L=[-1,0,0,-1];x=[-c[2],-c[3],m,y];U=[-c[2],-c[1]-N];break;case 270:L=[0,-1,1,0];x=[-c[3],c[0],m,y];U=[-c[3],c[2]-N]}const H=["q",`${L.join(" ")} 0 0 cm`,`${x.join(" ")} re W n`,"BT",`${getPdfColor(g,!0)}`,`0 Tc /Helv ${numberToString(M)} Tf`];H.push(`${U.join(" ")} Td (${escapeString(F[0])}) Tj`);const J=numberToString(R);for(let e=1,t=F.length;e{e.push(`${a[0]} ${a[1]} m`,`${a[2]} ${a[3]} l`,"S");return[t[0]-o,t[2]+o,t[7]-o,t[3]+o]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=M;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[4]+this.borderStyle.width/2,a=t[5]+this.borderStyle.width/2,s=t[6]-t[4]-this.borderStyle.width,n=t[3]-t[7]-this.borderStyle.width;e.push(`${i} ${a} ${s} ${n} re`);r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=U;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=getRgbColor(t.getArray("IC"),null),r=s?getPdfColorArray(s):null,n=r?a:null;if(0===this.borderStyle.width&&!r)return;const g=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:r,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[0]+this.borderStyle.width/2,a=t[1]-this.borderStyle.width/2,s=t[6]-this.borderStyle.width/2,n=t[7]+this.borderStyle.width/2,o=i+(s-i)/2,c=a+(n-a)/2,C=(s-i)/2*g,h=(n-a)/2*g;e.push(`${o} ${n} m`,`${o+C} ${n} ${s} ${c+h} ${s} ${c} c`,`${s} ${c-h} ${o+C} ${a} ${o} ${a} c`,`${o-C} ${a} ${i} ${c-h} ${i} ${c} c`,`${i} ${c+h} ${o-C} ${n} ${o} ${n} c`,"h");r?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=L;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const a=t.getArray("Vertices");if(!isNumberArray(a,null))return;const s=this.data.vertices=Float32Array.from(a);if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),r=this.borderStyle.width||1,n=2*r,g=[1/0,1/0,-1/0,-1/0];for(let e=0,t=s.length;e{for(let t=0,i=s.length;t{for(const t of this.data.inkLists){for(let i=0,a=t.length;ie/255)));Q.set("CA",n);const u=new Dict(t);Q.set("AP",u);i?u.set("N",i):u.set("N",a);return Q}static async createNewAppearanceStream(e,t,i){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,i);const{color:a,rect:s,paths:r,thickness:n,opacity:g}=e,o=[`${n} w 1 J 1 j`,`${getPdfColor(a,!1)}`];1!==g&&o.push("/R0 gs");for(const e of r.lines){o.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,i=e.length;t{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}static createNewDict(e,t,{apRef:i,ap:a}){const{color:s,oldAnnotation:r,opacity:n,rect:g,rotation:o,user:c,quadPoints:C}=e,h=r||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("Highlight"));h.set(r?"M":"CreationDate",`D:${getModificationDate()}`);h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",g);h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);h.set("QuadPoints",C);h.set("C",Array.from(s,(e=>e/255)));h.set("CA",n);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);e.set("N",i||a)}return h}static async createNewAppearanceStream(e,t,i){const{color:a,rect:s,outlines:r,opacity:n}=e,g=[`${getPdfColor(a,!0)}`,"/R0 gs"],o=[];for(const e of r){o.length=0;o.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,i=e.length;t{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=Y;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA");this._setDefaultAppearance({xref:i,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{const i=(t[1]-t[5])/6;let a=i,s=t[4];const r=t[5],n=t[6];e.push(`${s} ${r+a} m`);do{s+=2;a=0===a?i:0;e.push(`${s} ${r+a} l`)}while(s{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{#T;constructor(e){super(e);this.data.annotationType=K;this.#T=this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!1;this.#T=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}this.data.hasOwnCanvas=this.#T;return!t?.has(this.data.id)}static async createImage(e,t){const{width:i,height:a}=e,s=new OffscreenCanvas(i,a),r=s.getContext("2d",{alpha:!0});r.drawImage(e,0,0);const n=r.getImageData(0,0,i,a).data,g=new Uint32Array(n.buffer),o=g.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(o){r.fillStyle="white";r.fillRect(0,0,i,a);r.drawImage(e,0,0)}const c=s.convertToBlob({type:"image/jpeg",quality:1}).then((e=>e.arrayBuffer())),C=Name.get("XObject"),h=Name.get("Image"),l=new Dict(t);l.set("Type",C);l.set("Subtype",h);l.set("BitsPerComponent",8);l.set("ColorSpace",Name.get("DeviceRGB"));l.set("Filter",Name.get("DCTDecode"));l.set("BBox",[0,0,i,a]);l.set("Width",i);l.set("Height",a);let Q=null;if(o){const e=new Uint8Array(g.length);if(FeatureTest.isLittleEndian)for(let t=0,i=g.length;t>>24;else for(let t=0,i=g.length;t=0&&r<=1?r:null}}class DecryptStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.decrypt=i;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.str.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.str.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const i=this.bufferLength,a=i+e.length;this.ensureBuffer(a).set(e,i);this.bufferLength=a}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),i=e.length;for(let e=0;e<256;++e)t[e]=e;for(let a=0,s=0;a<256;++a){const r=t[a];s=s+r+e[a%i]&255;t[a]=t[s];t[s]=r}this.s=t}encryptBlock(e){let t=this.a,i=this.b;const a=this.s,s=e.length,r=new Uint8Array(s);for(let n=0;n>5&255;C[h++]=s>>13&255;C[h++]=s>>21&255;C[h++]=s>>>29&255;C[h++]=0;C[h++]=0;C[h++]=0;const E=new Int32Array(16);for(h=0;h>>32-g)|0;s=r}r=r+s|0;n=n+c|0;g=g+Q|0;o=o+u|0}return new Uint8Array([255&r,r>>8&255,r>>16&255,r>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&g,g>>8&255,g>>16&255,g>>>24&255,255&o,o>>8&255,o>>16&255,o>>>24&255])}}();class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}or(e){this.high|=e.high;this.low|=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}shiftLeft(e){if(e>=32){this.high=this.low<>>32-e;this.low<<=e}}rotateRight(e){let t,i;if(32&e){i=this.low;t=this.high}else{t=this.low;i=this.high}e&=31;this.low=t>>>e|i<<32-e;this.high=i>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let i=(this.high>>>0)+(e.high>>>0);t>4294967295&&(i+=1);this.low=0|t;this.high=0|i}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const Ag=function calculateSHA256Closure(){function rotr(e,t){return e>>>t|e<<32-t}function ch(e,t,i){return e&t^~e&i}function maj(e,t,i){return e&t^e&i^t&i}function sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function hash(t,i,a){let s=1779033703,r=3144134277,n=1013904242,g=2773480762,o=1359893119,c=2600822924,C=528734635,h=1541459225;const l=64*Math.ceil((a+9)/64),Q=new Uint8Array(l);let E,u;for(E=0;E>>29&255;Q[E++]=a>>21&255;Q[E++]=a>>13&255;Q[E++]=a>>5&255;Q[E++]=a<<3&255;const f=new Uint32Array(64);for(E=0;E>>10)+f[u-7]+littleSigma(f[u-15])+f[u-16]|0;let t,i,a=s,l=r,d=n,m=g,y=o,w=c,D=C,b=h;for(u=0;u<64;++u){t=b+sigmaPrime(y)+ch(y,w,D)+e[u]+f[u];i=sigma(a)+maj(a,l,d);b=D;D=w;w=y;y=m+t|0;m=d;d=l;l=a;a=t+i|0}s=s+a|0;r=r+l|0;n=n+d|0;g=g+m|0;o=o+y|0;c=c+w|0;C=C+D|0;h=h+b|0}var p;return new Uint8Array([s>>24&255,s>>16&255,s>>8&255,255&s,r>>24&255,r>>16&255,r>>8&255,255&r,n>>24&255,n>>16&255,n>>8&255,255&n,g>>24&255,g>>16&255,g>>8&255,255&g,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,C>>24&255,C>>16&255,C>>8&255,255&C,h>>24&255,h>>16&255,h>>8&255,255&h])}}(),eg=function calculateSHA512Closure(){function ch(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.not();s.and(a);e.xor(s)}function maj(e,t,i,a,s){e.assign(t);e.and(i);s.assign(t);s.and(a);e.xor(s);s.assign(i);s.and(a);e.xor(s)}function sigma(e,t,i){e.assign(t);e.rotateRight(28);i.assign(t);i.rotateRight(34);e.xor(i);i.assign(t);i.rotateRight(39);e.xor(i)}function sigmaPrime(e,t,i){e.assign(t);e.rotateRight(14);i.assign(t);i.rotateRight(18);e.xor(i);i.assign(t);i.rotateRight(41);e.xor(i)}function littleSigma(e,t,i){e.assign(t);e.rotateRight(1);i.assign(t);i.rotateRight(8);e.xor(i);i.assign(t);i.shiftRight(7);e.xor(i)}function littleSigmaPrime(e,t,i){e.assign(t);e.rotateRight(19);i.assign(t);i.rotateRight(61);e.xor(i);i.assign(t);i.shiftRight(6);e.xor(i)}const e=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function hash(t,i,a,s=!1){let r,n,g,o,c,C,h,l;if(s){r=new Word64(3418070365,3238371032);n=new Word64(1654270250,914150663);g=new Word64(2438529370,812702999);o=new Word64(355462360,4144912697);c=new Word64(1731405415,4290775857);C=new Word64(2394180231,1750603025);h=new Word64(3675008525,1694076839);l=new Word64(1203062813,3204075428)}else{r=new Word64(1779033703,4089235720);n=new Word64(3144134277,2227873595);g=new Word64(1013904242,4271175723);o=new Word64(2773480762,1595750129);c=new Word64(1359893119,2917565137);C=new Word64(2600822924,725511199);h=new Word64(528734635,4215389547);l=new Word64(1541459225,327033209)}const Q=128*Math.ceil((a+17)/128),E=new Uint8Array(Q);let u,d;for(u=0;u>>29&255;E[u++]=a>>21&255;E[u++]=a>>13&255;E[u++]=a>>5&255;E[u++]=a<<3&255;const p=new Array(80);for(u=0;u<80;u++)p[u]=new Word64(0,0);let m=new Word64(0,0),y=new Word64(0,0),w=new Word64(0,0),D=new Word64(0,0),b=new Word64(0,0),F=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0);const R=new Word64(0,0),N=new Word64(0,0),G=new Word64(0,0),M=new Word64(0,0);let U,x;for(u=0;u=1;--e){i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e)r[e]=this._inv_s[r[e]];for(let i=0,a=16*e;i<16;++i,++a)r[i]^=t[a];for(let e=0;e<16;e+=4){const t=this._mix[r[e]],a=this._mix[r[e+1]],s=this._mix[r[e+2]],n=this._mix[r[e+3]];i=t^a>>>8^a<<24^s>>>16^s<<16^n>>>24^n<<8;r[e]=i>>>24&255;r[e+1]=i>>16&255;r[e+2]=i>>8&255;r[e+3]=255&i}}i=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=i;i=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=i;r[2]=a;i=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=i;r[7]=a;r[3]=s;for(let e=0;e<16;++e){r[e]=this._inv_s[r[e]];r[e]^=t[e]}return r}_encrypt(e,t){const i=this._s;let a,s,r;const n=new Uint8Array(16);n.set(e);for(let e=0;e<16;++e)n[e]^=t[e];for(let e=1;e=a;--i)if(e[i]!==t){t=0;break}g-=t;r[r.length-1]=e.subarray(0,16-t)}}const o=new Uint8Array(g);for(let e=0,t=0,i=r.length;e=256&&(g=255&(27^g))}for(let t=0;t<4;++t){i[e]=a^=i[e-32];e++;i[e]=s^=i[e-32];e++;i[e]=r^=i[e-32];e++;i[e]=n^=i[e-32];e++}}return i}}class PDF17{checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(Ag(s,0,s.length),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(Ag(a,0,a.length),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=Ag(s,0,s.length);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=Ag(a,0,a.length);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class PDF20{_hash(e,t,i){let a=Ag(t,0,t.length).subarray(0,32),s=[0],r=0;for(;r<64||s.at(-1)>r-32;){const t=e.length+a.length+i.length,c=new Uint8Array(t);let C=0;c.set(e,C);C+=e.length;c.set(a,C);C+=a.length;c.set(i,C);const h=new Uint8Array(64*t);for(let e=0,i=0;e<64;e++,i+=t)h.set(c,i);s=new AES128Cipher(a.subarray(0,16)).encrypt(h,a.subarray(16,32));const l=s.slice(0,16).reduce(((e,t)=>e+t),0)%3;0===l?a=Ag(s,0,s.length):1===l?a=(n=s,g=0,o=s.length,eg(n,g,o,!0)):2===l&&(a=eg(s,0,s.length));r++}var n,g,o;return a.subarray(0,32)}checkOwnerPassword(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);return isArrayEqual(this._hash(e,s,i),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(this._hash(e,a,[]),i)}getOwnerKey(e,t,i,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(i,e.length+t.length);const r=this._hash(e,s,i);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=this._hash(e,a,[]);return new AES256Cipher(s).decryptBlock(i,!1,new Uint8Array(16))}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const i=new this.StreamCipherConstructor;return new DecryptStream(e,t,(function cipherTransformDecryptStream(e,t){return i.decryptBlock(e,t)}))}decryptString(e){const t=new this.StringCipherConstructor;let i=stringToBytes(e);i=t.decryptBlock(i,!0);return bytesToString(i)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const i=16-e.length%16;e+=String.fromCharCode(i).repeat(i);const a=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(a);else for(let e=0;e<16;e++)a[e]=Math.floor(256*Math.random());let s=stringToBytes(e);s=t.encrypt(s,a);const r=new Uint8Array(16+s.length);r.set(a);r.set(s,16);return bytesToString(r)}let i=stringToBytes(e);i=t.encrypt(i);return bytesToString(i)}}class CipherTransformFactory{static#q=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#O(e,t,i,a,s,r,n,g,o,c,C,h){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const l=6===e?new PDF20:new PDF17;return l.checkUserPassword(t,g,n)?l.getUserKey(t,o,C):t.length&&l.checkOwnerPassword(t,a,r,i)?l.getOwnerKey(t,s,r,c):null}#P(e,t,i,a,s,r,n,g){const o=40+i.length+e.length,c=new Uint8Array(o);let C,h,l=0;if(t){h=Math.min(32,t.length);for(;l>8&255;c[l++]=s>>16&255;c[l++]=s>>>24&255;for(C=0,h=e.length;C=4&&!g){c[l++]=255;c[l++]=255;c[l++]=255;c[l++]=255}let Q=$n(c,0,l);const E=n>>3;if(r>=3)for(C=0;C<50;++C)Q=$n(Q,0,E);const u=Q.subarray(0,E);let d,f;if(r>=3){for(l=0;l<32;++l)c[l]=CipherTransformFactory.#q[l];for(C=0,h=e.length;C>3;if(i>=3)for(g=0;g<50;++g)o=$n(o,0,o.length);let C,h;if(i>=3){h=t;const e=new Uint8Array(c);for(g=19;g>=0;g--){for(let t=0;t>8&255;s[n++]=e>>16&255;s[n++]=255&t;s[n++]=t>>8&255;if(a){s[n++]=115;s[n++]=65;s[n++]=108;s[n++]=84}return $n(s,0,n).subarray(0,Math.min(i.length+5,16))}#X(e,t,i,a,s){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const r=this,n=e.get(t.name),g=n?.get("CFM");if(!g||"None"===g.name)return function(){return new NullCipher};if("V2"===g.name)return function(){return new ARCFourCipher(r.#j(i,a,s,!1))};if("AESV2"===g.name)return function(){return new AES128Cipher(r.#j(i,a,s,!0))};if("AESV3"===g.name)return function(){return new AES256Cipher(s)};throw new FormatError("Unknown crypto method")}constructor(e,t,i){const a=e.get("Filter");if(!isName(a,"Standard"))throw new FormatError("unknown encryption method");this.filterName=a.name;this.dict=e;const s=e.get("V");if(!Number.isInteger(s)||1!==s&&2!==s&&4!==s&&5!==s)throw new FormatError("unsupported encryption algorithm");this.algorithm=s;let r=e.get("Length");if(!r)if(s<=3)r=40;else{const t=e.get("CF"),i=e.get("StmF");if(t instanceof Dict&&i instanceof Name){t.suppressEncryption=!0;const e=t.get(i.name);r=e?.get("Length")||128;r<40&&(r<<=3)}}if(!Number.isInteger(r)||r<40||r%8!=0)throw new FormatError("invalid key length");const n=stringToBytes(e.get("O")),g=stringToBytes(e.get("U")),o=n.subarray(0,32),c=g.subarray(0,32),C=e.get("P"),h=e.get("R"),l=(4===s||5===s)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=l;const Q=stringToBytes(t);let E,u;if(i){if(6===h)try{i=utf8StringToString(i)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}E=stringToBytes(i)}if(5!==s)u=this.#P(Q,E,o,c,C,h,r,l);else{const t=n.subarray(32,40),i=n.subarray(40,48),a=g.subarray(0,48),s=g.subarray(32,40),r=g.subarray(40,48),C=stringToBytes(e.get("OE")),l=stringToBytes(e.get("UE")),Q=stringToBytes(e.get("Perms"));u=this.#O(h,E,o,t,i,a,c,s,r,C,l,Q)}if(!u&&!i)throw new PasswordException("No password given",rt);if(!u&&i){const e=this.#W(E,o,h,r);u=this.#P(Q,e,o,c,C,h,r,l)}if(!u)throw new PasswordException("Incorrect Password",nt);this.encryptionKey=u;if(s>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#X(this.cf,this.strf,e,t,this.encryptionKey),this.#X(this.cf,this.stmf,e,t,this.encryptionKey));const i=this.#j(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(i)};return new CipherTransform(cipherConstructor,cipherConstructor)}}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const i=t.firstChild;return"value"===i?.nodeName?t.children.map((e=>decodeString(e.textContent))):decodeString(t.textContent)}}class XRef{#Z=null;constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[n,g]=r;if(!Number.isInteger(n)||!Number.isInteger(g))throw new FormatError(`Invalid XRef range fields: ${n}, ${g}`);if(!Number.isInteger(i)||!Number.isInteger(a)||!Number.isInteger(s))throw new FormatError(`Invalid XRef entry fields length: ${n}, ${g}`);for(let r=t.entryNum;r=e.length);){i+=String.fromCharCode(a);a=e[t]}return i}function skipUntil(e,t,i){const a=i.length,s=e.length;let r=0;for(;t=a)break;t++;r++}return r}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,i=/^(\d+)\s+(\d+)\s+obj\b/,a=new Uint8Array([116,114,97,105,108,101,114]),s=new Uint8Array([115,116,97,114,116,120,114,101,102]),r=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const n=this.stream;n.pos=0;const g=n.getBytes(),o=bytesToString(g),c=g.length;let C=n.start;const h=[],l=[];for(;C=c)break;Q=g[C]}while(10!==Q&&13!==Q);continue}const E=readToken(g,C);let u;if(E.startsWith("xref")&&(4===E.length||/\s/.test(E[4]))){C+=skipUntil(g,C,a);h.push(C);C+=skipUntil(g,C,s)}else if(u=i.exec(E)){const t=0|u[1],i=0|u[2],a=C+E.length;let s,h=!1;if(this.entries[t]){if(this.entries[t].gen===i)try{new Parser({lexer:new Lexer(n.makeSubStream(a))}).getObj();h=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${E}): "${e}".`):h=!0}}else h=!0;h&&(this.entries[t]={offset:C-n.start,gen:i,uncompressed:!0});e.lastIndex=a;const Q=e.exec(o);if(Q){s=e.lastIndex+1-C;if("endobj"!==Q[1]){warn(`indexObjects: Found "${Q[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);s-=Q[1].length+1}}else s=c-C;const d=g.subarray(C,C+s),f=skipUntil(d,0,r);if(f0?Math.max(...this._xrefStms):null)}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const i=e.num,a=this._cacheMap.get(i);if(void 0!==a){a instanceof Dict&&!a.objId&&(a.objId=e.toString());return a}let s=this.getEntry(i);if(null===s){this._cacheMap.set(i,s);return s}if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return lt}this._pendingRefs.put(e);try{s=s.uncompressed?this.fetchUncompressed(e,s,t):this.fetchCompressed(e,s,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}s instanceof Dict?s.objId=e.toString():s instanceof BaseStream&&(s.dict.objId=e.toString());return s}fetchUncompressed(e,t,i=!1){const a=e.gen;let s=e.num;if(t.gen!==a){const r=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this._getBoundingBox("MediaBox")||tg)}get cropBox(){return shadow(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const i=Util.intersect(e,t);if(i&&i[2]-i[0]>0&&i[3]-i[1]>0)return shadow(this,"view",i);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this._getInheritableProperty("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}_onSubStreamError(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((e=>e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this._onSubStreamError.bind(this)):new NullStream))}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#V(e,t,i){const a=[];for(const s of e)if(s.id){const e=Ref.fromString(s.id);if(!e){warn(`A non-linked annotation cannot be modified: ${s.id}`);continue}if(s.deleted){t.put(e,e);if(s.popupRef){const e=Ref.fromString(s.popupRef);e&&t.put(e,e)}continue}i?.put(e);s.ref=e;a.push(this.xref.fetchAsync(e).then((e=>{e instanceof Dict&&(s.oldAnnotation=e.clone())}),(()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)})));delete s.id}await Promise.all(a)}async saveNewAnnotations(e,t,i,a,s){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const r=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),n=new RefSetCache,g=new RefSet;await this.#V(i,n,g);const o=this.pageDict,c=this.annotations.filter((e=>!(e instanceof Ref&&n.has(e)))),C=await AnnotationFactory.saveNewAnnotations(r,t,i,a,s);for(const{ref:e}of C.annotations)e instanceof Ref&&!g.has(e)&&c.push(e);const h=o.clone();h.set("Annots",c);s.put(this.ref,{data:h});for(const e of n)s.put(e,{data:null})}save(e,t,i,a){const s=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(e){const r=[];for(const n of e)r.push(n.save(s,t,i,a).catch((function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null})));return Promise.all(r)}))}loadResources(e){this.resourcesPromise||=this.pdfManager.ensure(this,"resources");return this.resourcesPromise.then((()=>new ObjectLoader(this.resources,e,this.xref).load()))}getOperatorList({handler:e,sink:t,task:i,intent:a,cacheKey:s,annotationStorage:r=null,modifiedIds:n=null}){const C=this.getContentStream(),E=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),d=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),f=this.xfaFactory?null:getNewAnnotationsMap(r),p=f?.get(this.pageIndex);let m=Promise.resolve(null),y=null;if(p){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const a=new Set;for(const{bitmapId:e,bitmap:t}of p)!e||t||a.has(e)||a.add(e);const{isOffscreenCanvasSupported:s}=this.evaluatorOptions;if(a.size>0){const e=p.slice();for(const[t,i]of r)t.startsWith(u)&&i.bitmap&&a.has(i.bitmapId)&&e.push(i);t=AnnotationFactory.generateImages(e,this.xref,s)}else t=AnnotationFactory.generateImages(p,this.xref,s);y=new RefSet;m=Promise.all([e,this.#V(p,y,null)]).then((([e])=>e?AnnotationFactory.printNewAnnotations(e,d,i,p,t):null))}const w=Promise.all([C,E]).then((([r])=>{const n=new OperatorList(a,t);e.send("StartRenderPage",{transparency:d.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:s});return d.getOperatorList({stream:r,task:i,resources:this.resources,operatorList:n}).then((function(){return n}))}));return Promise.all([w,this._parsedAnnotations,m]).then((function([e,t,s]){if(s){t=t.filter((e=>!(e.ref&&y.has(e.ref))));for(let e=0,i=s.length;ee.ref&&isRefsEqual(e.ref,a.refToReplace)));if(r>=0){t.splice(r,1,a);s.splice(e--,1);i--}}}t=t.concat(s)}if(0===t.length||a&l){e.flush(!0);return{length:e.totalLength}}const C=!!(a&h),E=!!(a&Q),u=!!(a&g),f=!!(a&o),p=!!(a&c),m=[];for(const e of t)(u||f&&e.mustBeViewed(r,C)&&e.mustBeViewedWhenEditing(E,n)||p&&e.mustBePrinted(r))&&m.push(e.getOperatorList(d,i,a,r).catch((function(e){warn(`getOperatorList - ignoring annotation data during "${i.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(m).then((function(t){let i=!1,a=!1;for(const{opList:s,separateForm:r,separateCanvas:n}of t){e.addOpList(s);i||=r;a||=n}e.flush(!0,{form:i,canvas:a});return{length:e.totalLength}}))}))}async extractTextContent({handler:e,task:t,includeMarkedContent:i,disableNormalization:a,sink:s}){const r=this.getContentStream(),n=this.loadResources(["ExtGState","Font","Properties","XObject"]),g=this.pdfManager.ensureCatalog("lang"),[o,,c]=await Promise.all([r,n,g]);return new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:o,task:t,resources:this.resources,includeMarkedContent:i,disableNormalization:a,sink:s,viewBox:this.view,lang:c})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return this.pdfManager.ensure(t,"serializable")}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,i){const a=await this._parsedAnnotations;if(0===a.length)return a;const s=[],r=[];let n;const C=!!(i&g),h=!!(i&o),l=!!(i&c);for(const i of a){const a=C||h&&i.viewable;(a||l&&i.printable)&&s.push(i.data);if(i.hasTextContent&&a){n||=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});r.push(i.extractTextContent(n,t,[-1/0,-1/0,1/0,1/0]).catch((function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)})))}}await Promise.all(r);return s}get annotations(){const e=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){return shadow(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async e=>{if(0===e.length)return e;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const a=i?.orphanFields,s=[];for(const i of e)s.push(AnnotationFactory.create(this.xref,i,t,this._localIdFactory,!1,a,this.ref).catch((function(e){warn(`_parsedAnnotations: "${e}".`);return null})));const r=[];let n,g;for(const e of await Promise.all(s))e&&(e instanceof WidgetAnnotation?(g||=[]).push(e):e instanceof PopupAnnotation?(n||=[]).push(e):r.push(e));g&&r.push(...g);n&&r.push(...n);return r})))}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,pA))}}const ig=new Uint8Array([37,80,68,70,45]),ag=new Uint8Array([115,116,97,114,116,120,114,101,102]),sg=new Uint8Array([101,110,100,111,98,106]);function find(e,t,i=1024,a=!1){const s=t.length,r=e.peekBytes(i),n=r.length-s;if(n<=0)return!1;if(a){const i=s-1;let a=r.length-1;for(;a>=i;){let n=0;for(;n=s){e.pos+=a-i;return!0}a--}}else{let i=0;for(;i<=n;){let a=0;for(;a=s){e.pos+=i;return!0}i++}}return!1}class PDFDocument{constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);this._pagePromises=new Map;this._version=null;const i={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++i.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,sg)){e.skip(6);let i=e.peekByte();for(;isWhiteSpace(i);){e.pos++;i=e.peekByte()}t=e.pos-e.start}}else{const i=1024,a=ag.length;let s=!1,r=e.end;for(;!s&&r>0;){r-=i-a;r<0&&(r=0);e.pos=r;s=find(e,ag,i,!0)}if(s){e.skip(9);let i;do{i=e.getByte()}while(isWhiteSpace(i));let a="";for(;i>=32&&i<=57;){a+=String.fromCharCode(i);i=e.getByte()}t=parseInt(a,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,ig))return;e.moveStart();e.skip(ig.length);let t,i="";for(;(t=e.getByte())>32&&i.length<7;)i+=String.fromCharCode(t);ft.test(i)?this._version=i:warn(`Invalid PDF header version: ${i}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}_hasOnlyDocumentSignatures(e,t=0){return!!Array.isArray(e)&&e.every((e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this._hasOnlyDocumentSignatures(e.get("Kids"),t)}const i=isName(e.get("FT"),"Sig"),a=e.get("Rect"),s=Array.isArray(a)&&a.every((e=>0===e));return i&&s}))}get _xfaStreams(){const e=this.catalog.acroForm;if(!e)return null;const t=e.get("XFA"),i={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(t instanceof BaseStream&&!t.isEmpty){i["xdp:xdp"]=t;return i}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,a=t.length;e0;e.hasFields=a;const s=t.get("XFA");e.hasXfa=Array.isArray(s)&&s.length>0||s instanceof BaseStream&&!s.isEmpty;const r=!!(1&t.get("SigFlags")),n=r&&this._hasOnlyDocumentSignatures(i);e.hasAcroForm=a&&!n;e.hasSignatures=r}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const e={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let t;try{t=this.xref.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(t instanceof Dict))return shadow(this,"documentInfo",e);for(const i of t.getKeys()){const a=t.get(i);switch(i){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof a){e[i]=stringToPDFString(a);continue}break;case"Trapped":if(a instanceof Name){e[i]=a;continue}break;default:let t;switch(typeof a){case"string":t=stringToPDFString(a);break;case"number":case"boolean":t=a;break;default:a instanceof Name&&(t=a)}if(void 0===t){warn(`Bad value, for custom key "${i}", in Info: ${a}.`);continue}e.Custom||(e.Custom=Object.create(null));e.Custom[i]=t;continue}warn(`Bad value, for key "${i}", in Info: ${a}.`)}return shadow(this,"documentInfo",e)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let i,a;if(Array.isArray(t)&&validate(t[0])){i=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(a=stringToBytes(t[1]))}else i=$n(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[toHexUtil(i),a?toHexUtil(a):null])}async _getLinearizationPage(e){const{catalog:t,linearization:i,xref:a}=this,s=Ref.get(i.objectNumberFirst,0);try{const e=await a.fetchAsync(s);if(e instanceof Dict){let i=e.getRaw("Type");i instanceof Ref&&(i=await a.fetchAsync(i));if(isName(i,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(s)||t.pageKidsCountCache.put(s,1);t.pageIndexCache.has(s)||t.pageIndexCache.put(s,0);return[e,s]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(i){warn(`_getLinearizationPage: "${i.message}".`);return t.getPageDict(e)}}getPage(e){const t=this._pagePromises.get(e);if(t)return t;const{catalog:i,linearization:a,xfaFactory:s}=this;let r;r=s?Promise.resolve([Dict.empty,null]):a?.pageFirst===e?this._getLinearizationPage(e):i.getPageDict(e);r=r.then((([t,a])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:a,globalIdFactory:this._globalIdFactory,fontCache:i.fontCache,builtInCMapCache:i.builtInCMapCache,standardFontDataCache:i.standardFontDataCache,globalImageCache:i.globalImageCache,systemFontCache:i.systemFontCache,nonBlendModesSet:i.nonBlendModesSet,xfaFactory:s})));this._pagePromises.set(e,r);return r}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this._pagePromises.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:i}=this;t.setActualNumPages();let a;try{await Promise.all([i.ensureDoc("xfaFactory"),i.ensureDoc("linearization"),i.ensureCatalog("numPages")]);if(this.xfaFactory)return;a=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(a))throw new FormatError("Page count is not an integer.");if(a<=1)return;await this.getPage(a-1)}catch(s){this._pagePromises.delete(a-1);await this.cleanup();if(s instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${a}.`);let r;try{r=await t.getAllPageDicts(e)}catch(i){if(i instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[a,s]]of r){let r;if(a instanceof Error){r=Promise.reject(a);r.catch((()=>{}))}else r=Promise.resolve(new Page({pdfManager:i,xref:this.xref,pageIndex:e,pageDict:a,ref:s,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this._pagePromises.set(e,r)}t.setActualNumPages(r.size)}}fontFallback(e,t){return this.catalog.fontFallback(e,t)}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#z(e,t,i,a,s,r,n){const{xref:g}=this;if(!(i instanceof Ref)||r.has(i))return;r.put(i);const o=await g.fetchAsync(i);if(!(o instanceof Dict))return;if(o.has("T")){const t=stringToPDFString(await o.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let i=o;for(;;){i=i.getRaw("Parent")||t;if(i instanceof Ref){if(r.has(i))break;i=await g.fetchAsync(i)}if(!(i instanceof Dict))break;if(i.has("T")){const t=stringToPDFString(await i.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!o.has("Parent")&&isName(o.get("Subtype"),"Widget")&&n.put(i,t);a.has(e)||a.set(e,[]);a.get(e).push(AnnotationFactory.create(g,i,s,null,!0,n,null).then((e=>e?.getFieldObject())).catch((function(e){warn(`#collectFieldObjects: "${e}".`);return null})));if(!o.has("Kids"))return;const c=await o.getAsync("Kids");if(Array.isArray(c))for(const t of c)await this.#z(e,i,t,a,s,r,n)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then((async e=>{if(!e.hasFields)return null;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]);if(!t)return null;const a=new RefSet,s=Object.create(null),r=new Map,n=new RefSetCache;for(const e of await i.getAsync("Fields"))await this.#z("",null,e,r,t,a,n);const g=[];for(const[e,t]of r)g.push(Promise.all(t).then((t=>{(t=t.filter((e=>!!e))).length>0&&(s[e]=t)})));await Promise.all(g);return{allFields:s,orphanFields:n}})))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t&&Object.values(t.allFields).some((e=>e.some((e=>null!==e.actions))))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const i of e)i instanceof Ref&&t.push(i.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor(e){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e.docBaseUrl);this._docId=e.docId;this._password=e.password;this.enableXfa=e.enableXfa;e.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;e.evaluatorOptions.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(e.evaluatorOptions)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}loadXfaFonts(e,t){return this.pdfDocument.loadXfaFonts(e,t)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(e){return this.pdfDocument.serializeXfaData(e)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,i){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,i){const a=e[t];return"function"==typeof a?a.apply(e,i):a}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,i){try{const a=e[t];return"function"==typeof a?a.apply(e,i):a}catch(a){if(!(a instanceof MissingDataException))throw a;await this.requestRange(a.begin,a.end);return this.ensure(e,t,i)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const rg=1,ng=2,gg=1,og=2,Ig=3,cg=4,Cg=5,hg=6,lg=7,Bg=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof MissingPDFException||e instanceof PasswordException||e instanceof UnexpectedResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"MissingPDFException":return new MissingPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"UnexpectedResponseException":return new UnexpectedResponseException(e.message,e.status);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#_=new AbortController;constructor(e,t,i){this.sourceName=e;this.targetName=t;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.#$.bind(this),{signal:this.#_.signal})}#$({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#AA(e);return}if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===rg)i.resolve(e.data);else{if(e.callback!==ng)throw new Error("Unexpected callback case");i.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const i=this.sourceName,a=e.sourceName,s=this.comObj;Promise.try(t,e.data).then((function(t){s.postMessage({sourceName:i,targetName:a,callback:rg,callbackId:e.callbackId,data:t})}),(function(t){s.postMessage({sourceName:i,targetName:a,callback:ng,callbackId:e.callbackId,reason:wrapReason(t)})}))}else e.streamId?this.#eA(e):t(e.data)}on(e,t){const i=this.actionHandler;if(i[e])throw new Error(`There is already an actionName called "${e}"`);i[e]=t}send(e,t,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},i)}sendWithPromise(e,t,i){const a=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[a]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:a,data:t},i)}catch(e){s.reject(e)}return s.promise}sendWithStream(e,t,i,a){const s=this.streamId++,r=this.sourceName,n=this.targetName,g=this.comObj;return new ReadableStream({start:i=>{const o=Promise.withResolvers();this.streamControllers[s]={controller:i,startCall:o,pullCall:null,cancelCall:null,isClosed:!1};g.postMessage({sourceName:r,targetName:n,action:e,streamId:s,data:t,desiredSize:i.desiredSize},a);return o.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[s].pullCall=t;g.postMessage({sourceName:r,targetName:n,stream:hg,streamId:s,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[s].cancelCall=t;this.streamControllers[s].isClosed=!0;g.postMessage({sourceName:r,targetName:n,stream:gg,streamId:s,reason:wrapReason(e)});return t.promise}},i)}#eA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this,n=this.actionHandler[e.action],g={enqueue(e,r=1,n){if(this.isCancelled)return;const g=this.desiredSize;this.desiredSize-=r;if(g>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:i,targetName:a,stream:cg,streamId:t,chunk:e},n)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Ig,streamId:t});delete r.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:a,stream:Cg,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};g.sinkCapability.resolve();g.ready=g.sinkCapability.promise;this.streamSinks[t]=g;Promise.try(n,e.data,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:Bg,streamId:t,reason:wrapReason(e)})}))}#AA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,s=this.comObj,r=this.streamControllers[t],n=this.streamSinks[t];switch(e.stream){case Bg:e.success?r.startCall.resolve():r.startCall.reject(wrapReason(e.reason));break;case lg:e.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(e.reason));break;case hg:if(!n){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0});break}n.desiredSize<=0&&e.desiredSize>0&&n.sinkCapability.resolve();n.desiredSize=e.desiredSize;Promise.try(n.onPull||onFn).then((function(){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:lg,streamId:t,reason:wrapReason(e)})}));break;case cg:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(e.chunk);break;case Ig:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#tA(r,t);break;case Cg:assert(r,"error should have stream controller");r.controller.error(wrapReason(e.reason));this.#tA(r,t);break;case og:e.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(e.reason));this.#tA(r,t);break;case gg:if(!n)break;const g=wrapReason(e.reason);Promise.try(n.onCancel||onFn,g).then((function(){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,success:!0})}),(function(e){s.postMessage({sourceName:i,targetName:a,stream:og,streamId:t,reason:wrapReason(e)})}));n.sinkCapability.reject(g);n.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#tA(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#_?.abort();this.#_=null}}async function writeObject(e,t,i,{encrypt:a=null}){const s=a?.createCipherTransform(e.num,e.gen);i.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,i,s):t instanceof BaseStream?await writeStream(t,i,s):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,i,s);i.push("\nendobj\n")}async function writeDict(e,t,i){t.push("<<");for(const a of e.getKeys()){t.push(` /${escapePDFName(a)} `);await writeValue(e.getRaw(a),t,i)}t.push(">>")}async function writeStream(e,t,i){let a=e.getBytes();const{dict:s}=e,[r,n]=await Promise.all([s.getAsync("Filter"),s.getAsync("DecodeParms")]),g=isName(Array.isArray(r)?await s.xref.fetchIfRefAsync(r[0]):r,"FlateDecode");if(a.length>=256||g)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(a).then((async()=>{await t.ready;await t.close()})).catch((()=>{}));const i=await new Response(e.readable).arrayBuffer();a=new Uint8Array(i);let o,c;if(r){if(!g){o=Array.isArray(r)?[Name.get("FlateDecode"),...r]:[Name.get("FlateDecode"),r];n&&(c=Array.isArray(n)?[null,...n]:[null,n])}}else o=Name.get("FlateDecode");o&&s.set("Filter",o);c&&s.set("DecodeParms",c)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let o=bytesToString(a);i&&(o=i.encryptString(o));s.set("Length",o.length);await writeDict(s,t,i);t.push(" stream\n",o,"\nendstream")}async function writeArray(e,t,i){t.push("[");let a=!0;for(const s of e){a?a=!1:t.push(" ");await writeValue(s,t,i)}t.push("]")}async function writeValue(e,t,i){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,i);else if("string"==typeof e){i&&(e=i.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,i):e instanceof BaseStream?await writeStream(e,t,i):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,i,a){for(let s=t+i-1;s>i-1;s--){a[s]=255&e;e>>=8}return i+t}function writeString(e,t,i){for(let a=0,s=e.length;a1&&(r=i.documentElement.searchNode([s.at(-1)],0));r?r.childNodes=Array.isArray(a)?a.map((e=>new SimpleDOMNode("value",e))):[new SimpleDOMNode("#text",a)]:warn(`Node not found for path: ${t}`)}const a=[];i.documentElement.dump(a);return a.join("")}(a.fetchIfRef(t).getString(),i)}const s=new StringStream(e);s.dict=new Dict(a);s.dict.set("Type",Name.get("EmbeddedFile"));i.put(t,{data:s})}function getIndexes(e){const t=[];for(const{ref:i}of e)i.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(i.num,1);return t}function computeIDs(e,t,i){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const a=function computeMD5(e,t){const i=Math.floor(Date.now()/1e3),a=t.filename||"",s=[i.toString(),a,e.toString()];let r=s.reduce(((e,t)=>e+t.length),0);for(const e of Object.values(t.info)){s.push(e);r+=e.length}const n=new Uint8Array(r);let g=0;for(const e of s){writeString(e,g,n);g+=e.length}return bytesToString($n(n))}(e,t);i.set("ID",[t.fileIds[0],a])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:i,xref:a=null,hasXfa:s=!1,xfaDatasetsRef:r=null,hasXfaDatasetsEntry:n=!1,needAppearances:g,acroFormRef:o=null,acroForm:c=null,xfaData:C=null,useXrefStream:h=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:i,hasXfa:a,hasXfaDatasetsEntry:s,xfaDatasetsRef:r,needAppearances:n,changes:g}){!a||s||r||warn("XFA - Cannot save it");if(!n&&(!a||!r||s))return;const o=t.clone();if(a&&!s){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,r);o.set("XFA",e)}n&&o.set("NeedAppearances",!0);g.put(i,{data:o})}({xref:a,acroForm:c,acroFormRef:o,hasXfa:s,hasXfaDatasetsEntry:n,xfaDatasetsRef:r,needAppearances:g,changes:i});s&&updateXFA({xfaData:C,xfaDatasetsRef:r,changes:i,xref:a});const l=function getTrailerDict(e,t,i){const a=new Dict(null);a.set("Prev",e.startXRef);const s=e.newRef;if(i){t.put(s,{data:""});a.set("Size",s.num+1);a.set("Type",Name.get("XRef"))}else a.set("Size",s.num);null!==e.rootRef&&a.set("Root",e.rootRef);null!==e.infoRef&&a.set("Info",e.infoRef);null!==e.encryptRef&&a.set("Encrypt",e.encryptRef);return a}(t,i,h),Q=[],E=await async function writeChanges(e,t,i=[]){const a=[];for(const[s,{data:r}]of e.items())if(null!==r&&"string"!=typeof r){await writeObject(s,r,i,t);a.push({ref:s,data:i.join("")});i.length=0}else a.push({ref:s,data:r});return a.sort(((e,t)=>e.ref.num-t.ref.num))}(i,a,Q);let u=e.length;const d=e.at(-1);if(10!==d&&13!==d){Q.push("\n");u+=1}for(const{data:e}of E)null!==e&&Q.push(e);await(h?async function getXRefStreamTable(e,t,i,a,s){const r=[];let n=0,g=0;for(const{ref:e,data:a}of i){let i;n=Math.max(n,t);if(null!==a){i=Math.min(e.gen,65535);r.push([1,t,i]);t+=a.length}else{i=Math.min(e.gen+1,65535);r.push([0,0,i])}g=Math.max(g,i)}a.set("Index",getIndexes(i));const o=[1,getSizeInBytes(n),getSizeInBytes(g)];a.set("W",o);computeIDs(t,e,a);const c=o.reduce(((e,t)=>e+t),0),C=new Uint8Array(c*r.length),h=new Stream(C);h.dict=a;let l=0;for(const[e,t,i]of r){l=writeInt(e,o[0],l,C);l=writeInt(t,o[1],l,C);l=writeInt(i,o[2],l,C)}await writeObject(e.newRef,h,s,{});s.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q):async function getXRefTable(e,t,i,a,s){s.push("xref\n");const r=getIndexes(i);let n=0;for(const{ref:e,data:a}of i){if(e.num===r[n]){s.push(`${r[n]} ${r[n+1]}\n`);n+=2}if(null!==a){s.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=a.length}else s.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,a);s.push("trailer\n");await writeDict(a,s);s.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,l,Q));const f=Q.reduce(((e,t)=>e+t.length),e.length),p=new Uint8Array(f);p.set(e);let m=e.length;for(const e of Q){writeString(e,m,p);m+=e.length}return p}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const i=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(i);return i}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,i){this._msgHandler=i;this.onProgress=null;const a=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=a.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!t&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let i=!1;e.on("test",(t=>{if(!i){i=!0;e.send("test",t instanceof Uint8Array)}}));e.on("configure",(e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(gt=e)}(e.verbosity)}));e.on("GetDocRequest",(e=>this.createDocumentHandler(e,t)))}static createDocumentHandler(e,t){let i,a=!1,s=null;const r=new Set,n=getVerbosityLevel(),{docId:g,apiVersion:o}=e,c="4.10.38";if(o!==c)throw new Error(`The API version "${o}" does not match the Worker version "${c}".`);const C=[];for(const e in[])C.push(e);if(C.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+C.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const h=g+"_worker";let l=new MessageHandler(h,g,t);function ensureNotTerminated(){if(a)throw new Error("Worker was terminated")}function startWorkerTask(e){r.add(e)}function finishWorkerTask(e){e.finish();r.delete(e)}async function loadDocument(e){await i.ensureDoc("checkHeader");await i.ensureDoc("parseStartXRef");await i.ensureDoc("parse",[e]);await i.ensureDoc("checkFirstPage",[e]);await i.ensureDoc("checkLastPage",[e]);const t=await i.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaFonts");startWorkerTask(e);await Promise.all([i.loadXfaFonts(l,e).catch((e=>{})).then((()=>finishWorkerTask(e))),i.loadXfaImages()])}const[a,s]=await Promise.all([i.ensureDoc("numPages"),i.ensureDoc("fingerprints")]);return{numPages:a,fingerprints:s,htmlForXfa:t?await i.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();l.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);l.sendWithPromise("PasswordRequest",e).then((function({password:e}){finishWorkerTask(t);i.updatePassword(e);pdfManagerReady()})).catch((function(){finishWorkerTask(t);l.send("DocException",e)}))}else l.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,(function(e){ensureNotTerminated();e instanceof XRefParseException?i.requestLoadedStream().then((function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)})):onFailure(e)}))}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:i,rangeChunkSize:a,length:r,docBaseUrl:n,enableXfa:o,evaluatorOptions:c}){const C={source:null,disableAutoFetch:i,docBaseUrl:n,docId:g,enableXfa:o,evaluatorOptions:c,handler:l,length:r,password:t,rangeChunkSize:a};if(e){C.source=e;return new LocalPdfManager(C)}const h=new PDFWorkerStream(l),Q=h.getFullReader(),E=Promise.withResolvers();let u,d=[],f=0;Q.headersReady.then((function(){if(Q.isRangeSupported){C.source=h;C.length=Q.contentLength;C.disableAutoFetch||=Q.isStreamingSupported;u=new NetworkPdfManager(C);for(const e of d)u.sendProgressiveData(e);d=[];E.resolve(u);s=null}})).catch((function(e){E.reject(e);s=null}));new Promise((function(e,t){const readChunk=function({value:e,done:i}){try{ensureNotTerminated();if(i){if(!u){const e=arrayBuffersToBytes(d);d=[];r&&e.length!==r&&warn("reported HTTP length is different from actual");C.source=e;u=new LocalPdfManager(C);E.resolve(u)}s=null;return}f+=e.byteLength;Q.isStreamingSupported||l.send("DocProgress",{loaded:f,total:Math.max(f,Q.contentLength||0)});u?u.sendProgressiveData(e):d.push(e);Q.read().then(readChunk,t)}catch(e){t(e)}};Q.read().then(readChunk,t)})).catch((function(e){E.reject(e);s=null}));s=e=>{h.cancelAllRequests(e)};return E.promise})(e).then((function(e){if(a){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}i=e;i.requestLoadedStream(!0).then((e=>{l.send("DataLoaded",{length:e.bytes.byteLength})}))})).then(pdfManagerReady,onFailure)}l.on("GetPage",(function(e){return i.getPage(e.pageIndex).then((function(e){return Promise.all([i.ensure(e,"rotate"),i.ensure(e,"ref"),i.ensure(e,"userUnit"),i.ensure(e,"view")]).then((function([e,t,i,a]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:i,view:a}}))}))}));l.on("GetPageIndex",(function(e){const t=Ref.get(e.num,e.gen);return i.ensureCatalog("getPageIndex",[t])}));l.on("GetDestinations",(function(e){return i.ensureCatalog("destinations")}));l.on("GetDestination",(function(e){return i.ensureCatalog("getDestination",[e.id])}));l.on("GetPageLabels",(function(e){return i.ensureCatalog("pageLabels")}));l.on("GetPageLayout",(function(e){return i.ensureCatalog("pageLayout")}));l.on("GetPageMode",(function(e){return i.ensureCatalog("pageMode")}));l.on("GetViewerPreferences",(function(e){return i.ensureCatalog("viewerPreferences")}));l.on("GetOpenAction",(function(e){return i.ensureCatalog("openAction")}));l.on("GetAttachments",(function(e){return i.ensureCatalog("attachments")}));l.on("GetDocJSActions",(function(e){return i.ensureCatalog("jsActions")}));l.on("GetPageJSActions",(function({pageIndex:e}){return i.getPage(e).then((function(e){return i.ensure(e,"jsActions")}))}));l.on("GetOutline",(function(e){return i.ensureCatalog("documentOutline")}));l.on("GetOptionalContentConfig",(function(e){return i.ensureCatalog("optionalContentConfig")}));l.on("GetPermissions",(function(e){return i.ensureCatalog("permissions")}));l.on("GetMetadata",(function(e){return Promise.all([i.ensureDoc("documentInfo"),i.ensureCatalog("metadata")])}));l.on("GetMarkInfo",(function(e){return i.ensureCatalog("markInfo")}));l.on("GetData",(function(e){return i.requestLoadedStream().then((function(e){return e.bytes}))}));l.on("GetAnnotations",(function({pageIndex:e,intent:t}){return i.getPage(e).then((function(i){const a=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(a);return i.getAnnotationsData(l,a,t).then((e=>{finishWorkerTask(a);return e}),(e=>{finishWorkerTask(a);throw e}))}))}));l.on("GetFieldObjects",(function(e){return i.ensureDoc("fieldObjects").then((e=>e?.allFields||null))}));l.on("HasJSActions",(function(e){return i.ensureDoc("hasJSActions")}));l.on("GetCalculationOrderIds",(function(e){return i.ensureDoc("calculationOrderIds")}));l.on("SaveDocument",(async function({isPureXfa:e,numPages:t,annotationStorage:a,filename:s}){const r=[i.requestLoadedStream(),i.ensureCatalog("acroForm"),i.ensureCatalog("acroFormRef"),i.ensureDoc("startXRef"),i.ensureDoc("xref"),i.ensureDoc("linearization"),i.ensureCatalog("structTreeRoot")],n=new RefSetCache,g=[],o=e?null:getNewAnnotationsMap(a),[c,C,h,Q,E,u,d]=await Promise.all(r),f=E.trailer.getRaw("Root")||null;let p;if(o){d?await d.canUpdateStructTree({pdfManager:i,xref:E,newAnnotationsByPage:o})&&(p=d):await StructTreeRoot.canCreateStructureTree({catalogRef:f,pdfManager:i,newAnnotationsByPage:o})&&(p=null);const e=AnnotationFactory.generateImages(a.values(),E,i.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===p?g:[];for(const[a,s]of o)t.push(i.getPage(a).then((t=>{const i=new WorkerTask(`Save (editor): page ${a}`);startWorkerTask(i);return t.saveNewAnnotations(l,i,s,e,n).finally((function(){finishWorkerTask(i)}))})));null===p?g.push(Promise.all(t).then((async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:o,xref:E,catalogRef:f,pdfManager:i,changes:n})}))):p&&g.push(Promise.all(t).then((async()=>{await p.updateStructureTree({newAnnotationsByPage:o,pdfManager:i,changes:n})})))}if(e)g.push(i.serializeXfaData(a));else for(let e=0;ee.needAppearances)),D=C instanceof Dict&&C.get("XFA")||null;let b=null,F=!1;if(Array.isArray(D)){for(let e=0,t=D.length;e{E.resetNewTemporaryRef()}))}));l.on("GetOperatorList",(function(e,t){const a=e.pageIndex;i.getPage(a).then((function(i){const s=new WorkerTask(`GetOperatorList: page ${a}`);startWorkerTask(s);const r=n>=yA?Date.now():0;i.getOperatorList({handler:l,sink:t,task:s,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds}).then((function(e){finishWorkerTask(s);r&&info(`page=${a+1} - getOperatorList: time=${Date.now()-r}ms, len=${e.length}`);t.close()}),(function(e){finishWorkerTask(s);s.terminated||t.error(e)}))}))}));l.on("GetTextContent",(function(e,t){const{pageIndex:a,includeMarkedContent:s,disableNormalization:r}=e;i.getPage(a).then((function(e){const i=new WorkerTask("GetTextContent: page "+a);startWorkerTask(i);const g=n>=yA?Date.now():0;e.extractTextContent({handler:l,task:i,sink:t,includeMarkedContent:s,disableNormalization:r}).then((function(){finishWorkerTask(i);g&&info(`page=${a+1} - getTextContent: time=`+(Date.now()-g)+"ms");t.close()}),(function(e){finishWorkerTask(i);i.terminated||t.error(e)}))}))}));l.on("GetStructTree",(function(e){return i.getPage(e.pageIndex).then((function(e){return i.ensure(e,"getStructTree")}))}));l.on("FontFallback",(function(e){return i.fontFallback(e.id,l)}));l.on("Cleanup",(function(e){return i.cleanup(!0)}));l.on("Terminate",(function(e){a=!0;const t=[];if(i){i.terminate(new AbortException("Worker was terminated."));const e=i.cleanup();t.push(e);i=null}else clearGlobalCaches();s?.(new AbortException("Worker was terminated."));for(const e of r){t.push(e.finished);e.terminate()}return Promise.all(t).then((function(){l.destroy();l=null}))}));l.on("Ready",(function(t){setupDoc(e);e=null}));return h}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}var Qg=__webpack_exports__.WorkerMessageHandler;export{Qg as WorkerMessageHandler}; \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/loading-icon.gif b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/loading-icon.gif rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/web/images/loading-icon.gif diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css similarity index 64% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css index 4639f999b07..baf50d36823 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.css +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.css @@ -26,19 +26,13 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) .messageBar{ +.messageBar{ --message-bar-close-button-hover-bg-color:rgb(251 251 254 / 0.14); --message-bar-close-button-active-bg-color:rgb(251 251 254 / 0.21); --message-bar-close-button-focus-bg-color:rgb(251 251 254 / 0.07); } } -:where(html.is-dark) .messageBar{ - --message-bar-close-button-hover-bg-color:rgb(251 251 254 / 0.14); - --message-bar-close-button-active-bg-color:rgb(251 251 254 / 0.21); - --message-bar-close-button-focus-bg-color:rgb(251 251 254 / 0.07); -} - @media screen and (forced-colors: active){ .messageBar{ @@ -170,7 +164,7 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) #editorUndoBar{ +#editorUndoBar{ --text-primary-color:#fbfbfe; --message-bar-icon-color:#73a7f3; @@ -183,18 +177,6 @@ } } -:where(html.is-dark) #editorUndoBar{ - --text-primary-color:#fbfbfe; - - --message-bar-icon-color:#73a7f3; - --message-bar-bg-color:#003070; - --message-bar-border-color:rgb(255 255 255 / 0.08); - - --undo-button-bg-color:rgb(255 255 255 / 0.08); - --undo-button-bg-color-hover:rgb(255 255 255 / 0.14); - --undo-button-bg-color-active:rgb(255 255 255 / 0.21); -} - @media screen and (forced-colors: active){ #editorUndoBar{ @@ -303,7 +285,7 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) .dialog{ +.dialog{ --dialog-bg-color:#1c1b22; --dialog-border-color:#1c1b22; --dialog-shadow:0 2px 14px 0 #15141a; @@ -327,29 +309,6 @@ } } -:where(html.is-dark) .dialog{ - --dialog-bg-color:#1c1b22; - --dialog-border-color:#1c1b22; - --dialog-shadow:0 2px 14px 0 #15141a; - --text-primary-color:#fbfbfe; - --text-secondary-color:#cfcfd8; - --focus-ring-color:#0df; - --hover-filter:brightness(1.4); - --link-fg-color:#0df; - --link-hover-fg-color:#80ebff; - --separator-color:#52525e; - - --textarea-bg-color:#42414d; - - --radio-bg-color:#2b2a33; - --radio-checked-bg-color:#15141a; - --radio-checked-border-color:#0df; - - --button-secondary-bg-color:#2b2a33; - --button-primary-bg-color:#0df; - --button-primary-fg-color:#15141a; -} - @media screen and (forced-colors: active){ .dialog{ @@ -564,7 +523,7 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) :is(.dialog .mainContainer) .messageBar{ +:is(.dialog .mainContainer) .messageBar{ --message-bar-bg-color:#5a3100; --message-bar-fg-color:#fbfbfe; --message-bar-border-color:rgb(255 255 255 / 0.08); @@ -572,13 +531,6 @@ } } -:where(html.is-dark) :is(.dialog .mainContainer) .messageBar{ - --message-bar-bg-color:#5a3100; - --message-bar-fg-color:#fbfbfe; - --message-bar-border-color:rgb(255 255 255 / 0.08); - --message-bar-icon-color:#e49c49; - } - @media screen and (forced-colors: active){ :is(.dialog .mainContainer) .messageBar{ @@ -1555,7 +1507,7 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) .toggle-button{ +.toggle-button{ --button-background-color:color-mix(in srgb, currentColor 7%, transparent); --button-background-color-hover:color-mix( in srgb, @@ -1575,25 +1527,6 @@ } } -:where(html.is-dark) .toggle-button{ - --button-background-color:color-mix(in srgb, currentColor 7%, transparent); - --button-background-color-hover:color-mix( - in srgb, - currentColor 14%, - transparent - ); - --button-background-color-active:color-mix( - in srgb, - currentColor 21%, - transparent - ); - --color-accent-primary:#0df; - --color-accent-primary-hover:#80ebff; - --color-accent-primary-active:#aaf2ff; - --border-interactive-color:#bfbfc9; - --color-canvas:#1c1b22; -} - @media (forced-colors: active){ .toggle-button{ @@ -1965,7 +1898,7 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) :is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ +:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ --editor-toolbar-bg-color:#2b2a33; --editor-toolbar-fg-color:#fbfbfe; --editor-toolbar-hover-bg-color:#52525e; @@ -1975,15 +1908,6 @@ } } -:where(html.is-dark) :is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ - --editor-toolbar-bg-color:#2b2a33; - --editor-toolbar-fg-color:#fbfbfe; - --editor-toolbar-hover-bg-color:#52525e; - --editor-toolbar-focus-outline-color:#0df; - --alt-text-done-color:#54ffbd; - --alt-text-warning-color:#80ebff; - } - @media screen and (forced-colors: active){ :is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar{ @@ -2220,19 +2144,13 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) .show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ +.show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ --alt-text-tooltip-bg:#1c1b22; --alt-text-tooltip-fg:#fbfbfe; --alt-text-tooltip-shadow:0px 2px 6px 0px #15141a; } } -:where(html.is-dark) .show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ - --alt-text-tooltip-bg:#1c1b22; - --alt-text-tooltip-fg:#fbfbfe; - --alt-text-tooltip-shadow:0px 2px 6px 0px #15141a; - } - @media screen and (forced-colors: active){ .show:is(:is(:is(:is(:is(.annotationEditorLayer :is(.freeTextEditor,.inkEditor,.stampEditor,.highlightEditor),.textLayer) .editToolbar) .buttons) .altText) .tooltip){ @@ -2352,19 +2270,13 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) :is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ +:is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ --no-alt-text-badge-border-color:#52525e; --no-alt-text-badge-bg-color:#fbfbfe; --no-alt-text-badge-fg-color:#15141a; } } -:where(html.is-dark) :is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ - --no-alt-text-badge-border-color:#52525e; - --no-alt-text-badge-bg-color:#fbfbfe; - --no-alt-text-badge-fg-color:#15141a; - } - @media screen and (forced-colors: active){ :is(.annotationEditorLayer .stampEditor) .noAltTextBadge{ @@ -2600,15 +2512,11 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) .dialog.newAltText{ +.dialog.newAltText{ --preview-image-bg-color:#2b2a33; } } -:where(html.is-dark) .dialog.newAltText{ - --preview-image-bg-color:#2b2a33; -} - @media screen and (forced-colors: active){ .dialog.newAltText{ @@ -2803,19 +2711,13 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) .colorPicker{ +.colorPicker{ --hover-outline-color:#80ebff; --selected-outline-color:#aaf2ff; --swatch-border-color:#52525e; } } -:where(html.is-dark) .colorPicker{ - --hover-outline-color:#80ebff; - --selected-outline-color:#aaf2ff; - --swatch-border-color:#52525e; -} - @media screen and (forced-colors: active){ .colorPicker{ @@ -3052,15 +2954,11 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) :is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ +:is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ --example-color:#80808e; } } -:where(html.is-dark) :is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ - --example-color:#80808e; - } - @media screen and (forced-colors: active){ :is(#highlightParamsToolbarContainer #editorHighlightThickness) .thicknessPicker{ @@ -3104,15 +3002,11 @@ @media (prefers-color-scheme: dark){ -:where(html:not(.is-light)) :is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ +:is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ --divider-color:#8f8f9d; } } -:where(html.is-dark) :is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ - --divider-color:#8f8f9d; - } - @media screen and (forced-colors: active){ :is(#highlightParamsToolbarContainer #editorHighlightVisibility) .divider{ @@ -3301,6 +3195,15 @@ border:none; } +.pdfViewer.singlePageView{ + display:inline-block; +} + +.pdfViewer.singlePageView .page{ + margin:0; + border:none; +} + .pdfViewer:is(.scrollHorizontal, .scrollWrapped), .spread{ margin-inline:3.5px; @@ -3369,1825 +3272,3 @@ margin:0 auto; border:2px solid transparent; } - -:root{ - --dir-factor:1; - --inline-start:left; - --inline-end:right; - - --sidebar-width:200px; - --sidebar-transition-duration:200ms; - --sidebar-transition-timing-function:ease; - - --toolbar-height:32px; - --toolbar-horizontal-padding:1px; - --toolbar-vertical-padding:2px; - --icon-size:16px; - - --toolbar-icon-opacity:0.7; - --doorhanger-icon-opacity:0.9; - --doorhanger-height:8px; - - --main-color:rgb(12 12 13); - --body-bg-color:rgb(212 212 215); - --progressBar-color:rgb(10 132 255); - --progressBar-bg-color:rgb(221 221 222); - --progressBar-blend-color:rgb(116 177 239); - --scrollbar-color:auto; - --scrollbar-bg-color:auto; - --toolbar-icon-bg-color:rgb(0 0 0); - --toolbar-icon-hover-bg-color:rgb(0 0 0); - - --sidebar-narrow-bg-color:rgb(212 212 215 / 0.9); - --sidebar-toolbar-bg-color:rgb(245 246 247); - --toolbar-bg-color:rgb(249 249 250); - --toolbar-border-color:rgb(184 184 184); - --toolbar-box-shadow:0 1px 0 var(--toolbar-border-color); - --toolbar-border-bottom:none; - --toolbarSidebar-box-shadow:inset calc(-1px * var(--dir-factor)) 0 0 rgb(0 0 0 / 0.25), 0 1px 0 rgb(0 0 0 / 0.15), 0 0 1px rgb(0 0 0 / 0.1); - --toolbarSidebar-border-bottom:none; - --button-hover-color:rgb(221 222 223); - --toggled-btn-color:rgb(0 0 0); - --toggled-btn-bg-color:rgb(0 0 0 / 0.3); - --toggled-hover-active-btn-color:rgb(0 0 0 / 0.4); - --toggled-hover-btn-outline:none; - --dropdown-btn-bg-color:rgb(215 215 219); - --dropdown-btn-border:none; - --separator-color:rgb(0 0 0 / 0.3); - --field-color:rgb(6 6 6); - --field-bg-color:rgb(255 255 255); - --field-border-color:rgb(187 187 188); - --treeitem-color:rgb(0 0 0 / 0.8); - --treeitem-bg-color:rgb(0 0 0 / 0.15); - --treeitem-hover-color:rgb(0 0 0 / 0.9); - --treeitem-selected-color:rgb(0 0 0 / 0.9); - --treeitem-selected-bg-color:rgb(0 0 0 / 0.25); - --thumbnail-hover-color:rgb(0 0 0 / 0.1); - --thumbnail-selected-color:rgb(0 0 0 / 0.2); - --doorhanger-bg-color:rgb(255 255 255); - --doorhanger-border-color:rgb(12 12 13 / 0.2); - --doorhanger-hover-color:rgb(12 12 13); - --doorhanger-hover-bg-color:rgb(237 237 237); - --doorhanger-separator-color:rgb(222 222 222); - --dialog-button-border:none; - --dialog-button-bg-color:rgb(12 12 13 / 0.1); - --dialog-button-hover-bg-color:rgb(12 12 13 / 0.3); - - --loading-icon:url(images/loading.svg); - --treeitem-expanded-icon:url(images/treeitem-expanded.svg); - --treeitem-collapsed-icon:url(images/treeitem-collapsed.svg); - --toolbarButton-editorFreeText-icon:url(images/toolbarButton-editorFreeText.svg); - --toolbarButton-editorHighlight-icon:url(images/toolbarButton-editorHighlight.svg); - --toolbarButton-editorInk-icon:url(images/toolbarButton-editorInk.svg); - --toolbarButton-editorStamp-icon:url(images/toolbarButton-editorStamp.svg); - --toolbarButton-menuArrow-icon:url(images/toolbarButton-menuArrow.svg); - --toolbarButton-sidebarToggle-icon:url(images/toolbarButton-sidebarToggle.svg); - --toolbarButton-secondaryToolbarToggle-icon:url(images/toolbarButton-secondaryToolbarToggle.svg); - --toolbarButton-pageUp-icon:url(images/toolbarButton-pageUp.svg); - --toolbarButton-pageDown-icon:url(images/toolbarButton-pageDown.svg); - --toolbarButton-zoomOut-icon:url(images/toolbarButton-zoomOut.svg); - --toolbarButton-zoomIn-icon:url(images/toolbarButton-zoomIn.svg); - --toolbarButton-presentationMode-icon:url(images/toolbarButton-presentationMode.svg); - --toolbarButton-print-icon:url(images/toolbarButton-print.svg); - --toolbarButton-openFile-icon:url(images/toolbarButton-openFile.svg); - --toolbarButton-download-icon:url(images/toolbarButton-download.svg); - --toolbarButton-bookmark-icon:url(images/toolbarButton-bookmark.svg); - --toolbarButton-viewThumbnail-icon:url(images/toolbarButton-viewThumbnail.svg); - --toolbarButton-viewOutline-icon:url(images/toolbarButton-viewOutline.svg); - --toolbarButton-viewAttachments-icon:url(images/toolbarButton-viewAttachments.svg); - --toolbarButton-viewLayers-icon:url(images/toolbarButton-viewLayers.svg); - --toolbarButton-currentOutlineItem-icon:url(images/toolbarButton-currentOutlineItem.svg); - --toolbarButton-search-icon:url(images/toolbarButton-search.svg); - --findbarButton-previous-icon:url(images/findbarButton-previous.svg); - --findbarButton-next-icon:url(images/findbarButton-next.svg); - --secondaryToolbarButton-firstPage-icon:url(images/secondaryToolbarButton-firstPage.svg); - --secondaryToolbarButton-lastPage-icon:url(images/secondaryToolbarButton-lastPage.svg); - --secondaryToolbarButton-rotateCcw-icon:url(images/secondaryToolbarButton-rotateCcw.svg); - --secondaryToolbarButton-rotateCw-icon:url(images/secondaryToolbarButton-rotateCw.svg); - --secondaryToolbarButton-selectTool-icon:url(images/secondaryToolbarButton-selectTool.svg); - --secondaryToolbarButton-handTool-icon:url(images/secondaryToolbarButton-handTool.svg); - --secondaryToolbarButton-scrollPage-icon:url(images/secondaryToolbarButton-scrollPage.svg); - --secondaryToolbarButton-scrollVertical-icon:url(images/secondaryToolbarButton-scrollVertical.svg); - --secondaryToolbarButton-scrollHorizontal-icon:url(images/secondaryToolbarButton-scrollHorizontal.svg); - --secondaryToolbarButton-scrollWrapped-icon:url(images/secondaryToolbarButton-scrollWrapped.svg); - --secondaryToolbarButton-spreadNone-icon:url(images/secondaryToolbarButton-spreadNone.svg); - --secondaryToolbarButton-spreadOdd-icon:url(images/secondaryToolbarButton-spreadOdd.svg); - --secondaryToolbarButton-spreadEven-icon:url(images/secondaryToolbarButton-spreadEven.svg); - --secondaryToolbarButton-imageAltTextSettings-icon:var( - --toolbarButton-editorStamp-icon - ); - --secondaryToolbarButton-documentProperties-icon:url(images/secondaryToolbarButton-documentProperties.svg); - --editorParams-stampAddImage-icon:url(images/toolbarButton-zoomIn.svg); -} - -[dir="rtl"]:root{ - --dir-factor:-1; - --inline-start:right; - --inline-end:left; -} - -@media (prefers-color-scheme: dark){ - :root:where(:not(.is-light)){ - --main-color:rgb(249 249 250); - --body-bg-color:rgb(42 42 46); - --progressBar-color:rgb(0 96 223); - --progressBar-bg-color:rgb(40 40 43); - --progressBar-blend-color:rgb(20 68 133); - --scrollbar-color:rgb(121 121 123); - --scrollbar-bg-color:rgb(35 35 39); - --toolbar-icon-bg-color:rgb(255 255 255); - --toolbar-icon-hover-bg-color:rgb(255 255 255); - - --sidebar-narrow-bg-color:rgb(42 42 46 / 0.9); - --sidebar-toolbar-bg-color:rgb(50 50 52); - --toolbar-bg-color:rgb(56 56 61); - --toolbar-border-color:rgb(12 12 13); - --button-hover-color:rgb(102 102 103); - --toggled-btn-color:rgb(255 255 255); - --toggled-btn-bg-color:rgb(0 0 0 / 0.3); - --toggled-hover-active-btn-color:rgb(0 0 0 / 0.4); - --dropdown-btn-bg-color:rgb(74 74 79); - --separator-color:rgb(0 0 0 / 0.3); - --field-color:rgb(250 250 250); - --field-bg-color:rgb(64 64 68); - --field-border-color:rgb(115 115 115); - --treeitem-color:rgb(255 255 255 / 0.8); - --treeitem-bg-color:rgb(255 255 255 / 0.15); - --treeitem-hover-color:rgb(255 255 255 / 0.9); - --treeitem-selected-color:rgb(255 255 255 / 0.9); - --treeitem-selected-bg-color:rgb(255 255 255 / 0.25); - --thumbnail-hover-color:rgb(255 255 255 / 0.1); - --thumbnail-selected-color:rgb(255 255 255 / 0.2); - --doorhanger-bg-color:rgb(74 74 79); - --doorhanger-border-color:rgb(39 39 43); - --doorhanger-hover-color:rgb(249 249 250); - --doorhanger-hover-bg-color:rgb(93 94 98); - --doorhanger-separator-color:rgb(92 92 97); - --dialog-button-bg-color:rgb(92 92 97); - --dialog-button-hover-bg-color:rgb(115 115 115); - } -} - -:root:where(.is-dark){ - --main-color:rgb(249 249 250); - --body-bg-color:rgb(42 42 46); - --progressBar-color:rgb(0 96 223); - --progressBar-bg-color:rgb(40 40 43); - --progressBar-blend-color:rgb(20 68 133); - --scrollbar-color:rgb(121 121 123); - --scrollbar-bg-color:rgb(35 35 39); - --toolbar-icon-bg-color:rgb(255 255 255); - --toolbar-icon-hover-bg-color:rgb(255 255 255); - - --sidebar-narrow-bg-color:rgb(42 42 46 / 0.9); - --sidebar-toolbar-bg-color:rgb(50 50 52); - --toolbar-bg-color:rgb(56 56 61); - --toolbar-border-color:rgb(12 12 13); - --button-hover-color:rgb(102 102 103); - --toggled-btn-color:rgb(255 255 255); - --toggled-btn-bg-color:rgb(0 0 0 / 0.3); - --toggled-hover-active-btn-color:rgb(0 0 0 / 0.4); - --dropdown-btn-bg-color:rgb(74 74 79); - --separator-color:rgb(0 0 0 / 0.3); - --field-color:rgb(250 250 250); - --field-bg-color:rgb(64 64 68); - --field-border-color:rgb(115 115 115); - --treeitem-color:rgb(255 255 255 / 0.8); - --treeitem-bg-color:rgb(255 255 255 / 0.15); - --treeitem-hover-color:rgb(255 255 255 / 0.9); - --treeitem-selected-color:rgb(255 255 255 / 0.9); - --treeitem-selected-bg-color:rgb(255 255 255 / 0.25); - --thumbnail-hover-color:rgb(255 255 255 / 0.1); - --thumbnail-selected-color:rgb(255 255 255 / 0.2); - --doorhanger-bg-color:rgb(74 74 79); - --doorhanger-border-color:rgb(39 39 43); - --doorhanger-hover-color:rgb(249 249 250); - --doorhanger-hover-bg-color:rgb(93 94 98); - --doorhanger-separator-color:rgb(92 92 97); - --dialog-button-bg-color:rgb(92 92 97); - --dialog-button-hover-bg-color:rgb(115 115 115); - } - -@media screen and (forced-colors: active){ - :root{ - --button-hover-color:Highlight; - --doorhanger-hover-bg-color:Highlight; - --toolbar-icon-opacity:1; - --toolbar-icon-bg-color:ButtonText; - --toolbar-icon-hover-bg-color:ButtonFace; - --toggled-hover-active-btn-color:ButtonText; - --toggled-hover-btn-outline:2px solid ButtonBorder; - --toolbar-border-color:CanvasText; - --toolbar-border-bottom:1px solid var(--toolbar-border-color); - --toolbar-box-shadow:none; - --toggled-btn-color:HighlightText; - --toggled-btn-bg-color:LinkText; - --doorhanger-hover-color:ButtonFace; - --doorhanger-border-color-whcm:1px solid ButtonText; - --doorhanger-triangle-opacity-whcm:0; - --dialog-button-border:1px solid Highlight; - --dialog-button-hover-bg-color:Highlight; - --dialog-button-hover-color:ButtonFace; - --dropdown-btn-border:1px solid ButtonText; - --field-border-color:ButtonText; - --main-color:CanvasText; - --separator-color:GrayText; - --doorhanger-separator-color:GrayText; - --toolbarSidebar-box-shadow:none; - --toolbarSidebar-border-bottom:1px solid var(--toolbar-border-color); - } -} - -@media screen and (prefers-reduced-motion: reduce){ - :root{ - --sidebar-transition-duration:0; - } -} - -@keyframes progressIndeterminate{ - 0%{ - transform:translateX(calc(-142px * var(--dir-factor))); - } - - 100%{ - transform:translateX(0); - } -} - -html[data-toolbar-density="compact"]{ - --toolbar-height:30px; - } - -html[data-toolbar-density="touch"]{ - --toolbar-height:44px; - } - -html, -body{ - height:100%; - width:100%; -} - -body{ - margin:0; - background-color:var(--body-bg-color); - scrollbar-color:var(--scrollbar-color) var(--scrollbar-bg-color); -} - -body.wait::before{ - content:""; - position:fixed; - width:100%; - height:100%; - z-index:100000; - cursor:wait; - } - -.hidden, -[hidden]{ - display:none !important; -} - -#viewerContainer.pdfPresentationMode:fullscreen{ - top:0; - background-color:rgb(0 0 0); - width:100%; - height:100%; - overflow:hidden; - cursor:none; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -.pdfPresentationMode:fullscreen section:not([data-internal-link]){ - pointer-events:none; -} - -.pdfPresentationMode:fullscreen .textLayer span{ - cursor:none; -} - -.pdfPresentationMode.pdfPresentationModeControls > *, -.pdfPresentationMode.pdfPresentationModeControls .textLayer span{ - cursor:default; -} - -#outerContainer{ - width:100%; - height:100%; - position:relative; - margin:0; -} - -#sidebarContainer{ - position:absolute; - inset-block:var(--toolbar-height) 0; - inset-inline-start:calc(-1 * var(--sidebar-width)); - width:var(--sidebar-width); - visibility:hidden; - z-index:1; - font:message-box; - border-top:1px solid transparent; - border-inline-end:var(--doorhanger-border-color-whcm); - transition-property:inset-inline-start; - transition-duration:var(--sidebar-transition-duration); - transition-timing-function:var(--sidebar-transition-timing-function); -} - -#outerContainer:is(.sidebarMoving, .sidebarOpen) #sidebarContainer{ - visibility:visible; -} - -#outerContainer.sidebarOpen #sidebarContainer{ - inset-inline-start:0; -} - -#mainContainer{ - position:absolute; - inset:0; - min-width:350px; - margin:0; - display:flex; - flex-direction:column; -} - -#sidebarContent{ - inset-block:var(--toolbar-height) 0; - inset-inline-start:0; - overflow:auto; - position:absolute; - width:100%; - box-shadow:inset calc(-1px * var(--dir-factor)) 0 0 rgb(0 0 0 / 0.25); -} - -#viewerContainer{ - overflow:auto; - position:absolute; - inset:var(--toolbar-height) 0 0; - outline:none; - z-index:0; -} - -#viewerContainer:not(.pdfPresentationMode){ - transition-duration:var(--sidebar-transition-duration); - transition-timing-function:var(--sidebar-transition-timing-function); -} - -#outerContainer.sidebarOpen #viewerContainer:not(.pdfPresentationMode){ - inset-inline-start:var(--sidebar-width); - transition-property:inset-inline-start; -} - -#sidebarContainer :is(input, button, select){ - font:message-box; -} - -.toolbar{ - z-index:2; -} - -#toolbarSidebar{ - width:100%; - height:var(--toolbar-height); - background-color:var(--sidebar-toolbar-bg-color); - box-shadow:var(--toolbarSidebar-box-shadow); - border-bottom:var(--toolbarSidebar-border-bottom); - padding:var(--toolbar-vertical-padding) var(--toolbar-horizontal-padding); - justify-content:space-between; -} - -#toolbarSidebar #toolbarSidebarLeft{ - width:auto; - height:100%; - } - -:is(#toolbarSidebar #toolbarSidebarLeft) #viewThumbnail::before{ - -webkit-mask-image:var(--toolbarButton-viewThumbnail-icon); - mask-image:var(--toolbarButton-viewThumbnail-icon); - } - -:is(#toolbarSidebar #toolbarSidebarLeft) #viewOutline::before{ - -webkit-mask-image:var(--toolbarButton-viewOutline-icon); - mask-image:var(--toolbarButton-viewOutline-icon); - transform:scaleX(var(--dir-factor)); - } - -:is(#toolbarSidebar #toolbarSidebarLeft) #viewAttachments::before{ - -webkit-mask-image:var(--toolbarButton-viewAttachments-icon); - mask-image:var(--toolbarButton-viewAttachments-icon); - } - -:is(#toolbarSidebar #toolbarSidebarLeft) #viewLayers::before{ - -webkit-mask-image:var(--toolbarButton-viewLayers-icon); - mask-image:var(--toolbarButton-viewLayers-icon); - } - -#toolbarSidebar #toolbarSidebarRight{ - width:auto; - height:100%; - padding-inline-end:2px; - } - -#sidebarResizer{ - position:absolute; - inset-block:0; - inset-inline-end:-6px; - width:6px; - z-index:200; - cursor:ew-resize; -} - -#outerContainer.sidebarOpen #loadingBar{ - inset-inline-start:var(--sidebar-width); -} - -#outerContainer.sidebarResizing - :is(#sidebarContainer, #viewerContainer, #loadingBar){ - transition-duration:0s; -} - -.doorHanger, -.doorHangerRight{ - border-radius:2px; - box-shadow:0 1px 5px var(--doorhanger-border-color), 0 0 0 1px var(--doorhanger-border-color); - border:var(--doorhanger-border-color-whcm); - background-color:var(--doorhanger-bg-color); - inset-block-start:calc(100% + var(--doorhanger-height) - 2px); -} - -:is(.doorHanger,.doorHangerRight)::after,:is(.doorHanger,.doorHangerRight)::before{ - bottom:100%; - border-style:solid; - border-color:transparent; - content:""; - height:0; - width:0; - position:absolute; - pointer-events:none; - opacity:var(--doorhanger-triangle-opacity-whcm); - } - -:is(.doorHanger,.doorHangerRight)::before{ - border-width:calc(var(--doorhanger-height) + 2px); - border-bottom-color:var(--doorhanger-border-color); - } - -:is(.doorHanger,.doorHangerRight)::after{ - border-width:var(--doorhanger-height); - } - -.doorHangerRight{ - inset-inline-end:calc(50% - var(--doorhanger-height) - 1px); -} - -.doorHangerRight::before{ - inset-inline-end:-1px; - } - -.doorHangerRight::after{ - border-bottom-color:var(--doorhanger-bg-color); - inset-inline-end:1px; - } - -.doorHanger{ - inset-inline-start:calc(50% - var(--doorhanger-height) - 1px); -} - -.doorHanger::before{ - inset-inline-start:-1px; - } - -.doorHanger::after{ - border-bottom-color:var(--toolbar-bg-color); - inset-inline-start:1px; - } - -.dialogButton{ - border:none; - background:none; - width:28px; - height:28px; - outline:none; -} - -.dialogButton:is(:hover, :focus-visible){ - background-color:var(--dialog-button-hover-bg-color); -} - -.dialogButton:is(:hover, :focus-visible) > span{ - color:var(--dialog-button-hover-color); -} - -.splitToolbarButtonSeparator{ - float:var(--inline-start); - width:0; - height:62%; - border-left:1px solid var(--separator-color); - border-right:none; -} - -.dialogButton{ - min-width:16px; - margin:2px 1px; - padding:2px 6px 0; - border:none; - border-radius:2px; - color:var(--main-color); - font-size:12px; - line-height:14px; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - cursor:default; - box-sizing:border-box; -} - -.treeItemToggler::before{ - position:absolute; - display:inline-block; - width:16px; - height:16px; - - content:""; - background-color:var(--toolbar-icon-bg-color); - -webkit-mask-size:cover; - mask-size:cover; -} - -#sidebarToggleButton::before{ - -webkit-mask-image:var(--toolbarButton-sidebarToggle-icon); - mask-image:var(--toolbarButton-sidebarToggle-icon); - transform:scaleX(var(--dir-factor)); -} - -#secondaryToolbarToggleButton::before{ - -webkit-mask-image:var(--toolbarButton-secondaryToolbarToggle-icon); - mask-image:var(--toolbarButton-secondaryToolbarToggle-icon); - transform:scaleX(var(--dir-factor)); -} - -#previous::before{ - -webkit-mask-image:var(--toolbarButton-pageUp-icon); - mask-image:var(--toolbarButton-pageUp-icon); -} - -#next::before{ - -webkit-mask-image:var(--toolbarButton-pageDown-icon); - mask-image:var(--toolbarButton-pageDown-icon); -} - -#zoomOutButton::before{ - -webkit-mask-image:var(--toolbarButton-zoomOut-icon); - mask-image:var(--toolbarButton-zoomOut-icon); -} - -#zoomInButton::before{ - -webkit-mask-image:var(--toolbarButton-zoomIn-icon); - mask-image:var(--toolbarButton-zoomIn-icon); -} - -#presentationMode::before{ - -webkit-mask-image:var(--toolbarButton-presentationMode-icon); - mask-image:var(--toolbarButton-presentationMode-icon); -} - -#editorFreeTextButton::before{ - -webkit-mask-image:var(--toolbarButton-editorFreeText-icon); - mask-image:var(--toolbarButton-editorFreeText-icon); -} - -#editorHighlightButton::before{ - -webkit-mask-image:var(--toolbarButton-editorHighlight-icon); - mask-image:var(--toolbarButton-editorHighlight-icon); -} - -#editorInkButton::before{ - -webkit-mask-image:var(--toolbarButton-editorInk-icon); - mask-image:var(--toolbarButton-editorInk-icon); -} - -#editorStampButton::before{ - -webkit-mask-image:var(--toolbarButton-editorStamp-icon); - mask-image:var(--toolbarButton-editorStamp-icon); -} - -#printButton::before{ - -webkit-mask-image:var(--toolbarButton-print-icon); - mask-image:var(--toolbarButton-print-icon); -} - -#secondaryOpenFile::before{ - -webkit-mask-image:var(--toolbarButton-openFile-icon); - mask-image:var(--toolbarButton-openFile-icon); -} - -#downloadButton::before{ - -webkit-mask-image:var(--toolbarButton-download-icon); - mask-image:var(--toolbarButton-download-icon); -} - -#viewBookmark::before{ - -webkit-mask-image:var(--toolbarButton-bookmark-icon); - mask-image:var(--toolbarButton-bookmark-icon); -} - -#currentOutlineItem::before{ - -webkit-mask-image:var(--toolbarButton-currentOutlineItem-icon); - mask-image:var(--toolbarButton-currentOutlineItem-icon); - transform:scaleX(var(--dir-factor)); -} - -#viewFindButton::before{ - -webkit-mask-image:var(--toolbarButton-search-icon); - mask-image:var(--toolbarButton-search-icon); -} - -.pdfSidebarNotification::after{ - position:absolute; - display:inline-block; - top:2px; - inset-inline-end:2px; - content:""; - background-color:rgb(112 219 85); - height:9px; - width:9px; - border-radius:50%; -} - -.verticalToolbarSeparator{ - display:block; - margin-inline:2px; - width:0; - height:80%; - border-left:1px solid var(--separator-color); - border-right:none; - box-sizing:border-box; -} - -.horizontalToolbarSeparator{ - display:block; - margin:6px 0; - border-top:1px solid var(--doorhanger-separator-color); - border-bottom:none; - height:0; - width:100%; -} - -.toggleButton{ - display:inline; -} - -.toggleButton:has( > input:checked){ - color:var(--toggled-btn-color); - background-color:var(--toggled-btn-bg-color); - } - -.toggleButton:is(:hover,:has( > input:focus-visible)){ - color:var(--toggled-btn-color); - background-color:var(--button-hover-color); - } - -.toggleButton > input{ - position:absolute; - top:50%; - left:50%; - opacity:0; - width:0; - height:0; - } - -.toolbarField{ - padding:4px 7px; - margin:3px 0; - border-radius:2px; - background-color:var(--field-bg-color); - background-clip:padding-box; - border:1px solid var(--field-border-color); - box-shadow:none; - color:var(--field-color); - font-size:12px; - line-height:16px; - outline:none; -} - -.toolbarField:focus{ - border-color:#0a84ff; - } - -#pageNumber{ - -moz-appearance:textfield; - text-align:end; - width:40px; - background-size:0 0; - transition-property:none; -} - -#pageNumber::-webkit-inner-spin-button{ - -webkit-appearance:none; - } - -.loadingInput:has( > .loading:is(#pageNumber))::after{ - display:inline; - visibility:visible; - - transition-property:visibility; - transition-delay:var(--loading-icon-delay); - } - -.loadingInput{ - position:relative; -} - -.loadingInput::after{ - position:absolute; - visibility:hidden; - display:none; - width:var(--icon-size); - height:var(--icon-size); - - content:""; - background-color:var(--toolbar-icon-bg-color); - -webkit-mask-size:cover; - mask-size:cover; - -webkit-mask-image:var(--loading-icon); - mask-image:var(--loading-icon); - } - -.loadingInput.start::after{ - inset-inline-start:4px; - } - -.loadingInput.end::after{ - inset-inline-end:4px; - } - -#thumbnailView, -#outlineView, -#attachmentsView, -#layersView{ - position:absolute; - width:calc(100% - 8px); - inset-block:0; - padding:4px 4px 0; - overflow:auto; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; -} - -#thumbnailView{ - width:calc(100% - 60px); - padding:10px 30px 0; -} - -#thumbnailView > a:is(:active, :focus){ - outline:0; -} - -.thumbnail{ - --thumbnail-width:0; - --thumbnail-height:0; - - float:var(--inline-start); - width:var(--thumbnail-width); - height:var(--thumbnail-height); - margin:0 10px 5px; - padding:1px; - border:7px solid transparent; - border-radius:2px; -} - -#thumbnailView > a:last-of-type > .thumbnail{ - margin-bottom:10px; -} - -a:focus > .thumbnail, -.thumbnail:hover{ - border-color:var(--thumbnail-hover-color); -} - -.thumbnail.selected{ - border-color:var(--thumbnail-selected-color) !important; -} - -.thumbnailImage{ - width:var(--thumbnail-width); - height:var(--thumbnail-height); - opacity:0.9; -} - -a:focus > .thumbnail > .thumbnailImage, -.thumbnail:hover > .thumbnailImage{ - opacity:0.95; -} - -.thumbnail.selected > .thumbnailImage{ - opacity:1 !important; -} - -.thumbnail:not([data-loaded]) > .thumbnailImage{ - width:calc(var(--thumbnail-width) - 2px); - height:calc(var(--thumbnail-height) - 2px); - border:1px dashed rgb(132 132 132); -} - -.treeWithDeepNesting > .treeItem, -.treeItem > .treeItems{ - margin-inline-start:20px; -} - -.treeItem > a{ - text-decoration:none; - display:inline-block; - min-width:calc(100% - 4px); - height:auto; - margin-bottom:1px; - padding:2px 0 5px; - padding-inline-start:4px; - border-radius:2px; - color:var(--treeitem-color); - font-size:13px; - line-height:15px; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - white-space:normal; - cursor:pointer; -} - -#layersView .treeItem > a *{ - cursor:pointer; -} - -#layersView .treeItem > a > label{ - padding-inline-start:4px; -} - -#layersView .treeItem > a > label > input{ - float:var(--inline-start); - margin-top:1px; -} - -.treeItemToggler{ - position:relative; - float:var(--inline-start); - height:0; - width:0; - color:rgb(255 255 255 / 0.5); -} - -.treeItemToggler::before{ - inset-inline-end:4px; - -webkit-mask-image:var(--treeitem-expanded-icon); - mask-image:var(--treeitem-expanded-icon); -} - -.treeItemToggler.treeItemsHidden::before{ - -webkit-mask-image:var(--treeitem-collapsed-icon); - mask-image:var(--treeitem-collapsed-icon); - transform:scaleX(var(--dir-factor)); -} - -.treeItemToggler.treeItemsHidden ~ .treeItems{ - display:none; -} - -.treeItem.selected > a{ - background-color:var(--treeitem-selected-bg-color); - color:var(--treeitem-selected-color); -} - -.treeItemToggler:hover, -.treeItemToggler:hover + a, -.treeItemToggler:hover ~ .treeItems, -.treeItem > a:hover{ - background-color:var(--treeitem-bg-color); - background-clip:padding-box; - border-radius:2px; - color:var(--treeitem-hover-color); -} - -#outlineOptionsContainer{ - display:none; -} - -#sidebarContainer:has(#outlineView:not(.hidden)) #outlineOptionsContainer{ - display:inline flex; - } - -.dialogButton{ - width:auto; - margin:3px 4px 2px !important; - padding:2px 11px; - color:var(--main-color); - background-color:var(--dialog-button-bg-color); - border:var(--dialog-button-border) !important; -} - -dialog{ - margin:auto; - padding:15px; - border-spacing:4px; - color:var(--main-color); - font:message-box; - font-size:12px; - line-height:14px; - background-color:var(--doorhanger-bg-color); - border:1px solid rgb(0 0 0 / 0.5); - border-radius:4px; - box-shadow:0 1px 4px rgb(0 0 0 / 0.3); -} - -dialog::backdrop{ - background-color:rgb(0 0 0 / 0.2); -} - -dialog > .row{ - display:table-row; -} - -dialog > .row > *{ - display:table-cell; -} - -dialog .toolbarField{ - margin:5px 0; -} - -dialog .separator{ - display:block; - margin:4px 0; - height:0; - width:100%; - border-top:1px solid var(--separator-color); - border-bottom:none; -} - -dialog .buttonRow{ - text-align:center; - vertical-align:middle; -} - -dialog :link{ - color:rgb(255 255 255); -} - -#passwordDialog{ - text-align:center; -} - -#passwordDialog .toolbarField{ - width:200px; -} - -#documentPropertiesDialog{ - text-align:left; -} - -#documentPropertiesDialog .row > *{ - min-width:100px; - text-align:start; -} - -#documentPropertiesDialog .row > span{ - width:125px; - word-wrap:break-word; -} - -#documentPropertiesDialog .row > p{ - max-width:225px; - word-wrap:break-word; -} - -#documentPropertiesDialog .buttonRow{ - margin-top:10px; -} - -.grab-to-pan-grab{ - cursor:grab !important; -} - -.grab-to-pan-grab - *:not(input):not(textarea):not(button):not(select):not(:link){ - cursor:inherit !important; -} - -.grab-to-pan-grab:active, -.grab-to-pan-grabbing{ - cursor:grabbing !important; -} - -.grab-to-pan-grabbing{ - position:fixed; - background:rgb(0 0 0 / 0); - display:block; - inset:0; - overflow:hidden; - z-index:50000; -} - -.toolbarButton{ - height:100%; - aspect-ratio:1; - display:flex; - align-items:center; - justify-content:center; - background:none; - border:none; - color:var(--main-color); - outline:none; - border-radius:2px; - box-sizing:border-box; - font:message-box; - flex:none; - position:relative; - padding:0; -} - -.toolbarButton > span{ - display:inline-block; - width:0; - height:0; - overflow:hidden; - } - -.toolbarButton::before{ - opacity:var(--toolbar-icon-opacity); - display:inline-block; - width:var(--icon-size); - height:var(--icon-size); - content:""; - background-color:var(--toolbar-icon-bg-color); - -webkit-mask-size:cover; - mask-size:cover; - -webkit-mask-position:center; - mask-position:center; - } - -.toolbarButton.toggled{ - background-color:var(--toggled-btn-bg-color); - color:var(--toggled-btn-color); - } - -.toolbarButton.toggled::before{ - background-color:var(--toggled-btn-color); - } - -.toolbarButton.toggled:hover{ - outline:var(--toggled-hover-btn-outline) !important; - } - -.toolbarButton.toggled:hover:active{ - background-color:var(--toggled-hover-active-btn-color); - } - -.toolbarButton:is(:hover,:focus-visible){ - background-color:var(--button-hover-color); - } - -.toolbarButton:is(:hover,:focus-visible)::before{ - background-color:var(--toolbar-icon-hover-bg-color); - } - -.toolbarButton:is([disabled="disabled"],[disabled]){ - opacity:0.5; - pointer-events:none; - } - -.toolbarButton.labeled{ - width:100%; - min-height:var(--menuitem-height); - justify-content:flex-start; - gap:8px; - padding-inline-start:12px; - aspect-ratio:unset; - text-align:start; - white-space:normal; - cursor:default; - } - -.toolbarButton.labeled:is(a){ - text-decoration:none; - } - -.toolbarButton.labeled[href="#"]:is(a){ - opacity:0.5; - pointer-events:none; - } - -.toolbarButton.labeled::before{ - opacity:var(--doorhanger-icon-opacity); - } - -.toolbarButton.labeled:is(:hover,:focus-visible){ - background-color:var(--doorhanger-hover-bg-color); - color:var(--doorhanger-hover-color); - } - -.toolbarButton.labeled > span{ - display:inline-block; - width:-moz-max-content; - width:max-content; - height:auto; - } - -.toolbarButtonWithContainer{ - height:100%; - aspect-ratio:1; - display:inline-block; - position:relative; - flex:none; -} - -.toolbarButtonWithContainer > .toolbarButton{ - width:100%; - height:100%; - } - -.toolbarButtonWithContainer .menu{ - padding-block:5px; - } - -.toolbarButtonWithContainer .menuContainer{ - width:100%; - height:auto; - max-height:calc( - var(--viewer-container-height) - var(--toolbar-height) - - var(--doorhanger-height) - ); - display:flex; - flex-direction:column; - box-sizing:border-box; - overflow-y:auto; - } - -.toolbarButtonWithContainer .editorParamsToolbar{ - height:auto; - width:220px; - position:absolute; - z-index:30000; - cursor:default; - } - -:is(.toolbarButtonWithContainer .editorParamsToolbar) #editorStampAddImage::before{ - -webkit-mask-image:var(--editorParams-stampAddImage-icon); - mask-image:var(--editorParams-stampAddImage-icon); - } - -:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsLabel{ - flex:none; - font:menu; - font-size:13px; - font-style:normal; - font-weight:400; - line-height:150%; - color:var(--main-color); - width:-moz-fit-content; - width:fit-content; - inset-inline-start:0; - } - -:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsToolbarContainer{ - width:100%; - height:auto; - display:flex; - flex-direction:column; - box-sizing:border-box; - padding-inline:10px; - padding-block:10px; - } - -:is(:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsToolbarContainer) > .editorParamsSetter{ - min-height:26px; - display:flex; - align-items:center; - justify-content:space-between; - } - -:is(:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsToolbarContainer) .editorParamsColor{ - width:32px; - height:32px; - flex:none; - padding:0; - } - -:is(:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsToolbarContainer) .editorParamsSlider{ - background-color:transparent; - width:90px; - flex:0 1 0; - font:message-box; - } - -:is(:is(:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsToolbarContainer) .editorParamsSlider)::-moz-range-progress{ - background-color:black; - } - -:is(:is(:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsToolbarContainer) .editorParamsSlider)::-webkit-slider-runnable-track,:is(:is(:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsToolbarContainer) .editorParamsSlider)::-moz-range-track{ - background-color:black; - } - -:is(:is(:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsToolbarContainer) .editorParamsSlider)::-webkit-slider-thumb,:is(:is(:is(.toolbarButtonWithContainer .editorParamsToolbar) .editorParamsToolbarContainer) .editorParamsSlider)::-moz-range-thumb{ - background-color:white; - } - -#secondaryToolbar{ - height:auto; - width:220px; - position:absolute; - z-index:30000; - cursor:default; - min-height:26px; - max-height:calc(var(--viewer-container-height) - 40px); -} - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #secondaryOpenFile::before{ - -webkit-mask-image:var(--toolbarButton-openFile-icon); - mask-image:var(--toolbarButton-openFile-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #secondaryPrint::before{ - -webkit-mask-image:var(--toolbarButton-print-icon); - mask-image:var(--toolbarButton-print-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #secondaryDownload::before{ - -webkit-mask-image:var(--toolbarButton-download-icon); - mask-image:var(--toolbarButton-download-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #presentationMode::before{ - -webkit-mask-image:var(--toolbarButton-presentationMode-icon); - mask-image:var(--toolbarButton-presentationMode-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #viewBookmark::before{ - -webkit-mask-image:var(--toolbarButton-bookmark-icon); - mask-image:var(--toolbarButton-bookmark-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #firstPage::before{ - -webkit-mask-image:var(--secondaryToolbarButton-firstPage-icon); - mask-image:var(--secondaryToolbarButton-firstPage-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #lastPage::before{ - -webkit-mask-image:var(--secondaryToolbarButton-lastPage-icon); - mask-image:var(--secondaryToolbarButton-lastPage-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #pageRotateCcw::before{ - -webkit-mask-image:var(--secondaryToolbarButton-rotateCcw-icon); - mask-image:var(--secondaryToolbarButton-rotateCcw-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #pageRotateCw::before{ - -webkit-mask-image:var(--secondaryToolbarButton-rotateCw-icon); - mask-image:var(--secondaryToolbarButton-rotateCw-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #cursorSelectTool::before{ - -webkit-mask-image:var(--secondaryToolbarButton-selectTool-icon); - mask-image:var(--secondaryToolbarButton-selectTool-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #cursorHandTool::before{ - -webkit-mask-image:var(--secondaryToolbarButton-handTool-icon); - mask-image:var(--secondaryToolbarButton-handTool-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #scrollPage::before{ - -webkit-mask-image:var(--secondaryToolbarButton-scrollPage-icon); - mask-image:var(--secondaryToolbarButton-scrollPage-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #scrollVertical::before{ - -webkit-mask-image:var(--secondaryToolbarButton-scrollVertical-icon); - mask-image:var(--secondaryToolbarButton-scrollVertical-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #scrollHorizontal::before{ - -webkit-mask-image:var(--secondaryToolbarButton-scrollHorizontal-icon); - mask-image:var(--secondaryToolbarButton-scrollHorizontal-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #scrollWrapped::before{ - -webkit-mask-image:var(--secondaryToolbarButton-scrollWrapped-icon); - mask-image:var(--secondaryToolbarButton-scrollWrapped-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #spreadNone::before{ - -webkit-mask-image:var(--secondaryToolbarButton-spreadNone-icon); - mask-image:var(--secondaryToolbarButton-spreadNone-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #spreadOdd::before{ - -webkit-mask-image:var(--secondaryToolbarButton-spreadOdd-icon); - mask-image:var(--secondaryToolbarButton-spreadOdd-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #spreadEven::before{ - -webkit-mask-image:var(--secondaryToolbarButton-spreadEven-icon); - mask-image:var(--secondaryToolbarButton-spreadEven-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #imageAltTextSettings::before{ - -webkit-mask-image:var(--secondaryToolbarButton-imageAltTextSettings-icon); - mask-image:var(--secondaryToolbarButton-imageAltTextSettings-icon); - } - -:is(#secondaryToolbar #secondaryToolbarButtonContainer) #documentProperties::before{ - -webkit-mask-image:var(--secondaryToolbarButton-documentProperties-icon); - mask-image:var(--secondaryToolbarButton-documentProperties-icon); - } - -#findbar{ - --input-horizontal-padding:4px; - --findbar-padding:2px; - - width:-moz-max-content; - - width:max-content; - max-width:90vw; - min-height:var(--toolbar-height); - height:auto; - position:absolute; - z-index:30000; - cursor:default; - padding:0; - min-width:300px; - background-color:var(--toolbar-bg-color); - box-sizing:border-box; - flex-wrap:wrap; - justify-content:flex-start; -} - -#findbar > *{ - height:var(--toolbar-height); - padding:var(--findbar-padding); - } - -#findbar #findInputContainer{ - margin-inline-start:2px; - } - -:is(#findbar #findInputContainer) #findPreviousButton::before{ - -webkit-mask-image:var(--findbarButton-previous-icon); - mask-image:var(--findbarButton-previous-icon); - } - -:is(#findbar #findInputContainer) #findNextButton::before{ - -webkit-mask-image:var(--findbarButton-next-icon); - mask-image:var(--findbarButton-next-icon); - } - -:is(#findbar #findInputContainer) #findInput{ - width:200px; - padding:5px var(--input-horizontal-padding); - } - -:is(:is(#findbar #findInputContainer) #findInput)::-moz-placeholder{ - font-style:normal; - } - -:is(:is(#findbar #findInputContainer) #findInput)::placeholder{ - font-style:normal; - } - -.loadingInput:has( > [data-status="pending"]:is(:is(#findbar #findInputContainer) #findInput))::after{ - display:inline; - visibility:visible; - inset-inline-end:calc(var(--input-horizontal-padding) + 1px); - } - -[data-status="notFound"]:is(:is(#findbar #findInputContainer) #findInput){ - background-color:rgb(255 102 102); - } - -#findbar #findbarMessageContainer{ - display:none; - gap:4px; - } - -:is(#findbar #findbarMessageContainer):has( > :is(#findResultsCount,#findMsg):not(:empty)){ - display:inline flex; - } - -:is(#findbar #findbarMessageContainer) #findResultsCount{ - background-color:rgb(217 217 217); - color:rgb(82 82 82); - padding-block:4px; - } - -:is(:is(#findbar #findbarMessageContainer) #findResultsCount):empty{ - display:none; - } - -[data-status="notFound"]:is(:is(#findbar #findbarMessageContainer) #findMsg){ - font-weight:bold; - } - -:is(:is(#findbar #findbarMessageContainer) #findMsg):empty{ - display:none; - } - -#findbar.wrapContainers{ - flex-direction:column; - align-items:flex-start; - height:-moz-max-content; - height:max-content; - } - -#findbar.wrapContainers .toolbarLabel{ - margin:0 4px; - } - -#findbar.wrapContainers #findbarMessageContainer{ - flex-wrap:wrap; - flex-flow:column nowrap; - align-items:flex-start; - height:-moz-max-content; - height:max-content; - } - -:is(#findbar.wrapContainers #findbarMessageContainer) #findResultsCount{ - height:calc(var(--toolbar-height) - 2 * var(--findbar-padding)); - } - -:is(#findbar.wrapContainers #findbarMessageContainer) #findMsg{ - min-height:var(--toolbar-height); - } - -@page{ - margin:0; -} - -#printContainer{ - display:none; -} - -@media print{ - body{ - background:rgb(0 0 0 / 0) none; - } - - body[data-pdfjsprinting] #outerContainer{ - display:none; - } - - body[data-pdfjsprinting] #printContainer{ - display:block; - } - - #printContainer{ - height:100%; - } - #printContainer > .printedPage{ - page-break-after:always; - page-break-inside:avoid; - height:100%; - width:100%; - - display:flex; - flex-direction:column; - justify-content:center; - align-items:center; - } - - #printContainer > .xfaPrintedPage .xfaPage{ - position:absolute; - } - - #printContainer > .xfaPrintedPage{ - page-break-after:always; - page-break-inside:avoid; - width:100%; - height:100%; - position:relative; - } - - #printContainer > .printedPage :is(canvas, img){ - max-width:100%; - max-height:100%; - - direction:ltr; - display:block; - } -} - -.visibleMediumView{ - display:none !important; -} - -.toolbarLabel{ - width:-moz-max-content; - width:max-content; - min-width:16px; - height:100%; - padding-inline:4px; - margin:2px; - border-radius:2px; - color:var(--main-color); - font-size:12px; - line-height:14px; - text-align:left; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - cursor:default; - box-sizing:border-box; - - display:inline flex; - flex-direction:column; - align-items:center; - justify-content:center; -} - -.toolbarLabel > label{ - width:100%; - } - -.toolbarHorizontalGroup{ - height:100%; - display:inline flex; - flex-direction:row; - align-items:center; - justify-content:space-between; - gap:1px; - box-sizing:border-box; -} - -.dropdownToolbarButton{ - display:inline flex; - flex-direction:row; - align-items:center; - justify-content:center; - position:relative; - - width:-moz-fit-content; - - width:fit-content; - min-width:140px; - padding:0; - background-color:var(--dropdown-btn-bg-color); - border:var(--dropdown-btn-border); - border-radius:2px; - color:var(--main-color); - font-size:12px; - line-height:14px; - -webkit-user-select:none; - -moz-user-select:none; - user-select:none; - cursor:default; - box-sizing:border-box; - outline:none; -} - -.dropdownToolbarButton:hover{ - background-color:var(--button-hover-color); - } - -.dropdownToolbarButton > select{ - -webkit-appearance:none; - -moz-appearance:none; - appearance:none; - width:inherit; - min-width:inherit; - height:28px; - font:message-box; - font-size:12px; - color:var(--main-color); - margin:0; - padding-block:1px 2px; - padding-inline:6px 38px; - border:none; - outline:none; - background-color:var(--dropdown-btn-bg-color); - } - -:is(.dropdownToolbarButton > select) > option{ - background:var(--doorhanger-bg-color); - color:var(--main-color); - } - -:is(.dropdownToolbarButton > select):is(:hover,:focus-visible){ - background-color:var(--button-hover-color); - color:var(--toggled-btn-color); - } - -.dropdownToolbarButton::after{ - position:absolute; - display:inline; - width:var(--icon-size); - height:var(--icon-size); - - content:""; - background-color:var(--toolbar-icon-bg-color); - -webkit-mask-size:cover; - mask-size:cover; - - inset-inline-end:4px; - pointer-events:none; - -webkit-mask-image:var(--toolbarButton-menuArrow-icon); - mask-image:var(--toolbarButton-menuArrow-icon); - } - -.dropdownToolbarButton:is(:hover,:focus-visible,:active)::after{ - background-color:var(--toolbar-icon-hover-bg-color); - } - -#toolbarContainer{ - --menuitem-height:calc(var(--toolbar-height) - 6px); - - width:100%; - height:var(--toolbar-height); - padding:var(--toolbar-vertical-padding) var(--toolbar-horizontal-padding); - position:relative; - box-sizing:border-box; - font:message-box; - background-color:var(--toolbar-bg-color); - box-shadow:var(--toolbar-box-shadow); - border-bottom:var(--toolbar-border-bottom); -} - -#toolbarContainer #toolbarViewer{ - width:100%; - height:100%; - justify-content:space-between; - } - -:is(#toolbarContainer #toolbarViewer) > *{ - flex:none; - } - -:is(#toolbarContainer #toolbarViewer) input{ - font:message-box; - } - -:is(#toolbarContainer #toolbarViewer) .toolbarButtonSpacer{ - width:30px; - display:block; - height:1px; - } - -:is(#toolbarContainer #toolbarViewer) #toolbarViewerLeft #numPages.toolbarLabel{ - padding-inline-start:3px; - flex:none; - } - -#toolbarContainer #loadingBar{ - --progressBar-percent:0%; - --progressBar-end-offset:0; - - position:absolute; - top:var(--toolbar-height); - inset-inline:0 var(--progressBar-end-offset); - height:4px; - background-color:var(--progressBar-bg-color); - border-bottom:1px solid var(--toolbar-border-color); - transition-property:inset-inline-start; - transition-duration:var(--sidebar-transition-duration); - transition-timing-function:var(--sidebar-transition-timing-function); - } - -:is(#toolbarContainer #loadingBar) .progress{ - position:absolute; - top:0; - inset-inline-start:0; - width:100%; - transform:scaleX(var(--progressBar-percent)); - transform-origin:calc(50% - 50% * var(--dir-factor)) 0; - height:100%; - background-color:var(--progressBar-color); - overflow:hidden; - transition:transform 200ms; - } - -.indeterminate:is(#toolbarContainer #loadingBar) .progress{ - transform:none; - background-color:var(--progressBar-bg-color); - transition:none; - } - -:is(.indeterminate:is(#toolbarContainer #loadingBar) .progress) .glimmer{ - position:absolute; - top:0; - inset-inline-start:0; - height:100%; - width:calc(100% + 150px); - background:repeating-linear-gradient( - 135deg, - var(--progressBar-blend-color) 0, - var(--progressBar-bg-color) 5px, - var(--progressBar-bg-color) 45px, - var(--progressBar-color) 55px, - var(--progressBar-color) 95px, - var(--progressBar-blend-color) 100px - ); - animation:progressIndeterminate 1s linear infinite; - } - -#secondaryToolbar #firstPage::before{ - -webkit-mask-image:var(--secondaryToolbarButton-firstPage-icon); - mask-image:var(--secondaryToolbarButton-firstPage-icon); - } - -#secondaryToolbar #lastPage::before{ - -webkit-mask-image:var(--secondaryToolbarButton-lastPage-icon); - mask-image:var(--secondaryToolbarButton-lastPage-icon); - } - -#secondaryToolbar #pageRotateCcw::before{ - -webkit-mask-image:var(--secondaryToolbarButton-rotateCcw-icon); - mask-image:var(--secondaryToolbarButton-rotateCcw-icon); - } - -#secondaryToolbar #pageRotateCw::before{ - -webkit-mask-image:var(--secondaryToolbarButton-rotateCw-icon); - mask-image:var(--secondaryToolbarButton-rotateCw-icon); - } - -#secondaryToolbar #cursorSelectTool::before{ - -webkit-mask-image:var(--secondaryToolbarButton-selectTool-icon); - mask-image:var(--secondaryToolbarButton-selectTool-icon); - } - -#secondaryToolbar #cursorHandTool::before{ - -webkit-mask-image:var(--secondaryToolbarButton-handTool-icon); - mask-image:var(--secondaryToolbarButton-handTool-icon); - } - -#secondaryToolbar #scrollPage::before{ - -webkit-mask-image:var(--secondaryToolbarButton-scrollPage-icon); - mask-image:var(--secondaryToolbarButton-scrollPage-icon); - } - -#secondaryToolbar #scrollVertical::before{ - -webkit-mask-image:var(--secondaryToolbarButton-scrollVertical-icon); - mask-image:var(--secondaryToolbarButton-scrollVertical-icon); - } - -#secondaryToolbar #scrollHorizontal::before{ - -webkit-mask-image:var(--secondaryToolbarButton-scrollHorizontal-icon); - mask-image:var(--secondaryToolbarButton-scrollHorizontal-icon); - } - -#secondaryToolbar #scrollWrapped::before{ - -webkit-mask-image:var(--secondaryToolbarButton-scrollWrapped-icon); - mask-image:var(--secondaryToolbarButton-scrollWrapped-icon); - } - -#secondaryToolbar #spreadNone::before{ - -webkit-mask-image:var(--secondaryToolbarButton-spreadNone-icon); - mask-image:var(--secondaryToolbarButton-spreadNone-icon); - } - -#secondaryToolbar #spreadOdd::before{ - -webkit-mask-image:var(--secondaryToolbarButton-spreadOdd-icon); - mask-image:var(--secondaryToolbarButton-spreadOdd-icon); - } - -#secondaryToolbar #spreadEven::before{ - -webkit-mask-image:var(--secondaryToolbarButton-spreadEven-icon); - mask-image:var(--secondaryToolbarButton-spreadEven-icon); - } - -#secondaryToolbar #documentProperties::before{ - -webkit-mask-image:var(--secondaryToolbarButton-documentProperties-icon); - mask-image:var(--secondaryToolbarButton-documentProperties-icon); - } - -@media all and (max-width: 840px){ - #sidebarContainer{ - background-color:var(--sidebar-narrow-bg-color); - } - #outerContainer.sidebarOpen #viewerContainer{ - inset-inline-start:0 !important; - } -} - -@media all and (max-width: 750px){ - #outerContainer .hiddenMediumView{ - display:none !important; - } - #outerContainer .visibleMediumView:not(.hidden, [hidden]){ - display:inline-block !important; - } -} - -@media all and (max-width: 690px){ - .hiddenSmallView, - .hiddenSmallView *{ - display:none !important; - } - - #toolbarContainer #toolbarViewer .toolbarButtonSpacer{ - width:0; - } -} - -@media all and (max-width: 560px){ - #scaleSelectContainer{ - display:none; - } -} diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs similarity index 54% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.mjs rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs index c3d794a2725..1bb510f01fa 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.mjs +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/pdfjs-dist/dist/web/pdf_viewer.mjs @@ -42,13 +42,32 @@ /******/ })(); /******/ /************************************************************************/ -var __webpack_exports__ = {}; +var __webpack_exports__ = globalThis.pdfjsViewer = {}; // EXPORTS __webpack_require__.d(__webpack_exports__, { - PDFViewerApplication: () => (/* reexport */ PDFViewerApplication), - PDFViewerApplicationConstants: () => (/* binding */ AppConstants), - PDFViewerApplicationOptions: () => (/* reexport */ AppOptions) + AnnotationLayerBuilder: () => (/* reexport */ AnnotationLayerBuilder), + DownloadManager: () => (/* reexport */ DownloadManager), + EventBus: () => (/* reexport */ EventBus), + FindState: () => (/* reexport */ FindState), + GenericL10n: () => (/* reexport */ genericl10n_GenericL10n), + LinkTarget: () => (/* reexport */ LinkTarget), + PDFFindController: () => (/* reexport */ PDFFindController), + PDFHistory: () => (/* reexport */ PDFHistory), + PDFLinkService: () => (/* reexport */ PDFLinkService), + PDFPageView: () => (/* reexport */ PDFPageView), + PDFScriptingManager: () => (/* reexport */ PDFScriptingManagerComponents), + PDFSinglePageViewer: () => (/* reexport */ PDFSinglePageViewer), + PDFViewer: () => (/* reexport */ PDFViewer), + ProgressBar: () => (/* reexport */ ProgressBar), + RenderingStates: () => (/* reexport */ RenderingStates), + ScrollMode: () => (/* reexport */ ScrollMode), + SimpleLinkService: () => (/* reexport */ SimpleLinkService), + SpreadMode: () => (/* reexport */ SpreadMode), + StructTreeLayerBuilder: () => (/* reexport */ StructTreeLayerBuilder), + TextLayerBuilder: () => (/* reexport */ TextLayerBuilder), + XfaLayerBuilder: () => (/* reexport */ XfaLayerBuilder), + parseQueryString: () => (/* reexport */ parseQueryString) }); ;// ./web/ui_utils.js @@ -528,5719 +547,3374 @@ const calcRound = function () { return e.style.width === "calc(1320px)" ? Math.fround : x => x; }(); -;// ./web/app_options.js -{ - var compatParams = new Map(); - const userAgent = navigator.userAgent || ""; - const platform = navigator.platform || ""; - const maxTouchPoints = navigator.maxTouchPoints || 1; - const isAndroid = /Android/.test(userAgent); - const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; - (function () { - if (isIOS || isAndroid) { - compatParams.set("maxCanvasPixels", 5242880); - } - })(); - (function () { - if (isAndroid) { - compatParams.set("useSystemFonts", false); +;// ./web/pdf_find_utils.js +const CharacterType = { + SPACE: 0, + ALPHA_LETTER: 1, + PUNCT: 2, + HAN_LETTER: 3, + KATAKANA_LETTER: 4, + HIRAGANA_LETTER: 5, + HALFWIDTH_KATAKANA_LETTER: 6, + THAI_LETTER: 7 +}; +function isAlphabeticalScript(charCode) { + return charCode < 0x2e80; +} +function isAscii(charCode) { + return (charCode & 0xff80) === 0; +} +function isAsciiAlpha(charCode) { + return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; +} +function isAsciiDigit(charCode) { + return charCode >= 0x30 && charCode <= 0x39; +} +function isAsciiSpace(charCode) { + return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; +} +function isHan(charCode) { + return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; +} +function isKatakana(charCode) { + return charCode >= 0x30a0 && charCode <= 0x30ff; +} +function isHiragana(charCode) { + return charCode >= 0x3040 && charCode <= 0x309f; +} +function isHalfwidthKatakana(charCode) { + return charCode >= 0xff60 && charCode <= 0xff9f; +} +function isThai(charCode) { + return (charCode & 0xff80) === 0x0e00; +} +function getCharacterType(charCode) { + if (isAlphabeticalScript(charCode)) { + if (isAscii(charCode)) { + if (isAsciiSpace(charCode)) { + return CharacterType.SPACE; + } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { + return CharacterType.ALPHA_LETTER; + } + return CharacterType.PUNCT; + } else if (isThai(charCode)) { + return CharacterType.THAI_LETTER; + } else if (charCode === 0xa0) { + return CharacterType.SPACE; } - })(); + return CharacterType.ALPHA_LETTER; + } + if (isHan(charCode)) { + return CharacterType.HAN_LETTER; + } else if (isKatakana(charCode)) { + return CharacterType.KATAKANA_LETTER; + } else if (isHiragana(charCode)) { + return CharacterType.HIRAGANA_LETTER; + } else if (isHalfwidthKatakana(charCode)) { + return CharacterType.HALFWIDTH_KATAKANA_LETTER; + } + return CharacterType.ALPHA_LETTER; } -const OptionKind = { - BROWSER: 0x01, - VIEWER: 0x02, - API: 0x04, - WORKER: 0x08, - EVENT_DISPATCH: 0x10, - PREFERENCE: 0x80 +let NormalizeWithNFKC; +function getNormalizeWithNFKC() { + NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`; + return NormalizeWithNFKC; +} + +;// ./web/pdf_find_controller.js + + +const FindState = { + FOUND: 0, + NOT_FOUND: 1, + WRAPPED: 2, + PENDING: 3 }; -const Type = { - BOOLEAN: 0x01, - NUMBER: 0x02, - OBJECT: 0x04, - STRING: 0x08, - UNDEFINED: 0x10 +const FIND_TIMEOUT = 250; +const MATCH_SCROLL_OFFSET_TOP = -50; +const MATCH_SCROLL_OFFSET_LEFT = -400; +const CHARACTERS_TO_NORMALIZE = { + "\u2010": "-", + "\u2018": "'", + "\u2019": "'", + "\u201A": "'", + "\u201B": "'", + "\u201C": '"', + "\u201D": '"', + "\u201E": '"', + "\u201F": '"', + "\u00BC": "1/4", + "\u00BD": "1/2", + "\u00BE": "3/4" }; -const defaultOptions = { - allowedGlobalEvents: { - value: null, - kind: OptionKind.BROWSER - }, - canvasMaxAreaInBytes: { - value: -1, - kind: OptionKind.BROWSER + OptionKind.API - }, - isInAutomation: { - value: false, - kind: OptionKind.BROWSER - }, - localeProperties: { - value: { - lang: navigator.language || "en-US" - }, - kind: OptionKind.BROWSER - }, - nimbusDataStr: { - value: "", - kind: OptionKind.BROWSER - }, - supportsCaretBrowsingMode: { - value: false, - kind: OptionKind.BROWSER - }, - supportsDocumentFonts: { - value: true, - kind: OptionKind.BROWSER - }, - supportsIntegratedFind: { - value: false, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomCtrlKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsMouseWheelZoomMetaKey: { - value: true, - kind: OptionKind.BROWSER - }, - supportsPinchToZoom: { - value: true, - kind: OptionKind.BROWSER - }, - toolbarDensity: { - value: 0, - kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH - }, - altTextLearnMoreUrl: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationEditorMode: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - annotationMode: { - value: 2, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cursorToolOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - debuggerSrc: { - value: "./debugger.mjs", - kind: OptionKind.VIEWER - }, - defaultZoomDelay: { - value: 400, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - defaultZoomValue: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - disableHistory: { - value: false, - kind: OptionKind.VIEWER - }, - disablePageLabels: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltText: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableAltTextModelDownload: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableGuessAltText: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH - }, - enableHighlightFloatingButton: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableNewAltTextWhenAddingImage: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePermissions: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePrintAutoRotate: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableScripting: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableUpdatedAddImage: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - externalLinkRel: { - value: "noopener noreferrer nofollow", - kind: OptionKind.VIEWER - }, - externalLinkTarget: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - highlightEditorColors: { - value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - historyUpdateUrl: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - ignoreDestinationZoom: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - imageResourcesPath: { - value: "./images/", - kind: OptionKind.VIEWER - }, - maxCanvasPixels: { - value: 2 ** 25, - kind: OptionKind.VIEWER - }, - forcePageColors: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsBackground: { - value: "Canvas", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pageColorsForeground: { - value: "CanvasText", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - pdfBugEnabled: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - printResolution: { - value: 150, - kind: OptionKind.VIEWER - }, - sidebarViewOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - scrollModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - spreadModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - textLayerMode: { - value: 1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - viewOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cMapPacked: { - value: true, - kind: OptionKind.API - }, - cMapUrl: { - value: "../web/cmaps/", - kind: OptionKind.API - }, - disableAutoFetch: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableFontFace: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableRange: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableStream: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - docBaseUrl: { - value: "", - kind: OptionKind.API - }, - enableHWA: { - value: true, - kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableXfa: { - value: true, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - fontExtraProperties: { - value: false, - kind: OptionKind.API - }, - isEvalSupported: { - value: true, - kind: OptionKind.API - }, - isOffscreenCanvasSupported: { - value: true, - kind: OptionKind.API - }, - maxImageSize: { - value: -1, - kind: OptionKind.API - }, - pdfBug: { - value: false, - kind: OptionKind.API - }, - standardFontDataUrl: { - value: "../web/standard_fonts/", - kind: OptionKind.API - }, - useSystemFonts: { - value: undefined, - kind: OptionKind.API, - type: Type.BOOLEAN + Type.UNDEFINED - }, - verbosity: { - value: 1, - kind: OptionKind.API - }, - workerPort: { - value: null, - kind: OptionKind.WORKER - }, - workerSrc: { - value: "../build/pdf.worker.mjs", - kind: OptionKind.WORKER - } -}; -{ - defaultOptions.defaultUrl = { - value: "compressed.tracemonkey-pldi-09.pdf", - kind: OptionKind.VIEWER - }; - defaultOptions.sandboxBundleSrc = { - value: "../build/pdf.sandbox.mjs", - kind: OptionKind.VIEWER - }; - defaultOptions.viewerCssTheme = { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }; - defaultOptions.enableFakeMLManager = { - value: true, - kind: OptionKind.VIEWER - }; -} -{ - defaultOptions.disablePreferences = { - value: false, - kind: OptionKind.VIEWER - }; -} -class AppOptions { - static eventBus; - static #opts = new Map(); - static { - for (const name in defaultOptions) { - this.#opts.set(name, defaultOptions[name].value); +const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]); +let DIACRITICS_EXCEPTION_STR; +const DIACRITICS_REG_EXP = /\p{M}+/gu; +const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; +const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; +const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; +const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; +const SYLLABLES_LENGTHS = new Map(); +const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; +const NFKC_CHARS_TO_NORMALIZE = new Map(); +let noSyllablesRegExp = null; +let withSyllablesRegExp = null; +function normalize(text) { + const syllablePositions = []; + let m; + while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { + let { + index + } = m; + for (const char of m[0]) { + let len = SYLLABLES_LENGTHS.get(char); + if (!len) { + len = char.normalize("NFD").length; + SYLLABLES_LENGTHS.set(char, len); + } + syllablePositions.push([len, index++]); } - for (const [name, value] of compatParams) { - this.#opts.set(name, value); + } + let normalizationRegex; + if (syllablePositions.length === 0 && noSyllablesRegExp) { + normalizationRegex = noSyllablesRegExp; + } else if (syllablePositions.length > 0 && withSyllablesRegExp) { + normalizationRegex = withSyllablesRegExp; + } else { + const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); + const toNormalizeWithNFKC = getNormalizeWithNFKC(); + const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])"; + const HKDiacritics = "(?:\u3099|\u309A)"; + const CompoundWord = "\\p{Ll}-\\n\\p{Lu}"; + const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(${CompoundWord})|(\\S-\\n)|(${CJK}\\n)|(\\n)`; + if (syllablePositions.length === 0) { + normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); + } else { + normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); } - this._hasInvokedSet = false; - this._checkDisablePreferences = () => { - if (this.get("disablePreferences")) { - return true; - } - if (this._hasInvokedSet) { - console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.'); - } - return false; - }; } - static get(name) { - return this.#opts.get(name); + const rawDiacriticsPositions = []; + while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { + rawDiacriticsPositions.push([m[0].length, m.index]); } - static getAll(kind = null, defaultOnly = false) { - const options = Object.create(null); - for (const name in defaultOptions) { - const defaultOpt = defaultOptions[name]; - if (kind && !(kind & defaultOpt.kind)) { - continue; + let normalized = text.normalize("NFD"); + const positions = [0, 0]; + let rawDiacriticsIndex = 0; + let syllableIndex = 0; + let shift = 0; + let shiftOrigin = 0; + let eol = 0; + let hasDiacritics = false; + normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, p9, i) => { + i -= shiftOrigin; + if (p1) { + const replacement = CHARACTERS_TO_NORMALIZE[p1]; + const jj = replacement.length; + for (let j = 1; j < jj; j++) { + positions.push(i - shift + j, shift - j); } - options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value; + shift -= jj - 1; + return replacement; } - return options; - } - static set(name, value) { - this.setAll({ - [name]: value - }); - } - static setAll(options, prefs = false) { - this._hasInvokedSet ||= true; - let events; - for (const name in options) { - const defaultOpt = defaultOptions[name], - userOpt = options[name]; - if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) { - continue; + if (p2) { + let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2); + if (!replacement) { + replacement = p2.normalize("NFKC"); + NFKC_CHARS_TO_NORMALIZE.set(p2, replacement); } - const { - kind - } = defaultOpt; - if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) { - continue; + const jj = replacement.length; + for (let j = 1; j < jj; j++) { + positions.push(i - shift + j, shift - j); } - if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) { - (events ||= new Map()).set(name, userOpt); + shift -= jj - 1; + return replacement; + } + if (p3) { + hasDiacritics = true; + if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { + ++rawDiacriticsIndex; + } else { + positions.push(i - 1 - shift + 1, shift - 1); + shift -= 1; + shiftOrigin += 1; } - this.#opts.set(name, userOpt); + positions.push(i - shift + 1, shift); + shiftOrigin += 1; + eol += 1; + return p3.charAt(0); } - if (events) { - for (const [name, value] of events) { - this.eventBus.dispatch(name.toLowerCase(), { - source: this, - value - }); + if (p4) { + const hasTrailingDashEOL = p4.endsWith("\n"); + const len = hasTrailingDashEOL ? p4.length - 2 : p4.length; + hasDiacritics = true; + let jj = len; + if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { + jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; + ++rawDiacriticsIndex; + } + for (let j = 1; j <= jj; j++) { + positions.push(i - 1 - shift + j, shift - j); + } + shift -= jj; + shiftOrigin += jj; + if (hasTrailingDashEOL) { + i += len - 1; + positions.push(i - shift + 1, 1 + shift); + shift += 1; + shiftOrigin += 1; + eol += 1; + return p4.slice(0, len); + } + return p4; + } + if (p5) { + shiftOrigin += 1; + eol += 1; + return p5.replace("\n", ""); + } + if (p6) { + const len = p6.length - 2; + positions.push(i - shift + len, 1 + shift); + shift += 1; + shiftOrigin += 1; + eol += 1; + return p6.slice(0, -2); + } + if (p7) { + const len = p7.length - 1; + positions.push(i - shift + len, shift); + shiftOrigin += 1; + eol += 1; + return p7.slice(0, -1); + } + if (p8) { + positions.push(i - shift + 1, shift - 1); + shift -= 1; + shiftOrigin += 1; + eol += 1; + return " "; + } + if (i + eol === syllablePositions[syllableIndex]?.[1]) { + const newCharLen = syllablePositions[syllableIndex][0] - 1; + ++syllableIndex; + for (let j = 1; j <= newCharLen; j++) { + positions.push(i - (shift - j), shift - j); } + shift -= newCharLen; + shiftOrigin += newCharLen; } + return p9; + }); + positions.push(normalized.length, shift); + const starts = new Uint32Array(positions.length >> 1); + const shifts = new Int32Array(positions.length >> 1); + for (let i = 0, ii = positions.length; i < ii; i += 2) { + starts[i >> 1] = positions[i]; + shifts[i >> 1] = positions[i + 1]; } + return [normalized, [starts, shifts], hasDiacritics]; } - -;// ./web/pdf_link_service.js - -const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; -const LinkTarget = { - NONE: 0, - SELF: 1, - BLANK: 2, - PARENT: 3, - TOP: 4 -}; -class PDFLinkService { - externalLinkEnabled = true; +function getOriginalIndex(diffs, pos, len) { + if (!diffs) { + return [pos, len]; + } + const [starts, shifts] = diffs; + const start = pos; + const end = pos + len - 1; + let i = binarySearchFirstItem(starts, x => x >= start); + if (starts[i] > start) { + --i; + } + let j = binarySearchFirstItem(starts, x => x >= end, i); + if (starts[j] > end) { + --j; + } + const oldStart = start + shifts[i]; + const oldEnd = end + shifts[j]; + const oldLen = oldEnd + 1 - oldStart; + return [oldStart, oldLen]; +} +class PDFFindController { + #state = null; + #updateMatchesCountOnProgress = true; + #visitedPagesCount = 0; constructor({ + linkService, eventBus, - externalLinkTarget = null, - externalLinkRel = null, - ignoreDestinationZoom = false - } = {}) { - this.eventBus = eventBus; - this.externalLinkTarget = externalLinkTarget; - this.externalLinkRel = externalLinkRel; - this._ignoreDestinationZoom = ignoreDestinationZoom; - this.baseUrl = null; - this.pdfDocument = null; - this.pdfViewer = null; - this.pdfHistory = null; + updateMatchesCountOnProgress = true + }) { + this._linkService = linkService; + this._eventBus = eventBus; + this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress; + this.onIsPageVisible = null; + this.#reset(); + eventBus._on("find", this.#onFind.bind(this)); + eventBus._on("findbarclose", this.#onFindBarClose.bind(this)); } - setDocument(pdfDocument, baseUrl = null) { - this.baseUrl = baseUrl; - this.pdfDocument = pdfDocument; + get highlightMatches() { + return this._highlightMatches; } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; + get pageMatches() { + return this._pageMatches; } - setHistory(pdfHistory) { - this.pdfHistory = pdfHistory; + get pageMatchesLength() { + return this._pageMatchesLength; } - get pagesCount() { - return this.pdfDocument ? this.pdfDocument.numPages : 0; + get selected() { + return this._selected; } - get page() { - return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1; + get state() { + return this.#state; } - set page(value) { - if (this.pdfDocument) { - this.pdfViewer.currentPageNumber = value; + setDocument(pdfDocument) { + if (this._pdfDocument) { + this.#reset(); } - } - get rotation() { - return this.pdfDocument ? this.pdfViewer.pagesRotation : 0; - } - set rotation(value) { - if (this.pdfDocument) { - this.pdfViewer.pagesRotation = value; + if (!pdfDocument) { + return; } + this._pdfDocument = pdfDocument; + this._firstPageCapability.resolve(); } - get isInPresentationMode() { - return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false; - } - async goToDestination(dest) { - if (!this.pdfDocument) { + #onFind(state) { + if (!state) { return; } - let namedDest, explicitDest, pageNumber; - if (typeof dest === "string") { - namedDest = dest; - explicitDest = await this.pdfDocument.getDestination(dest); - } else { - namedDest = null; - explicitDest = await dest; + const pdfDocument = this._pdfDocument; + const { + type + } = state; + if (this.#state === null || this.#shouldDirtyMatch(state)) { + this._dirtyMatch = true; } - if (!Array.isArray(explicitDest)) { - console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`); - return; + this.#state = state; + if (type !== "highlightallchange") { + this.#updateUIState(FindState.PENDING); } - const [destRef] = explicitDest; - if (destRef && typeof destRef === "object") { - pageNumber = this.pdfDocument.cachedPageNumber(destRef); - if (!pageNumber) { - try { - pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1; - } catch { - console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`); - return; - } + this._firstPageCapability.promise.then(() => { + if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { + return; + } + this.#extractText(); + const findbarClosed = !this._highlightMatches; + const pendingTimeout = !!this._findTimeout; + if (this._findTimeout) { + clearTimeout(this._findTimeout); + this._findTimeout = null; + } + if (!type) { + this._findTimeout = setTimeout(() => { + this.#nextMatch(); + this._findTimeout = null; + }, FIND_TIMEOUT); + } else if (this._dirtyMatch) { + this.#nextMatch(); + } else if (type === "again") { + this.#nextMatch(); + if (findbarClosed && this.#state.highlightAll) { + this.#updateAllPages(); + } + } else if (type === "highlightallchange") { + if (pendingTimeout) { + this.#nextMatch(); + } else { + this._highlightMatches = true; + } + this.#updateAllPages(); + } else { + this.#nextMatch(); } - } else if (Number.isInteger(destRef)) { - pageNumber = destRef + 1; - } - if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { - console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`); - return; - } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.push({ - namedDest, - explicitDest, - pageNumber - }); - } - this.pdfViewer.scrollPageIntoView({ - pageNumber, - destArray: explicitDest, - ignoreDestinationZoom: this._ignoreDestinationZoom }); } - goToPage(val) { - if (!this.pdfDocument) { + scrollMatchIntoView({ + element = null, + selectedLeft = 0, + pageIndex = -1, + matchIndex = -1 + }) { + if (!this._scrollMatches || !element) { return; - } - const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; - if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { - console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); + } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { + return; + } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { return; } - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.pushPage(pageNumber); + this._scrollMatches = false; + const spot = { + top: MATCH_SCROLL_OFFSET_TOP, + left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT + }; + scrollIntoView(element, spot, true); + } + #reset() { + this._highlightMatches = false; + this._scrollMatches = false; + this._pdfDocument = null; + this._pageMatches = []; + this._pageMatchesLength = []; + this.#visitedPagesCount = 0; + this.#state = null; + this._selected = { + pageIdx: -1, + matchIdx: -1 + }; + this._offset = { + pageIdx: null, + matchIdx: null, + wrapped: false + }; + this._extractTextPromises = []; + this._pageContents = []; + this._pageDiffs = []; + this._hasDiacritics = []; + this._matchesCountTotal = 0; + this._pagesToSearch = null; + this._pendingFindMatches = new Set(); + this._resumePageIdx = null; + this._dirtyMatch = false; + clearTimeout(this._findTimeout); + this._findTimeout = null; + this._firstPageCapability = Promise.withResolvers(); + } + get #query() { + const { + query + } = this.#state; + if (typeof query === "string") { + if (query !== this._rawQuery) { + this._rawQuery = query; + [this._normalizedQuery] = normalize(query); + } + return this._normalizedQuery; } - this.pdfViewer.scrollPageIntoView({ - pageNumber - }); + return (query || []).filter(q => !!q).map(q => normalize(q)[0]); } - addLinkAttributes(link, url, newWindow = false) { - if (!url || typeof url !== "string") { - throw new Error('A valid "url" parameter must provided.'); + #shouldDirtyMatch(state) { + const newQuery = state.query, + prevQuery = this.#state.query; + const newType = typeof newQuery, + prevType = typeof prevQuery; + if (newType !== prevType) { + return true; } - const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget, - rel = this.externalLinkRel; - if (this.externalLinkEnabled) { - link.href = link.title = url; - } else { - link.href = ""; - link.title = `Disabled: ${url}`; - link.onclick = () => false; + if (newType === "string") { + if (newQuery !== prevQuery) { + return true; + } + } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) { + return true; } - let targetStr = ""; - switch (target) { - case LinkTarget.NONE: - break; - case LinkTarget.SELF: - targetStr = "_self"; - break; - case LinkTarget.BLANK: - targetStr = "_blank"; - break; - case LinkTarget.PARENT: - targetStr = "_parent"; - break; - case LinkTarget.TOP: - targetStr = "_top"; - break; + switch (state.type) { + case "again": + const pageNumber = this._selected.pageIdx + 1; + const linkService = this._linkService; + return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true); + case "highlightallchange": + return false; } - link.target = targetStr; - link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; + return true; } - getDestinationHash(dest) { - if (typeof dest === "string") { - if (dest.length > 0) { - return this.getAnchorUrl("#" + escape(dest)); + #isEntireWord(content, startIdx, length) { + let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP); + if (match) { + const first = content.charCodeAt(startIdx); + const limit = match[1].charCodeAt(0); + if (getCharacterType(first) === getCharacterType(limit)) { + return false; } - } else if (Array.isArray(dest)) { - const str = JSON.stringify(dest); - if (str.length > 0) { - return this.getAnchorUrl("#" + escape(str)); + } + match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP); + if (match) { + const last = content.charCodeAt(startIdx + length - 1); + const limit = match[1].charCodeAt(0); + if (getCharacterType(last) === getCharacterType(limit)) { + return false; } } - return this.getAnchorUrl(""); - } - getAnchorUrl(anchor) { - return this.baseUrl ? this.baseUrl + anchor : anchor; + return true; } - setHash(hash) { - if (!this.pdfDocument) { - return; - } - let pageNumber, dest; - if (hash.includes("=")) { - const params = parseQueryString(hash); - if (params.has("search")) { - const query = params.get("search").replaceAll('"', ""), - phrase = params.get("phrase") === "true"; - this.eventBus.dispatch("findfromurlhash", { - source: this, - query: phrase ? query : query.match(/\S+/g) - }); + #convertToRegExpString(query, hasDiacritics) { + const { + matchDiacritics + } = this.#state; + let isUnicode = false; + query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => { + if (p1) { + return `[ ]*\\${p1}[ ]*`; } - if (params.has("page")) { - pageNumber = params.get("page") | 0 || 1; + if (p2) { + return `[ ]*${p2}[ ]*`; } - if (params.has("zoom")) { - const zoomArgs = params.get("zoom").split(","); - const zoomArg = zoomArgs[0]; - const zoomArgNumber = parseFloat(zoomArg); - if (!zoomArg.includes("Fit")) { - dest = [null, { - name: "XYZ" - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg]; - } else if (zoomArg === "Fit" || zoomArg === "FitB") { - dest = [null, { - name: zoomArg - }]; - } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") { - dest = [null, { - name: zoomArg - }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null]; - } else if (zoomArg === "FitR") { - if (zoomArgs.length !== 5) { - console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'); - } else { - dest = [null, { - name: zoomArg - }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0]; - } - } else { - console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`); - } + if (p3) { + return "[ ]+"; } - if (dest) { - this.pdfViewer.scrollPageIntoView({ - pageNumber: pageNumber || this.page, - destArray: dest, - allowNegativeOffset: true - }); - } else if (pageNumber) { - this.page = pageNumber; + if (matchDiacritics) { + return p4 || p5; } - if (params.has("pagemode")) { - this.eventBus.dispatch("pagemode", { - source: this, - mode: params.get("pagemode") - }); + if (p4) { + return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : ""; } - if (params.has("nameddest")) { - this.goToDestination(params.get("nameddest")); + if (hasDiacritics) { + isUnicode = true; + return `${p5}\\p{M}*`; } - return; + return p5; + }); + const trailingSpaces = "[ ]*"; + if (query.endsWith(trailingSpaces)) { + query = query.slice(0, query.length - trailingSpaces.length); } - dest = unescape(hash); - try { - dest = JSON.parse(dest); - if (!Array.isArray(dest)) { - dest = dest.toString(); + if (matchDiacritics) { + if (hasDiacritics) { + DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION); + isUnicode = true; + query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`; } - } catch {} - if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) { - this.goToDestination(dest); + } + return [isUnicode, query]; + } + #calculateMatch(pageIndex) { + const query = this.#query; + if (query.length === 0) { return; } - console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`); + const pageContent = this._pageContents[pageIndex]; + const matcherResult = this.match(query, pageContent, pageIndex); + const matches = this._pageMatches[pageIndex] = []; + const matchesLength = this._pageMatchesLength[pageIndex] = []; + const diffs = this._pageDiffs[pageIndex]; + matcherResult?.forEach(({ + index, + length + }) => { + const [matchPos, matchLen] = getOriginalIndex(diffs, index, length); + if (matchLen) { + matches.push(matchPos); + matchesLength.push(matchLen); + } + }); + if (this.#state.highlightAll) { + this.#updatePage(pageIndex); + } + if (this._resumePageIdx === pageIndex) { + this._resumePageIdx = null; + this.#nextPageMatch(); + } + const pageMatchesCount = matches.length; + this._matchesCountTotal += pageMatchesCount; + if (this.#updateMatchesCountOnProgress) { + if (pageMatchesCount > 0) { + this.#updateUIResultsCount(); + } + } else if (++this.#visitedPagesCount === this._linkService.pagesCount) { + this.#updateUIResultsCount(); + } } - executeNamedAction(action) { - if (!this.pdfDocument) { + match(query, pageContent, pageIndex) { + const hasDiacritics = this._hasDiacritics[pageIndex]; + let isUnicode = false; + if (typeof query === "string") { + [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics); + } else { + query = query.sort().reverse().map(q => { + const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics); + isUnicode ||= isUnicodePart; + return `(${queryPart})`; + }).join("|"); + } + if (!query) { + return undefined; + } + const { + caseSensitive, + entireWord + } = this.#state; + const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`; + query = new RegExp(query, flags); + const matches = []; + let match; + while ((match = query.exec(pageContent)) !== null) { + if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) { + continue; + } + matches.push({ + index: match.index, + length: match[0].length + }); + } + return matches; + } + #extractText() { + if (this._extractTextPromises.length > 0) { return; } - switch (action) { - case "GoBack": - this.pdfHistory?.back(); - break; - case "GoForward": - this.pdfHistory?.forward(); - break; - case "NextPage": - this.pdfViewer.nextPage(); - break; - case "PrevPage": - this.pdfViewer.previousPage(); - break; - case "LastPage": - this.page = this.pagesCount; - break; - case "FirstPage": - this.page = 1; - break; - default: - break; + let deferred = Promise.resolve(); + const textOptions = { + disableNormalization: true + }; + for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { + const { + promise, + resolve + } = Promise.withResolvers(); + this._extractTextPromises[i] = promise; + deferred = deferred.then(() => { + return this._pdfDocument.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => { + const strBuf = []; + for (const textItem of textContent.items) { + strBuf.push(textItem.str); + if (textItem.hasEOL) { + strBuf.push("\n"); + } + } + [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join("")); + resolve(); + }, reason => { + console.error(`Unable to get text content for page ${i + 1}`, reason); + this._pageContents[i] = ""; + this._pageDiffs[i] = null; + this._hasDiacritics[i] = false; + resolve(); + }); + }); } - this.eventBus.dispatch("namedaction", { + } + #updatePage(index) { + if (this._scrollMatches && this._selected.pageIdx === index) { + this._linkService.page = index + 1; + } + this._eventBus.dispatch("updatetextlayermatches", { source: this, - action + pageIndex: index }); } - async executeSetOCGState(action) { - if (!this.pdfDocument) { + #updateAllPages() { + this._eventBus.dispatch("updatetextlayermatches", { + source: this, + pageIndex: -1 + }); + } + #nextMatch() { + const previous = this.#state.findPrevious; + const currentPageIndex = this._linkService.page - 1; + const numPages = this._linkService.pagesCount; + this._highlightMatches = true; + if (this._dirtyMatch) { + this._dirtyMatch = false; + this._selected.pageIdx = this._selected.matchIdx = -1; + this._offset.pageIdx = currentPageIndex; + this._offset.matchIdx = null; + this._offset.wrapped = false; + this._resumePageIdx = null; + this._pageMatches.length = 0; + this._pageMatchesLength.length = 0; + this.#visitedPagesCount = 0; + this._matchesCountTotal = 0; + this.#updateAllPages(); + for (let i = 0; i < numPages; i++) { + if (this._pendingFindMatches.has(i)) { + continue; + } + this._pendingFindMatches.add(i); + this._extractTextPromises[i].then(() => { + this._pendingFindMatches.delete(i); + this.#calculateMatch(i); + }); + } + } + const query = this.#query; + if (query.length === 0) { + this.#updateUIState(FindState.FOUND); return; } - const pdfDocument = this.pdfDocument, - optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise; - if (pdfDocument !== this.pdfDocument) { + if (this._resumePageIdx) { return; } - optionalContentConfig.setOCGState(action); - this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig); + const offset = this._offset; + this._pagesToSearch = numPages; + if (offset.matchIdx !== null) { + const numPageMatches = this._pageMatches[offset.pageIdx].length; + if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { + offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; + this.#updateMatch(true); + return; + } + this.#advanceOffsetPage(previous); + } + this.#nextPageMatch(); } - static #isValidExplicitDest(dest) { - if (!Array.isArray(dest) || dest.length < 2) { - return false; + #matchesReady(matches) { + const offset = this._offset; + const numMatches = matches.length; + const previous = this.#state.findPrevious; + if (numMatches) { + offset.matchIdx = previous ? numMatches - 1 : 0; + this.#updateMatch(true); + return true; } - const [page, zoom, ...args] = dest; - if (!(typeof page === "object" && Number.isInteger(page?.num) && Number.isInteger(page?.gen)) && !Number.isInteger(page)) { - return false; + this.#advanceOffsetPage(previous); + if (offset.wrapped) { + offset.matchIdx = null; + if (this._pagesToSearch < 0) { + this.#updateMatch(false); + return true; + } } - if (!(typeof zoom === "object" && typeof zoom?.name === "string")) { - return false; + return false; + } + #nextPageMatch() { + if (this._resumePageIdx !== null) { + console.error("There can only be one pending page."); } - const argsLen = args.length; - let allowNull = true; - switch (zoom.name) { - case "XYZ": - if (argsLen < 2 || argsLen > 3) { - return false; - } - break; - case "Fit": - case "FitB": - return argsLen === 0; - case "FitH": - case "FitBH": - case "FitV": - case "FitBV": - if (argsLen > 1) { - return false; - } - break; - case "FitR": - if (argsLen !== 4) { - return false; - } - allowNull = false; + let matches = null; + do { + const pageIdx = this._offset.pageIdx; + matches = this._pageMatches[pageIdx]; + if (!matches) { + this._resumePageIdx = pageIdx; break; - default: - return false; - } - for (const arg of args) { - if (!(typeof arg === "number" || allowNull && arg === null)) { - return false; } - } - return true; - } -} -class SimpleLinkService extends PDFLinkService { - setDocument(pdfDocument, baseUrl = null) {} -} - -;// ./web/pdfjs.js -const { - AbortException, - AnnotationEditorLayer, - AnnotationEditorParamsType, - AnnotationEditorType, - AnnotationEditorUIManager, - AnnotationLayer, - AnnotationMode, - build, - ColorPicker, - createValidAbsoluteUrl, - DOMSVGFactory, - DrawLayer, - FeatureTest, - fetchData, - getDocument, - getFilenameFromUrl, - getPdfFilenameFromUrl: pdfjs_getPdfFilenameFromUrl, - getXfaPageViewport, - GlobalWorkerOptions, - ImageKind, - InvalidPDFException, - isDataScheme, - isPdfFile, - MissingPDFException, - noContextMenu, - normalizeUnicode, - OPS, - OutputScale, - PasswordResponses, - PDFDataRangeTransport, - PDFDateString, - PDFWorker, - PermissionFlag, - PixelsPerInch, - RenderingCancelledException, - setLayerDimensions, - shadow, - stopEvent, - TextLayer, - TouchManager, - UnexpectedResponseException, - Util, - VerbosityLevel, - version, - XfaLayer -} = globalThis.pdfjsLib; - -;// ./web/event_utils.js -const WaitOnType = { - EVENT: "event", - TIMEOUT: "timeout" -}; -async function waitOnEventOrTimeout({ - target, - name, - delay = 0 -}) { - if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { - throw new Error("waitOnEventOrTimeout - invalid parameters."); - } - const { - promise, - resolve - } = Promise.withResolvers(); - const ac = new AbortController(); - function handler(type) { - ac.abort(); - clearTimeout(timeout); - resolve(type); - } - const evtMethod = target instanceof EventBus ? "_on" : "addEventListener"; - target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), { - signal: ac.signal - }); - const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay); - return promise; -} -class EventBus { - #listeners = Object.create(null); - on(eventName, listener, options = null) { - this._on(eventName, listener, { - external: true, - once: options?.once, - signal: options?.signal - }); - } - off(eventName, listener, options = null) { - this._off(eventName, listener); + } while (!this.#matchesReady(matches)); } - dispatch(eventName, data) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners || eventListeners.length === 0) { - return; + #advanceOffsetPage(previous) { + const offset = this._offset; + const numPages = this._linkService.pagesCount; + offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; + offset.matchIdx = null; + this._pagesToSearch--; + if (offset.pageIdx >= numPages || offset.pageIdx < 0) { + offset.pageIdx = previous ? numPages - 1 : 0; + offset.wrapped = true; } - let externalListeners; - for (const { - listener, - external, - once - } of eventListeners.slice(0)) { - if (once) { - this._off(eventName, listener); - } - if (external) { - (externalListeners ||= []).push(listener); - continue; + } + #updateMatch(found = false) { + let state = FindState.NOT_FOUND; + const wrapped = this._offset.wrapped; + this._offset.wrapped = false; + if (found) { + const previousPage = this._selected.pageIdx; + this._selected.pageIdx = this._offset.pageIdx; + this._selected.matchIdx = this._offset.matchIdx; + state = wrapped ? FindState.WRAPPED : FindState.FOUND; + if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { + this.#updatePage(previousPage); } - listener(data); } - if (externalListeners) { - for (const listener of externalListeners) { - listener(data); - } - externalListeners = null; + this.#updateUIState(state, this.#state.findPrevious); + if (this._selected.pageIdx !== -1) { + this._scrollMatches = true; + this.#updatePage(this._selected.pageIdx); } } - _on(eventName, listener, options = null) { - let rmAbort = null; - if (options?.signal instanceof AbortSignal) { - const { - signal - } = options; - if (signal.aborted) { - console.error("Cannot use an `aborted` signal."); + #onFindBarClose(evt) { + const pdfDocument = this._pdfDocument; + this._firstPageCapability.promise.then(() => { + if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { return; } - const onAbort = () => this._off(eventName, listener); - rmAbort = () => signal.removeEventListener("abort", onAbort); - signal.addEventListener("abort", onAbort); + if (this._findTimeout) { + clearTimeout(this._findTimeout); + this._findTimeout = null; + } + if (this._resumePageIdx) { + this._resumePageIdx = null; + this._dirtyMatch = true; + } + this.#updateUIState(FindState.FOUND); + this._highlightMatches = false; + this.#updateAllPages(); + }); + } + #requestMatchesCount() { + const { + pageIdx, + matchIdx + } = this._selected; + let current = 0, + total = this._matchesCountTotal; + if (matchIdx !== -1) { + for (let i = 0; i < pageIdx; i++) { + current += this._pageMatches[i]?.length || 0; + } + current += matchIdx + 1; } - const eventListeners = this.#listeners[eventName] ||= []; - eventListeners.push({ - listener, - external: options?.external === true, - once: options?.once === true, - rmAbort + if (current < 1 || current > total) { + current = total = 0; + } + return { + current, + total + }; + } + #updateUIResultsCount() { + this._eventBus.dispatch("updatefindmatchescount", { + source: this, + matchesCount: this.#requestMatchesCount() }); } - _off(eventName, listener, options = null) { - const eventListeners = this.#listeners[eventName]; - if (!eventListeners) { + #updateUIState(state, previous = false) { + if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) { return; } - for (let i = 0, ii = eventListeners.length; i < ii; i++) { - const evt = eventListeners[i]; - if (evt.listener === listener) { - evt.rmAbort?.(); - eventListeners.splice(i, 1); - return; - } - } + this._eventBus.dispatch("updatefindcontrolstate", { + source: this, + state, + previous, + entireWord: this.#state?.entireWord ?? null, + matchesCount: this.#requestMatchesCount(), + rawQuery: this.#state?.query ?? null + }); } } -class FirefoxEventBus extends EventBus { - #externalServices; - #globalEventNames; - #isInAutomation; - constructor(globalEventNames, externalServices, isInAutomation) { - super(); - this.#globalEventNames = globalEventNames; - this.#externalServices = externalServices; - this.#isInAutomation = isInAutomation; - } - dispatch(eventName, data) { - throw new Error("Not implemented: FirefoxEventBus.dispatch"); - } -} - -;// ./web/external_services.js -class BaseExternalServices { - updateFindControlState(data) {} - updateFindMatchesCount(data) {} - initPassiveLoading() {} - reportTelemetry(data) {} - async createL10n() { - throw new Error("Not implemented: createL10n"); - } - createScripting() { - throw new Error("Not implemented: createScripting"); - } - updateEditorStates(data) { - throw new Error("Not implemented: updateEditorStates"); - } - dispatchGlobalEvent(_event) {} -} -;// ./web/preferences.js +;// ./web/pdf_link_service.js -class BasePreferences { - #defaults = Object.freeze({ - altTextLearnMoreUrl: "", - annotationEditorMode: 0, - annotationMode: 2, - cursorToolOnLoad: 0, - defaultZoomDelay: 400, - defaultZoomValue: "", - disablePageLabels: false, - enableAltText: false, - enableAltTextModelDownload: true, - enableGuessAltText: true, - enableHighlightFloatingButton: false, - enableNewAltTextWhenAddingImage: true, - enablePermissions: false, - enablePrintAutoRotate: true, - enableScripting: true, - enableUpdatedAddImage: false, - externalLinkTarget: 0, - highlightEditorColors: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", - historyUpdateUrl: false, - ignoreDestinationZoom: false, - forcePageColors: false, - pageColorsBackground: "Canvas", - pageColorsForeground: "CanvasText", - pdfBugEnabled: false, - sidebarViewOnLoad: -1, - scrollModeOnLoad: -1, - spreadModeOnLoad: -1, - textLayerMode: 1, - viewOnLoad: 0, - disableAutoFetch: false, - disableFontFace: false, - disableRange: false, - disableStream: false, - enableHWA: true, - enableXfa: true, - viewerCssTheme: 0 - }); - #initializedPromise = null; - constructor() { - this.#initializedPromise = this._readFromStorage(this.#defaults).then(({ - browserPrefs, - prefs - }) => { - if (AppOptions._checkDisablePreferences()) { - return; - } - AppOptions.setAll({ - ...browserPrefs, - ...prefs - }, true); - }); - } - async _writeToStorage(prefObj) { - throw new Error("Not implemented: _writeToStorage"); - } - async _readFromStorage(prefObj) { - throw new Error("Not implemented: _readFromStorage"); - } - async reset() { - await this.#initializedPromise; - AppOptions.setAll(this.#defaults, true); - await this._writeToStorage(this.#defaults); - } - async set(name, value) { - await this.#initializedPromise; - AppOptions.setAll({ - [name]: value - }, true); - await this._writeToStorage(AppOptions.getAll(OptionKind.PREFERENCE)); - } - async get(name) { - await this.#initializedPromise; - return AppOptions.get(name); - } - get initializedPromise() { - return this.#initializedPromise; +const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; +const LinkTarget = { + NONE: 0, + SELF: 1, + BLANK: 2, + PARENT: 3, + TOP: 4 +}; +class PDFLinkService { + externalLinkEnabled = true; + constructor({ + eventBus, + externalLinkTarget = null, + externalLinkRel = null, + ignoreDestinationZoom = false + } = {}) { + this.eventBus = eventBus; + this.externalLinkTarget = externalLinkTarget; + this.externalLinkRel = externalLinkRel; + this._ignoreDestinationZoom = ignoreDestinationZoom; + this.baseUrl = null; + this.pdfDocument = null; + this.pdfViewer = null; + this.pdfHistory = null; } -} - -;// ./node_modules/@fluent/bundle/esm/types.js -class FluentType { - constructor(value) { - this.value = value; + setDocument(pdfDocument, baseUrl = null) { + this.baseUrl = baseUrl; + this.pdfDocument = pdfDocument; } - valueOf() { - return this.value; + setViewer(pdfViewer) { + this.pdfViewer = pdfViewer; } -} -class FluentNone extends FluentType { - constructor(value = "???") { - super(value); + setHistory(pdfHistory) { + this.pdfHistory = pdfHistory; } - toString(scope) { - return `{${this.value}}`; + get pagesCount() { + return this.pdfDocument ? this.pdfDocument.numPages : 0; } -} -class FluentNumber extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; + get page() { + return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1; } - toString(scope) { - try { - const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts); - return nf.format(this.value); - } catch (err) { - scope.reportError(err); - return this.value.toString(10); + set page(value) { + if (this.pdfDocument) { + this.pdfViewer.currentPageNumber = value; } } -} -class FluentDateTime extends FluentType { - constructor(value, opts = {}) { - super(value); - this.opts = opts; + get rotation() { + return this.pdfDocument ? this.pdfViewer.pagesRotation : 0; } - toString(scope) { - try { - const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts); - return dtf.format(this.value); - } catch (err) { - scope.reportError(err); - return new Date(this.value).toISOString(); + set rotation(value) { + if (this.pdfDocument) { + this.pdfViewer.pagesRotation = value; } } -} -;// ./node_modules/@fluent/bundle/esm/resolver.js - -const MAX_PLACEABLES = 100; -const FSI = "\u2068"; -const PDI = "\u2069"; -function match(scope, selector, key) { - if (key === selector) { - return true; - } - if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) { - return true; + get isInPresentationMode() { + return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false; } - if (selector instanceof FluentNumber && typeof key === "string") { - let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value); - if (key === category) { - return true; + async goToDestination(dest) { + if (!this.pdfDocument) { + return; } - } - return false; -} -function getDefault(scope, variants, star) { - if (variants[star]) { - return resolvePattern(scope, variants[star].value); - } - scope.reportError(new RangeError("No default")); - return new FluentNone(); -} -function getArguments(scope, args) { - const positional = []; - const named = Object.create(null); - for (const arg of args) { - if (arg.type === "narg") { - named[arg.name] = resolveExpression(scope, arg.value); + let namedDest, explicitDest, pageNumber; + if (typeof dest === "string") { + namedDest = dest; + explicitDest = await this.pdfDocument.getDestination(dest); } else { - positional.push(resolveExpression(scope, arg)); + namedDest = null; + explicitDest = await dest; } - } - return { - positional, - named - }; -} -function resolveExpression(scope, expr) { - switch (expr.type) { - case "str": - return expr.value; - case "num": - return new FluentNumber(expr.value, { - minimumFractionDigits: expr.precision + if (!Array.isArray(explicitDest)) { + console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`); + return; + } + const [destRef] = explicitDest; + if (destRef && typeof destRef === "object") { + pageNumber = this.pdfDocument.cachedPageNumber(destRef); + if (!pageNumber) { + try { + pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1; + } catch { + console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`); + return; + } + } + } else if (Number.isInteger(destRef)) { + pageNumber = destRef + 1; + } + if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { + console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`); + return; + } + if (this.pdfHistory) { + this.pdfHistory.pushCurrentPosition(); + this.pdfHistory.push({ + namedDest, + explicitDest, + pageNumber }); - case "var": - return resolveVariableReference(scope, expr); - case "mesg": - return resolveMessageReference(scope, expr); - case "term": - return resolveTermReference(scope, expr); - case "func": - return resolveFunctionReference(scope, expr); - case "select": - return resolveSelectExpression(scope, expr); - default: - return new FluentNone(); - } -} -function resolveVariableReference(scope, { - name -}) { - let arg; - if (scope.params) { - if (Object.prototype.hasOwnProperty.call(scope.params, name)) { - arg = scope.params[name]; - } else { - return new FluentNone(`$${name}`); } - } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) { - arg = scope.args[name]; - } else { - scope.reportError(new ReferenceError(`Unknown variable: $${name}`)); - return new FluentNone(`$${name}`); + this.pdfViewer.scrollPageIntoView({ + pageNumber, + destArray: explicitDest, + ignoreDestinationZoom: this._ignoreDestinationZoom + }); } - if (arg instanceof FluentType) { - return arg; + goToPage(val) { + if (!this.pdfDocument) { + return; + } + const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; + if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { + console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); + return; + } + if (this.pdfHistory) { + this.pdfHistory.pushCurrentPosition(); + this.pdfHistory.pushPage(pageNumber); + } + this.pdfViewer.scrollPageIntoView({ + pageNumber + }); } - switch (typeof arg) { - case "string": - return arg; - case "number": - return new FluentNumber(arg); - case "object": - if (arg instanceof Date) { - return new FluentDateTime(arg.getTime()); - } - default: - scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)); - return new FluentNone(`$${name}`); - } -} -function resolveMessageReference(scope, { - name, - attr -}) { - const message = scope.bundle._messages.get(name); - if (!message) { - scope.reportError(new ReferenceError(`Unknown message: ${name}`)); - return new FluentNone(name); - } - if (attr) { - const attribute = message.attributes[attr]; - if (attribute) { - return resolvePattern(scope, attribute); + addLinkAttributes(link, url, newWindow = false) { + if (!url || typeof url !== "string") { + throw new Error('A valid "url" parameter must provided.'); } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${name}.${attr}`); - } - if (message.value) { - return resolvePattern(scope, message.value); - } - scope.reportError(new ReferenceError(`No value: ${name}`)); - return new FluentNone(name); -} -function resolveTermReference(scope, { - name, - attr, - args -}) { - const id = `-${name}`; - const term = scope.bundle._terms.get(id); - if (!term) { - scope.reportError(new ReferenceError(`Unknown term: ${id}`)); - return new FluentNone(id); - } - if (attr) { - const attribute = term.attributes[attr]; - if (attribute) { - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, attribute); - scope.params = null; - return resolved; + const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget, + rel = this.externalLinkRel; + if (this.externalLinkEnabled) { + link.href = link.title = url; + } else { + link.href = ""; + link.title = `Disabled: ${url}`; + link.onclick = () => false; } - scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); - return new FluentNone(`${id}.${attr}`); - } - scope.params = getArguments(scope, args).named; - const resolved = resolvePattern(scope, term.value); - scope.params = null; - return resolved; -} -function resolveFunctionReference(scope, { - name, - args -}) { - let func = scope.bundle._functions[name]; - if (!func) { - scope.reportError(new ReferenceError(`Unknown function: ${name}()`)); - return new FluentNone(`${name}()`); - } - if (typeof func !== "function") { - scope.reportError(new TypeError(`Function ${name}() is not callable`)); - return new FluentNone(`${name}()`); - } - try { - let resolved = getArguments(scope, args); - return func(resolved.positional, resolved.named); - } catch (err) { - scope.reportError(err); - return new FluentNone(`${name}()`); - } -} -function resolveSelectExpression(scope, { - selector, - variants, - star -}) { - let sel = resolveExpression(scope, selector); - if (sel instanceof FluentNone) { - return getDefault(scope, variants, star); + let targetStr = ""; + switch (target) { + case LinkTarget.NONE: + break; + case LinkTarget.SELF: + targetStr = "_self"; + break; + case LinkTarget.BLANK: + targetStr = "_blank"; + break; + case LinkTarget.PARENT: + targetStr = "_parent"; + break; + case LinkTarget.TOP: + targetStr = "_top"; + break; + } + link.target = targetStr; + link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; } - for (const variant of variants) { - const key = resolveExpression(scope, variant.key); - if (match(scope, sel, key)) { - return resolvePattern(scope, variant.value); + getDestinationHash(dest) { + if (typeof dest === "string") { + if (dest.length > 0) { + return this.getAnchorUrl("#" + escape(dest)); + } + } else if (Array.isArray(dest)) { + const str = JSON.stringify(dest); + if (str.length > 0) { + return this.getAnchorUrl("#" + escape(str)); + } } + return this.getAnchorUrl(""); } - return getDefault(scope, variants, star); -} -function resolveComplexPattern(scope, ptn) { - if (scope.dirty.has(ptn)) { - scope.reportError(new RangeError("Cyclic reference")); - return new FluentNone(); + getAnchorUrl(anchor) { + return this.baseUrl ? this.baseUrl + anchor : anchor; } - scope.dirty.add(ptn); - const result = []; - const useIsolating = scope.bundle._useIsolating && ptn.length > 1; - for (const elem of ptn) { - if (typeof elem === "string") { - result.push(scope.bundle._transform(elem)); - continue; - } - scope.placeables++; - if (scope.placeables > MAX_PLACEABLES) { - scope.dirty.delete(ptn); - throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`); + setHash(hash) { + if (!this.pdfDocument) { + return; } - if (useIsolating) { - result.push(FSI); + let pageNumber, dest; + if (hash.includes("=")) { + const params = parseQueryString(hash); + if (params.has("search")) { + const query = params.get("search").replaceAll('"', ""), + phrase = params.get("phrase") === "true"; + this.eventBus.dispatch("findfromurlhash", { + source: this, + query: phrase ? query : query.match(/\S+/g) + }); + } + if (params.has("page")) { + pageNumber = params.get("page") | 0 || 1; + } + if (params.has("zoom")) { + const zoomArgs = params.get("zoom").split(","); + const zoomArg = zoomArgs[0]; + const zoomArgNumber = parseFloat(zoomArg); + if (!zoomArg.includes("Fit")) { + dest = [null, { + name: "XYZ" + }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg]; + } else if (zoomArg === "Fit" || zoomArg === "FitB") { + dest = [null, { + name: zoomArg + }]; + } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") { + dest = [null, { + name: zoomArg + }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null]; + } else if (zoomArg === "FitR") { + if (zoomArgs.length !== 5) { + console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'); + } else { + dest = [null, { + name: zoomArg + }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0]; + } + } else { + console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`); + } + } + if (dest) { + this.pdfViewer.scrollPageIntoView({ + pageNumber: pageNumber || this.page, + destArray: dest, + allowNegativeOffset: true + }); + } else if (pageNumber) { + this.page = pageNumber; + } + if (params.has("pagemode")) { + this.eventBus.dispatch("pagemode", { + source: this, + mode: params.get("pagemode") + }); + } + if (params.has("nameddest")) { + this.goToDestination(params.get("nameddest")); + } + return; } - result.push(resolveExpression(scope, elem).toString(scope)); - if (useIsolating) { - result.push(PDI); + dest = unescape(hash); + try { + dest = JSON.parse(dest); + if (!Array.isArray(dest)) { + dest = dest.toString(); + } + } catch {} + if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) { + this.goToDestination(dest); + return; } + console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`); } - scope.dirty.delete(ptn); - return result.join(""); -} -function resolvePattern(scope, value) { - if (typeof value === "string") { - return scope.bundle._transform(value); - } - return resolveComplexPattern(scope, value); -} -;// ./node_modules/@fluent/bundle/esm/scope.js -class Scope { - constructor(bundle, errors, args) { - this.dirty = new WeakSet(); - this.params = null; - this.placeables = 0; - this.bundle = bundle; - this.errors = errors; - this.args = args; - } - reportError(error) { - if (!this.errors || !(error instanceof Error)) { - throw error; + executeNamedAction(action) { + if (!this.pdfDocument) { + return; } - this.errors.push(error); - } - memoizeIntlObject(ctor, opts) { - let cache = this.bundle._intls.get(ctor); - if (!cache) { - cache = {}; - this.bundle._intls.set(ctor, cache); - } - let id = JSON.stringify(opts); - if (!cache[id]) { - cache[id] = new ctor(this.bundle.locales, opts); - } - return cache[id]; - } -} -;// ./node_modules/@fluent/bundle/esm/builtins.js - -function values(opts, allowed) { - const unwrapped = Object.create(null); - for (const [name, opt] of Object.entries(opts)) { - if (allowed.includes(name)) { - unwrapped[name] = opt.valueOf(); + switch (action) { + case "GoBack": + this.pdfHistory?.back(); + break; + case "GoForward": + this.pdfHistory?.forward(); + break; + case "NextPage": + this.pdfViewer.nextPage(); + break; + case "PrevPage": + this.pdfViewer.previousPage(); + break; + case "LastPage": + this.page = this.pagesCount; + break; + case "FirstPage": + this.page = 1; + break; + default: + break; } - } - return unwrapped; -} -const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"]; -function NUMBER(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`NUMBER(${arg.valueOf()})`); - } - if (arg instanceof FluentNumber) { - return new FluentNumber(arg.valueOf(), { - ...arg.opts, - ...values(opts, NUMBER_ALLOWED) - }); - } - if (arg instanceof FluentDateTime) { - return new FluentNumber(arg.valueOf(), { - ...values(opts, NUMBER_ALLOWED) + this.eventBus.dispatch("namedaction", { + source: this, + action }); } - throw new TypeError("Invalid argument to NUMBER"); -} -const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"]; -function DATETIME(args, opts) { - let arg = args[0]; - if (arg instanceof FluentNone) { - return new FluentNone(`DATETIME(${arg.valueOf()})`); - } - if (arg instanceof FluentDateTime) { - return new FluentDateTime(arg.valueOf(), { - ...arg.opts, - ...values(opts, DATETIME_ALLOWED) - }); + async executeSetOCGState(action) { + if (!this.pdfDocument) { + return; + } + const pdfDocument = this.pdfDocument, + optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise; + if (pdfDocument !== this.pdfDocument) { + return; + } + optionalContentConfig.setOCGState(action); + this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig); } - if (arg instanceof FluentNumber) { - return new FluentDateTime(arg.valueOf(), { - ...values(opts, DATETIME_ALLOWED) - }); + static #isValidExplicitDest(dest) { + if (!Array.isArray(dest) || dest.length < 2) { + return false; + } + const [page, zoom, ...args] = dest; + if (!(typeof page === "object" && Number.isInteger(page?.num) && Number.isInteger(page?.gen)) && !Number.isInteger(page)) { + return false; + } + if (!(typeof zoom === "object" && typeof zoom?.name === "string")) { + return false; + } + const argsLen = args.length; + let allowNull = true; + switch (zoom.name) { + case "XYZ": + if (argsLen < 2 || argsLen > 3) { + return false; + } + break; + case "Fit": + case "FitB": + return argsLen === 0; + case "FitH": + case "FitBH": + case "FitV": + case "FitBV": + if (argsLen > 1) { + return false; + } + break; + case "FitR": + if (argsLen !== 4) { + return false; + } + allowNull = false; + break; + default: + return false; + } + for (const arg of args) { + if (!(typeof arg === "number" || allowNull && arg === null)) { + return false; + } + } + return true; } - throw new TypeError("Invalid argument to DATETIME"); } -;// ./node_modules/@fluent/bundle/esm/memoizer.js -const cache = new Map(); -function getMemoizerForLocale(locales) { - const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales; - let memoizer = cache.get(stringLocale); - if (memoizer === undefined) { - memoizer = new Map(); - cache.set(stringLocale, memoizer); - } - return memoizer; +class SimpleLinkService extends PDFLinkService { + setDocument(pdfDocument, baseUrl = null) {} } -;// ./node_modules/@fluent/bundle/esm/bundle.js - +;// ./web/pdfjs.js +const { + AbortException, + AnnotationEditorLayer, + AnnotationEditorParamsType, + AnnotationEditorType, + AnnotationEditorUIManager, + AnnotationLayer, + AnnotationMode, + build, + ColorPicker, + createValidAbsoluteUrl, + DOMSVGFactory, + DrawLayer, + FeatureTest, + fetchData, + getDocument, + getFilenameFromUrl, + getPdfFilenameFromUrl, + getXfaPageViewport, + GlobalWorkerOptions, + ImageKind, + InvalidPDFException, + isDataScheme, + isPdfFile, + MissingPDFException, + noContextMenu, + normalizeUnicode, + OPS, + OutputScale, + PasswordResponses, + PDFDataRangeTransport, + PDFDateString, + PDFWorker, + PermissionFlag, + PixelsPerInch, + RenderingCancelledException, + setLayerDimensions, + shadow, + stopEvent, + TextLayer, + TouchManager, + UnexpectedResponseException, + Util, + VerbosityLevel, + version, + XfaLayer +} = globalThis.pdfjsLib; +;// ./web/annotation_layer_builder.js -class FluentBundle { - constructor(locales, { - functions, - useIsolating = true, - transform = v => v - } = {}) { - this._terms = new Map(); - this._messages = new Map(); - this.locales = Array.isArray(locales) ? locales : [locales]; - this._functions = { - NUMBER: NUMBER, - DATETIME: DATETIME, - ...functions - }; - this._useIsolating = useIsolating; - this._transform = transform; - this._intls = getMemoizerForLocale(locales); - } - hasMessage(id) { - return this._messages.has(id); - } - getMessage(id) { - return this._messages.get(id); +class AnnotationLayerBuilder { + #onAppend = null; + #eventAbortController = null; + constructor({ + pdfPage, + linkService, + downloadManager, + annotationStorage = null, + imageResourcesPath = "", + renderForms = true, + enableScripting = false, + hasJSActionsPromise = null, + fieldObjectsPromise = null, + annotationCanvasMap = null, + accessibilityManager = null, + annotationEditorUIManager = null, + onAppend = null + }) { + this.pdfPage = pdfPage; + this.linkService = linkService; + this.downloadManager = downloadManager; + this.imageResourcesPath = imageResourcesPath; + this.renderForms = renderForms; + this.annotationStorage = annotationStorage; + this.enableScripting = enableScripting; + this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false); + this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null); + this._annotationCanvasMap = annotationCanvasMap; + this._accessibilityManager = accessibilityManager; + this._annotationEditorUIManager = annotationEditorUIManager; + this.#onAppend = onAppend; + this.annotationLayer = null; + this.div = null; + this._cancelled = false; + this._eventBus = linkService.eventBus; } - addResource(res, { - allowOverrides = false - } = {}) { - const errors = []; - for (let i = 0; i < res.body.length; i++) { - let entry = res.body[i]; - if (entry.id.startsWith("-")) { - if (allowOverrides === false && this._terms.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`)); - continue; - } - this._terms.set(entry.id, entry); - } else { - if (allowOverrides === false && this._messages.has(entry.id)) { - errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`)); - continue; - } - this._messages.set(entry.id, entry); + async render(viewport, options, intent = "display") { + if (this.div) { + if (this._cancelled || !this.annotationLayer) { + return; } + this.annotationLayer.update({ + viewport: viewport.clone({ + dontFlip: true + }) + }); + return; } - return errors; - } - formatPattern(pattern, args = null, errors = null) { - if (typeof pattern === "string") { - return this._transform(pattern); - } - let scope = new Scope(this, errors, args); - try { - let value = resolveComplexPattern(scope, pattern); - return value.toString(scope); - } catch (err) { - if (scope.errors && err instanceof Error) { - scope.errors.push(err); - return new FluentNone().toString(scope); - } - throw err; + const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({ + intent + }), this._hasJSActionsPromise, this._fieldObjectsPromise]); + if (this._cancelled) { + return; } - } -} -;// ./node_modules/@fluent/bundle/esm/resource.js -const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm; -const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y; -const RE_VARIANT_START = /\*?\[/y; -const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y; -const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y; -const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y; -const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; -const RE_TEXT_RUN = /([^{}\n\r]+)/y; -const RE_STRING_RUN = /([^\\"\n\r]*)/y; -const RE_STRING_ESCAPE = /\\([\\"])/y; -const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; -const RE_LEADING_NEWLINES = /^\n+/; -const RE_TRAILING_SPACES = / +$/; -const RE_BLANK_LINES = / *\r?\n/g; -const RE_INDENT = /( *)$/; -const TOKEN_BRACE_OPEN = /{\s*/y; -const TOKEN_BRACE_CLOSE = /\s*}/y; -const TOKEN_BRACKET_OPEN = /\[\s*/y; -const TOKEN_BRACKET_CLOSE = /\s*] */y; -const TOKEN_PAREN_OPEN = /\s*\(\s*/y; -const TOKEN_ARROW = /\s*->\s*/y; -const TOKEN_COLON = /\s*:\s*/y; -const TOKEN_COMMA = /\s*,?\s*/y; -const TOKEN_BLANK = /\s+/y; -class FluentResource { - constructor(source) { - this.body = []; - RE_MESSAGE_START.lastIndex = 0; - let cursor = 0; - while (true) { - let next = RE_MESSAGE_START.exec(source); - if (next === null) { - break; - } - cursor = RE_MESSAGE_START.lastIndex; - try { - this.body.push(parseMessage(next[1])); - } catch (err) { - if (err instanceof SyntaxError) { - continue; - } - throw err; - } + const div = this.div = document.createElement("div"); + div.className = "annotationLayer"; + this.#onAppend?.(div); + if (annotations.length === 0) { + this.hide(); + return; } - function test(re) { - re.lastIndex = cursor; - return re.test(source); + this.annotationLayer = new AnnotationLayer({ + div, + accessibilityManager: this._accessibilityManager, + annotationCanvasMap: this._annotationCanvasMap, + annotationEditorUIManager: this._annotationEditorUIManager, + page: this.pdfPage, + viewport: viewport.clone({ + dontFlip: true + }), + structTreeLayer: options?.structTreeLayer || null + }); + await this.annotationLayer.render({ + annotations, + imageResourcesPath: this.imageResourcesPath, + renderForms: this.renderForms, + linkService: this.linkService, + downloadManager: this.downloadManager, + annotationStorage: this.annotationStorage, + enableScripting: this.enableScripting, + hasJSActions, + fieldObjects + }); + if (this.linkService.isInPresentationMode) { + this.#updatePresentationModeState(PresentationModeState.FULLSCREEN); } - function consumeChar(char, errorClass) { - if (source[cursor] === char) { - cursor++; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${char}`); - } - return false; + if (!this.#eventAbortController) { + this.#eventAbortController = new AbortController(); + this._eventBus?._on("presentationmodechanged", evt => { + this.#updatePresentationModeState(evt.state); + }, { + signal: this.#eventAbortController.signal + }); } - function consumeToken(re, errorClass) { - if (test(re)) { - cursor = re.lastIndex; - return true; - } - if (errorClass) { - throw new errorClass(`Expected ${re.toString()}`); - } - return false; + } + cancel() { + this._cancelled = true; + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + } + hide() { + if (!this.div) { + return; } - function match(re) { - re.lastIndex = cursor; - let result = re.exec(source); - if (result === null) { - throw new SyntaxError(`Expected ${re.toString()}`); - } - cursor = re.lastIndex; - return result; + this.div.hidden = true; + } + hasEditableAnnotations() { + return !!this.annotationLayer?.hasEditableAnnotations(); + } + #updatePresentationModeState(state) { + if (!this.div) { + return; } - function match1(re) { - return match(re)[1]; + let disableFormElements = false; + switch (state) { + case PresentationModeState.FULLSCREEN: + disableFormElements = true; + break; + case PresentationModeState.NORMAL: + break; + default: + return; } - function parseMessage(id) { - let value = parsePattern(); - let attributes = parseAttributes(); - if (value === null && Object.keys(attributes).length === 0) { - throw new SyntaxError("Expected message value or attributes"); + for (const section of this.div.childNodes) { + if (section.hasAttribute("data-internal-link")) { + continue; } - return { - id, - value, - attributes - }; + section.inert = disableFormElements; } - function parseAttributes() { - let attrs = Object.create(null); - while (test(RE_ATTRIBUTE_START)) { - let name = match1(RE_ATTRIBUTE_START); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected attribute value"); - } - attrs[name] = value; + } +} + +;// ./web/download_manager.js + +function download(blobUrl, filename) { + const a = document.createElement("a"); + if (!a.click) { + throw new Error('DownloadManager: "a.click()" is not supported.'); + } + a.href = blobUrl; + a.target = "_parent"; + if ("download" in a) { + a.download = filename; + } + (document.body || document.documentElement).append(a); + a.click(); + a.remove(); +} +class DownloadManager { + #openBlobUrls = new WeakMap(); + downloadData(data, filename, contentType) { + const blobUrl = URL.createObjectURL(new Blob([data], { + type: contentType + })); + download(blobUrl, filename); + } + openOrDownloadData(data, filename, dest = null) { + const isPdfData = isPdfFile(filename); + const contentType = isPdfData ? "application/pdf" : ""; + this.downloadData(data, filename, contentType); + return false; + } + download(data, url, filename) { + let blobUrl; + if (data) { + blobUrl = URL.createObjectURL(new Blob([data], { + type: "application/pdf" + })); + } else { + if (!createValidAbsoluteUrl(url, "http://example.com")) { + console.error(`download - not a valid URL: ${url}`); + return; } - return attrs; + blobUrl = url + "#pdfjs.action=download"; } - function parsePattern() { - let first; - if (test(RE_TEXT_RUN)) { - first = match1(RE_TEXT_RUN); - } - if (source[cursor] === "{" || source[cursor] === "}") { - return parsePatternElements(first ? [first] : [], Infinity); - } - let indent = parseIndent(); - if (indent) { - if (first) { - return parsePatternElements([first, indent], indent.length); - } - indent.value = trim(indent.value, RE_LEADING_NEWLINES); - return parsePatternElements([indent], indent.length); - } - if (first) { - return trim(first, RE_TRAILING_SPACES); - } - return null; + download(blobUrl, filename); + } +} + +;// ./web/event_utils.js +const WaitOnType = { + EVENT: "event", + TIMEOUT: "timeout" +}; +async function waitOnEventOrTimeout({ + target, + name, + delay = 0 +}) { + if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { + throw new Error("waitOnEventOrTimeout - invalid parameters."); + } + const { + promise, + resolve + } = Promise.withResolvers(); + const ac = new AbortController(); + function handler(type) { + ac.abort(); + clearTimeout(timeout); + resolve(type); + } + const evtMethod = target instanceof EventBus ? "_on" : "addEventListener"; + target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), { + signal: ac.signal + }); + const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay); + return promise; +} +class EventBus { + #listeners = Object.create(null); + on(eventName, listener, options = null) { + this._on(eventName, listener, { + external: true, + once: options?.once, + signal: options?.signal + }); + } + off(eventName, listener, options = null) { + this._off(eventName, listener); + } + dispatch(eventName, data) { + const eventListeners = this.#listeners[eventName]; + if (!eventListeners || eventListeners.length === 0) { + return; } - function parsePatternElements(elements = [], commonIndent) { - while (true) { - if (test(RE_TEXT_RUN)) { - elements.push(match1(RE_TEXT_RUN)); - continue; - } - if (source[cursor] === "{") { - elements.push(parsePlaceable()); - continue; - } - if (source[cursor] === "}") { - throw new SyntaxError("Unbalanced closing brace"); - } - let indent = parseIndent(); - if (indent) { - elements.push(indent); - commonIndent = Math.min(commonIndent, indent.length); - continue; - } - break; - } - let lastIndex = elements.length - 1; - let lastElement = elements[lastIndex]; - if (typeof lastElement === "string") { - elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES); + let externalListeners; + for (const { + listener, + external, + once + } of eventListeners.slice(0)) { + if (once) { + this._off(eventName, listener); } - let baked = []; - for (let element of elements) { - if (element instanceof Indent) { - element = element.value.slice(0, element.value.length - commonIndent); - } - if (element) { - baked.push(element); - } + if (external) { + (externalListeners ||= []).push(listener); + continue; } - return baked; + listener(data); } - function parsePlaceable() { - consumeToken(TOKEN_BRACE_OPEN, SyntaxError); - let selector = parseInlineExpression(); - if (consumeToken(TOKEN_BRACE_CLOSE)) { - return selector; - } - if (consumeToken(TOKEN_ARROW)) { - let variants = parseVariants(); - consumeToken(TOKEN_BRACE_CLOSE, SyntaxError); - return { - type: "select", - selector, - ...variants - }; + if (externalListeners) { + for (const listener of externalListeners) { + listener(data); } - throw new SyntaxError("Unclosed placeable"); + externalListeners = null; } - function parseInlineExpression() { - if (source[cursor] === "{") { - return parsePlaceable(); - } - if (test(RE_REFERENCE)) { - let [, sigil, name, attr = null] = match(RE_REFERENCE); - if (sigil === "$") { - return { - type: "var", - name - }; - } - if (consumeToken(TOKEN_PAREN_OPEN)) { - let args = parseArguments(); - if (sigil === "-") { - return { - type: "term", - name, - attr, - args - }; - } - if (RE_FUNCTION_NAME.test(name)) { - return { - type: "func", - name, - args - }; - } - throw new SyntaxError("Function names must be all upper-case"); - } - if (sigil === "-") { - return { - type: "term", - name, - attr, - args: [] - }; - } - return { - type: "mesg", - name, - attr - }; + } + _on(eventName, listener, options = null) { + let rmAbort = null; + if (options?.signal instanceof AbortSignal) { + const { + signal + } = options; + if (signal.aborted) { + console.error("Cannot use an `aborted` signal."); + return; } - return parseLiteral(); + const onAbort = () => this._off(eventName, listener); + rmAbort = () => signal.removeEventListener("abort", onAbort); + signal.addEventListener("abort", onAbort); } - function parseArguments() { - let args = []; - while (true) { - switch (source[cursor]) { - case ")": - cursor++; - return args; - case undefined: - throw new SyntaxError("Unclosed argument list"); - } - args.push(parseArgument()); - consumeToken(TOKEN_COMMA); - } + const eventListeners = this.#listeners[eventName] ||= []; + eventListeners.push({ + listener, + external: options?.external === true, + once: options?.once === true, + rmAbort + }); + } + _off(eventName, listener, options = null) { + const eventListeners = this.#listeners[eventName]; + if (!eventListeners) { + return; } - function parseArgument() { - let expr = parseInlineExpression(); - if (expr.type !== "mesg") { - return expr; - } - if (consumeToken(TOKEN_COLON)) { - return { - type: "narg", - name: expr.name, - value: parseLiteral() - }; + for (let i = 0, ii = eventListeners.length; i < ii; i++) { + const evt = eventListeners[i]; + if (evt.listener === listener) { + evt.rmAbort?.(); + eventListeners.splice(i, 1); + return; } - return expr; - } - function parseVariants() { - let variants = []; - let count = 0; - let star; - while (test(RE_VARIANT_START)) { - if (consumeChar("*")) { - star = count; - } - let key = parseVariantKey(); - let value = parsePattern(); - if (value === null) { - throw new SyntaxError("Expected variant value"); - } - variants[count++] = { - key, - value - }; - } - if (count === 0) { - return null; - } - if (star === undefined) { - throw new SyntaxError("Expected default variant"); - } - return { - variants, - star - }; - } - function parseVariantKey() { - consumeToken(TOKEN_BRACKET_OPEN, SyntaxError); - let key; - if (test(RE_NUMBER_LITERAL)) { - key = parseNumberLiteral(); - } else { - key = { - type: "str", - value: match1(RE_IDENTIFIER) - }; - } - consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError); - return key; - } - function parseLiteral() { - if (test(RE_NUMBER_LITERAL)) { - return parseNumberLiteral(); - } - if (source[cursor] === '"') { - return parseStringLiteral(); - } - throw new SyntaxError("Invalid expression"); - } - function parseNumberLiteral() { - let [, value, fraction = ""] = match(RE_NUMBER_LITERAL); - let precision = fraction.length; - return { - type: "num", - value: parseFloat(value), - precision - }; - } - function parseStringLiteral() { - consumeChar('"', SyntaxError); - let value = ""; - while (true) { - value += match1(RE_STRING_RUN); - if (source[cursor] === "\\") { - value += parseEscapeSequence(); - continue; - } - if (consumeChar('"')) { - return { - type: "str", - value - }; - } - throw new SyntaxError("Unclosed string literal"); - } - } - function parseEscapeSequence() { - if (test(RE_STRING_ESCAPE)) { - return match1(RE_STRING_ESCAPE); - } - if (test(RE_UNICODE_ESCAPE)) { - let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE); - let codepoint = parseInt(codepoint4 || codepoint6, 16); - return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�"; - } - throw new SyntaxError("Unknown escape sequence"); - } - function parseIndent() { - let start = cursor; - consumeToken(TOKEN_BLANK); - switch (source[cursor]) { - case ".": - case "[": - case "*": - case "}": - case undefined: - return false; - case "{": - return makeIndent(source.slice(start, cursor)); - } - if (source[cursor - 1] === " ") { - return makeIndent(source.slice(start, cursor)); - } - return false; - } - function trim(text, re) { - return text.replace(re, ""); - } - function makeIndent(blank) { - let value = blank.replace(RE_BLANK_LINES, "\n"); - let length = RE_INDENT.exec(blank)[1].length; - return new Indent(value, length); } } } -class Indent { - constructor(value, length) { - this.value = value; - this.length = length; +class FirefoxEventBus extends EventBus { + #externalServices; + #globalEventNames; + #isInAutomation; + constructor(globalEventNames, externalServices, isInAutomation) { + super(); + this.#globalEventNames = globalEventNames; + this.#externalServices = externalServices; + this.#isInAutomation = isInAutomation; + } + dispatch(eventName, data) { + throw new Error("Not implemented: FirefoxEventBus.dispatch"); } } -;// ./node_modules/@fluent/bundle/esm/index.js - - -;// ./node_modules/@fluent/dom/esm/overlay.js -const reOverlay = /<|&#?\w+;/; -const TEXT_LEVEL_ELEMENTS = { - "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"] -}; -const LOCALIZABLE_ATTRIBUTES = { - "http://www.w3.org/1999/xhtml": { - global: ["title", "aria-label", "aria-valuetext"], - a: ["download"], - area: ["download", "alt"], - input: ["alt", "placeholder"], - menuitem: ["label"], - menu: ["label"], - optgroup: ["label"], - option: ["label"], - track: ["label"], - img: ["alt"], - textarea: ["placeholder"], - th: ["abbr"] - }, - "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": { - global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"], - description: ["value"], - key: ["key", "keycode"], - label: ["value"], - textbox: ["placeholder", "value"] +;// ./node_modules/@fluent/bundle/esm/types.js +class FluentType { + constructor(value) { + this.value = value; } -}; -function translateElement(element, translation) { - const { - value - } = translation; - if (typeof value === "string") { - if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") { - element.textContent = value; - } else if (!reOverlay.test(value)) { - element.textContent = value; - } else { - const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template"); - templateElement.innerHTML = value; - overlayChildNodes(templateElement.content, element); - } + valueOf() { + return this.value; } - overlayAttributes(translation, element); } -function overlayChildNodes(fromFragment, toElement) { - for (const childNode of fromFragment.childNodes) { - if (childNode.nodeType === childNode.TEXT_NODE) { - continue; - } - if (childNode.hasAttribute("data-l10n-name")) { - const sanitized = getNodeForNamedElement(toElement, childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - if (isElementAllowed(childNode)) { - const sanitized = createSanitizedElement(childNode); - fromFragment.replaceChild(sanitized, childNode); - continue; - } - console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed."); - fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode); +class FluentNone extends FluentType { + constructor(value = "???") { + super(value); + } + toString(scope) { + return `{${this.value}}`; } - toElement.textContent = ""; - toElement.appendChild(fromFragment); } -function hasAttribute(attributes, name) { - if (!attributes) { - return false; +class FluentNumber extends FluentType { + constructor(value, opts = {}) { + super(value); + this.opts = opts; } - for (let attr of attributes) { - if (attr.name === name) { - return true; + toString(scope) { + try { + const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts); + return nf.format(this.value); + } catch (err) { + scope.reportError(err); + return this.value.toString(10); } } - return false; } -function overlayAttributes(fromElement, toElement) { - const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null; - for (const attr of Array.from(toElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) { - toElement.removeAttribute(attr.name); +class FluentDateTime extends FluentType { + constructor(value, opts = {}) { + super(value); + this.opts = opts; + } + toString(scope) { + try { + const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts); + return dtf.format(this.value); + } catch (err) { + scope.reportError(err); + return new Date(this.value).toISOString(); } } - if (!fromElement.attributes) { - return; +} +;// ./node_modules/@fluent/bundle/esm/resolver.js + +const MAX_PLACEABLES = 100; +const FSI = "\u2068"; +const PDI = "\u2069"; +function match(scope, selector, key) { + if (key === selector) { + return true; } - for (const attr of Array.from(fromElement.attributes)) { - if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) { - toElement.setAttribute(attr.name, attr.value); + if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) { + return true; + } + if (selector instanceof FluentNumber && typeof key === "string") { + let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value); + if (key === category) { + return true; } } + return false; } -function getNodeForNamedElement(sourceElement, translatedChild) { - const childName = translatedChild.getAttribute("data-l10n-name"); - const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`); - if (!sourceChild) { - console.warn(`An element named "${childName}" wasn't found in the source.`); - return createTextNodeFromTextContent(translatedChild); +function getDefault(scope, variants, star) { + if (variants[star]) { + return resolvePattern(scope, variants[star].value); } - if (sourceChild.localName !== translatedChild.localName) { - console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`); - return createTextNodeFromTextContent(translatedChild); - } - sourceElement.removeChild(sourceChild); - const clone = sourceChild.cloneNode(false); - return shallowPopulateUsing(translatedChild, clone); -} -function createSanitizedElement(element) { - const clone = element.ownerDocument.createElement(element.localName); - return shallowPopulateUsing(element, clone); -} -function createTextNodeFromTextContent(element) { - return element.ownerDocument.createTextNode(element.textContent); -} -function isElementAllowed(element) { - const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI]; - return allowed && allowed.includes(element.localName); + scope.reportError(new RangeError("No default")); + return new FluentNone(); } -function isAttrNameLocalizable(name, element, explicitlyAllowed = null) { - if (explicitlyAllowed && explicitlyAllowed.includes(name)) { - return true; - } - const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI]; - if (!allowed) { - return false; - } - const attrName = name.toLowerCase(); - const elemName = element.localName; - if (allowed.global.includes(attrName)) { - return true; - } - if (!allowed[elemName]) { - return false; - } - if (allowed[elemName].includes(attrName)) { - return true; - } - if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") { - const type = element.type.toLowerCase(); - if (type === "submit" || type === "button" || type === "reset") { - return true; +function getArguments(scope, args) { + const positional = []; + const named = Object.create(null); + for (const arg of args) { + if (arg.type === "narg") { + named[arg.name] = resolveExpression(scope, arg.value); + } else { + positional.push(resolveExpression(scope, arg)); } } - return false; -} -function shallowPopulateUsing(fromElement, toElement) { - toElement.textContent = fromElement.textContent; - overlayAttributes(fromElement, toElement); - return toElement; + return { + positional, + named + }; } -;// ./node_modules/cached-iterable/src/cached_iterable.mjs -class CachedIterable extends Array { - static from(iterable) { - if (iterable instanceof this) { - return iterable; - } - return new this(iterable); +function resolveExpression(scope, expr) { + switch (expr.type) { + case "str": + return expr.value; + case "num": + return new FluentNumber(expr.value, { + minimumFractionDigits: expr.precision + }); + case "var": + return resolveVariableReference(scope, expr); + case "mesg": + return resolveMessageReference(scope, expr); + case "term": + return resolveTermReference(scope, expr); + case "func": + return resolveFunctionReference(scope, expr); + case "select": + return resolveSelectExpression(scope, expr); + default: + return new FluentNone(); } } -;// ./node_modules/cached-iterable/src/cached_sync_iterable.mjs - -class CachedSyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); +function resolveVariableReference(scope, { + name +}) { + let arg; + if (scope.params) { + if (Object.prototype.hasOwnProperty.call(scope.params, name)) { + arg = scope.params[name]; } else { - throw new TypeError("Argument must implement the iteration protocol."); + return new FluentNone(`$${name}`); } + } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) { + arg = scope.args[name]; + } else { + scope.reportError(new ReferenceError(`Unknown variable: $${name}`)); + return new FluentNone(`$${name}`); } - [Symbol.iterator]() { - const cached = this; - let cur = 0; - return { - next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; + if (arg instanceof FluentType) { + return arg; } - touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && last.done) { - break; + switch (typeof arg) { + case "string": + return arg; + case "number": + return new FluentNumber(arg); + case "object": + if (arg instanceof Date) { + return new FluentDateTime(arg.getTime()); } - this.push(this.iterator.next()); - } - return this[this.length - 1]; + default: + scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)); + return new FluentNone(`$${name}`); } } -;// ./node_modules/cached-iterable/src/cached_async_iterable.mjs - -class CachedAsyncIterable extends CachedIterable { - constructor(iterable) { - super(); - if (Symbol.asyncIterator in Object(iterable)) { - this.iterator = iterable[Symbol.asyncIterator](); - } else if (Symbol.iterator in Object(iterable)) { - this.iterator = iterable[Symbol.iterator](); - } else { - throw new TypeError("Argument must implement the iteration protocol."); +function resolveMessageReference(scope, { + name, + attr +}) { + const message = scope.bundle._messages.get(name); + if (!message) { + scope.reportError(new ReferenceError(`Unknown message: ${name}`)); + return new FluentNone(name); + } + if (attr) { + const attribute = message.attributes[attr]; + if (attribute) { + return resolvePattern(scope, attribute); } + scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); + return new FluentNone(`${name}.${attr}`); } - [Symbol.asyncIterator]() { - const cached = this; - let cur = 0; - return { - async next() { - if (cached.length <= cur) { - cached.push(cached.iterator.next()); - } - return cached[cur++]; - } - }; + if (message.value) { + return resolvePattern(scope, message.value); } - async touchNext(count = 1) { - let idx = 0; - while (idx++ < count) { - const last = this[this.length - 1]; - if (last && (await last).done) { - break; - } - this.push(this.iterator.next()); + scope.reportError(new ReferenceError(`No value: ${name}`)); + return new FluentNone(name); +} +function resolveTermReference(scope, { + name, + attr, + args +}) { + const id = `-${name}`; + const term = scope.bundle._terms.get(id); + if (!term) { + scope.reportError(new ReferenceError(`Unknown term: ${id}`)); + return new FluentNone(id); + } + if (attr) { + const attribute = term.attributes[attr]; + if (attribute) { + scope.params = getArguments(scope, args).named; + const resolved = resolvePattern(scope, attribute); + scope.params = null; + return resolved; } - return this[this.length - 1]; + scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); + return new FluentNone(`${id}.${attr}`); } + scope.params = getArguments(scope, args).named; + const resolved = resolvePattern(scope, term.value); + scope.params = null; + return resolved; } -;// ./node_modules/cached-iterable/src/index.mjs - - -;// ./node_modules/@fluent/dom/esm/localization.js - -class Localization { - constructor(resourceIds = [], generateBundles) { - this.resourceIds = resourceIds; - this.generateBundles = generateBundles; - this.onChange(true); +function resolveFunctionReference(scope, { + name, + args +}) { + let func = scope.bundle._functions[name]; + if (!func) { + scope.reportError(new ReferenceError(`Unknown function: ${name}()`)); + return new FluentNone(`${name}()`); } - addResourceIds(resourceIds, eager = false) { - this.resourceIds.push(...resourceIds); - this.onChange(eager); - return this.resourceIds.length; + if (typeof func !== "function") { + scope.reportError(new TypeError(`Function ${name}() is not callable`)); + return new FluentNone(`${name}()`); } - removeResourceIds(resourceIds) { - this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r)); - this.onChange(); - return this.resourceIds.length; + try { + let resolved = getArguments(scope, args); + return func(resolved.positional, resolved.named); + } catch (err) { + scope.reportError(err); + return new FluentNone(`${name}()`); } - async formatWithFallback(keys, method) { - const translations = []; - let hasAtLeastOneBundle = false; - for await (const bundle of this.bundles) { - hasAtLeastOneBundle = true; - const missingIds = keysFromBundle(method, bundle, keys, translations); - if (missingIds.size === 0) { - break; - } - if (typeof console !== "undefined") { - const locale = bundle.locales[0]; - const ids = Array.from(missingIds).join(", "); - console.warn(`[fluent] Missing translations in ${locale}: ${ids}`); - } - } - if (!hasAtLeastOneBundle && typeof console !== "undefined") { - console.warn(`[fluent] Request for keys failed because no resource bundles got generated. - keys: ${JSON.stringify(keys)}. - resourceIds: ${JSON.stringify(this.resourceIds)}.`); - } - return translations; - } - formatMessages(keys) { - return this.formatWithFallback(keys, messageFromBundle); - } - formatValues(keys) { - return this.formatWithFallback(keys, valueFromBundle); +} +function resolveSelectExpression(scope, { + selector, + variants, + star +}) { + let sel = resolveExpression(scope, selector); + if (sel instanceof FluentNone) { + return getDefault(scope, variants, star); } - async formatValue(id, args) { - const [val] = await this.formatValues([{ - id, - args - }]); - return val; + for (const variant of variants) { + const key = resolveExpression(scope, variant.key); + if (match(scope, sel, key)) { + return resolvePattern(scope, variant.value); + } } - handleEvent() { - this.onChange(); + return getDefault(scope, variants, star); +} +function resolveComplexPattern(scope, ptn) { + if (scope.dirty.has(ptn)) { + scope.reportError(new RangeError("Cyclic reference")); + return new FluentNone(); } - onChange(eager = false) { - this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds)); - if (eager) { - this.bundles.touchNext(2); + scope.dirty.add(ptn); + const result = []; + const useIsolating = scope.bundle._useIsolating && ptn.length > 1; + for (const elem of ptn) { + if (typeof elem === "string") { + result.push(scope.bundle._transform(elem)); + continue; + } + scope.placeables++; + if (scope.placeables > MAX_PLACEABLES) { + scope.dirty.delete(ptn); + throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`); + } + if (useIsolating) { + result.push(FSI); + } + result.push(resolveExpression(scope, elem).toString(scope)); + if (useIsolating) { + result.push(PDI); } } + scope.dirty.delete(ptn); + return result.join(""); } -function valueFromBundle(bundle, errors, message, args) { - if (message.value) { - return bundle.formatPattern(message.value, args, errors); +function resolvePattern(scope, value) { + if (typeof value === "string") { + return scope.bundle._transform(value); } - return null; + return resolveComplexPattern(scope, value); } -function messageFromBundle(bundle, errors, message, args) { - const formatted = { - value: null, - attributes: null - }; - if (message.value) { - formatted.value = bundle.formatPattern(message.value, args, errors); +;// ./node_modules/@fluent/bundle/esm/scope.js +class Scope { + constructor(bundle, errors, args) { + this.dirty = new WeakSet(); + this.params = null; + this.placeables = 0; + this.bundle = bundle; + this.errors = errors; + this.args = args; } - let attrNames = Object.keys(message.attributes); - if (attrNames.length > 0) { - formatted.attributes = new Array(attrNames.length); - for (let [i, name] of attrNames.entries()) { - let value = bundle.formatPattern(message.attributes[name], args, errors); - formatted.attributes[i] = { - name, - value - }; + reportError(error) { + if (!this.errors || !(error instanceof Error)) { + throw error; } + this.errors.push(error); } - return formatted; -} -function keysFromBundle(method, bundle, keys, translations) { - const messageErrors = []; - const missingIds = new Set(); - keys.forEach(({ - id, - args - }, i) => { - if (translations[i] !== undefined) { - return; + memoizeIntlObject(ctor, opts) { + let cache = this.bundle._intls.get(ctor); + if (!cache) { + cache = {}; + this.bundle._intls.set(ctor, cache); } - let message = bundle.getMessage(id); - if (message) { - messageErrors.length = 0; - translations[i] = method(bundle, messageErrors, message, args); - if (messageErrors.length > 0 && typeof console !== "undefined") { - const locale = bundle.locales[0]; - const errors = messageErrors.join(", "); - console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`); - } - } else { - missingIds.add(id); + let id = JSON.stringify(opts); + if (!cache[id]) { + cache[id] = new ctor(this.bundle.locales, opts); } - }); - return missingIds; + return cache[id]; + } } -;// ./node_modules/@fluent/dom/esm/dom_localization.js - +;// ./node_modules/@fluent/bundle/esm/builtins.js -const L10NID_ATTR_NAME = "data-l10n-id"; -const L10NARGS_ATTR_NAME = "data-l10n-args"; -const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`; -class DOMLocalization extends Localization { - constructor(resourceIds, generateBundles) { - super(resourceIds, generateBundles); - this.roots = new Set(); - this.pendingrAF = null; - this.pendingElements = new Set(); - this.windowElement = null; - this.mutationObserver = null; - this.observerConfig = { - attributes: true, - characterData: false, - childList: true, - subtree: true, - attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME] - }; - } - onChange(eager = false) { - super.onChange(eager); - if (this.roots) { - this.translateRoots(); +function values(opts, allowed) { + const unwrapped = Object.create(null); + for (const [name, opt] of Object.entries(opts)) { + if (allowed.includes(name)) { + unwrapped[name] = opt.valueOf(); } } - setAttributes(element, id, args) { - element.setAttribute(L10NID_ATTR_NAME, id); - if (args) { - element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args)); - } else { - element.removeAttribute(L10NARGS_ATTR_NAME); - } - return element; + return unwrapped; +} +const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"]; +function NUMBER(args, opts) { + let arg = args[0]; + if (arg instanceof FluentNone) { + return new FluentNone(`NUMBER(${arg.valueOf()})`); } - getAttributes(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; + if (arg instanceof FluentNumber) { + return new FluentNumber(arg.valueOf(), { + ...arg.opts, + ...values(opts, NUMBER_ALLOWED) + }); } - connectRoot(newRoot) { - for (const root of this.roots) { - if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) { - throw new Error("Cannot add a root that overlaps with existing root."); - } - } - if (this.windowElement) { - if (this.windowElement !== newRoot.ownerDocument.defaultView) { - throw new Error(`Cannot connect a root: - DOMLocalization already has a root from a different window.`); - } - } else { - this.windowElement = newRoot.ownerDocument.defaultView; - this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations)); - } - this.roots.add(newRoot); - this.mutationObserver.observe(newRoot, this.observerConfig); + if (arg instanceof FluentDateTime) { + return new FluentNumber(arg.valueOf(), { + ...values(opts, NUMBER_ALLOWED) + }); } - disconnectRoot(root) { - this.roots.delete(root); - this.pauseObserving(); - if (this.roots.size === 0) { - this.mutationObserver = null; - if (this.windowElement && this.pendingrAF) { - this.windowElement.cancelAnimationFrame(this.pendingrAF); - } - this.windowElement = null; - this.pendingrAF = null; - this.pendingElements.clear(); - return true; - } - this.resumeObserving(); - return false; + throw new TypeError("Invalid argument to NUMBER"); +} +const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"]; +function DATETIME(args, opts) { + let arg = args[0]; + if (arg instanceof FluentNone) { + return new FluentNone(`DATETIME(${arg.valueOf()})`); } - translateRoots() { - const roots = Array.from(this.roots); - return Promise.all(roots.map(root => this.translateFragment(root))); + if (arg instanceof FluentDateTime) { + return new FluentDateTime(arg.valueOf(), { + ...arg.opts, + ...values(opts, DATETIME_ALLOWED) + }); } - pauseObserving() { - if (!this.mutationObserver) { - return; - } - this.translateMutations(this.mutationObserver.takeRecords()); - this.mutationObserver.disconnect(); - } - resumeObserving() { - if (!this.mutationObserver) { - return; - } - for (const root of this.roots) { - this.mutationObserver.observe(root, this.observerConfig); - } - } - translateMutations(mutations) { - for (const mutation of mutations) { - switch (mutation.type) { - case "attributes": - if (mutation.target.hasAttribute("data-l10n-id")) { - this.pendingElements.add(mutation.target); - } - break; - case "childList": - for (const addedNode of mutation.addedNodes) { - if (addedNode.nodeType === addedNode.ELEMENT_NODE) { - if (addedNode.childElementCount) { - for (const element of this.getTranslatables(addedNode)) { - this.pendingElements.add(element); - } - } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) { - this.pendingElements.add(addedNode); - } - } - } - break; - } - } - if (this.pendingElements.size > 0) { - if (this.pendingrAF === null) { - this.pendingrAF = this.windowElement.requestAnimationFrame(() => { - this.translateElements(Array.from(this.pendingElements)); - this.pendingElements.clear(); - this.pendingrAF = null; - }); - } - } - } - translateFragment(frag) { - return this.translateElements(this.getTranslatables(frag)); - } - async translateElements(elements) { - if (!elements.length) { - return undefined; - } - const keys = elements.map(this.getKeysForElement); - const translations = await this.formatMessages(keys); - return this.applyTranslations(elements, translations); - } - applyTranslations(elements, translations) { - this.pauseObserving(); - for (let i = 0; i < elements.length; i++) { - if (translations[i] !== undefined) { - translateElement(elements[i], translations[i]); - } - } - this.resumeObserving(); - } - getTranslatables(element) { - const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY)); - if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) { - nodes.push(element); - } - return nodes; + if (arg instanceof FluentNumber) { + return new FluentDateTime(arg.valueOf(), { + ...values(opts, DATETIME_ALLOWED) + }); } - getKeysForElement(element) { - return { - id: element.getAttribute(L10NID_ATTR_NAME), - args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) - }; + throw new TypeError("Invalid argument to DATETIME"); +} +;// ./node_modules/@fluent/bundle/esm/memoizer.js +const cache = new Map(); +function getMemoizerForLocale(locales) { + const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales; + let memoizer = cache.get(stringLocale); + if (memoizer === undefined) { + memoizer = new Map(); + cache.set(stringLocale, memoizer); } + return memoizer; } -;// ./node_modules/@fluent/dom/esm/index.js +;// ./node_modules/@fluent/bundle/esm/bundle.js -;// ./web/l10n.js -class L10n { - #dir; - #elements; - #lang; - #l10n; - constructor({ - lang, - isRTL - }, l10n = null) { - this.#lang = L10n.#fixupLangCode(lang); - this.#l10n = l10n; - this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr"; - } - _setL10n(l10n) { - this.#l10n = l10n; + + + +class FluentBundle { + constructor(locales, { + functions, + useIsolating = true, + transform = v => v + } = {}) { + this._terms = new Map(); + this._messages = new Map(); + this.locales = Array.isArray(locales) ? locales : [locales]; + this._functions = { + NUMBER: NUMBER, + DATETIME: DATETIME, + ...functions + }; + this._useIsolating = useIsolating; + this._transform = transform; + this._intls = getMemoizerForLocale(locales); } - getLanguage() { - return this.#lang; + hasMessage(id) { + return this._messages.has(id); } - getDirection() { - return this.#dir; + getMessage(id) { + return this._messages.get(id); } - async get(ids, args = null, fallback) { - if (Array.isArray(ids)) { - ids = ids.map(id => ({ - id - })); - const messages = await this.#l10n.formatMessages(ids); - return messages.map(message => message.value); + addResource(res, { + allowOverrides = false + } = {}) { + const errors = []; + for (let i = 0; i < res.body.length; i++) { + let entry = res.body[i]; + if (entry.id.startsWith("-")) { + if (allowOverrides === false && this._terms.has(entry.id)) { + errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`)); + continue; + } + this._terms.set(entry.id, entry); + } else { + if (allowOverrides === false && this._messages.has(entry.id)) { + errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`)); + continue; + } + this._messages.set(entry.id, entry); + } } - const messages = await this.#l10n.formatMessages([{ - id: ids, - args - }]); - return messages[0]?.value || fallback; - } - async translate(element) { - (this.#elements ||= new Set()).add(element); - try { - this.#l10n.connectRoot(element); - await this.#l10n.translateRoots(); - } catch {} + return errors; } - async translateOnce(element) { - try { - await this.#l10n.translateElements([element]); - } catch (ex) { - console.error("translateOnce:", ex); + formatPattern(pattern, args = null, errors = null) { + if (typeof pattern === "string") { + return this._transform(pattern); } - } - async destroy() { - if (this.#elements) { - for (const element of this.#elements) { - this.#l10n.disconnectRoot(element); + let scope = new Scope(this, errors, args); + try { + let value = resolveComplexPattern(scope, pattern); + return value.toString(scope); + } catch (err) { + if (scope.errors && err instanceof Error) { + scope.errors.push(err); + return new FluentNone().toString(scope); } - this.#elements.clear(); - this.#elements = null; + throw err; } - this.#l10n.pauseObserving(); - } - pause() { - this.#l10n.pauseObserving(); - } - resume() { - this.#l10n.resumeObserving(); - } - static #fixupLangCode(langCode) { - langCode = langCode?.toLowerCase() || "en-us"; - const PARTIAL_LANG_CODES = { - en: "en-us", - es: "es-es", - fy: "fy-nl", - ga: "ga-ie", - gu: "gu-in", - hi: "hi-in", - hy: "hy-am", - nb: "nb-no", - ne: "ne-np", - nn: "nn-no", - pa: "pa-in", - pt: "pt-pt", - sv: "sv-se", - zh: "zh-cn" - }; - return PARTIAL_LANG_CODES[langCode] || langCode; - } - static #isRTL(lang) { - const shortCode = lang.split("-", 1)[0]; - return ["ar", "he", "fa", "ps", "ur"].includes(shortCode); - } -} -const GenericL10n = null; - -;// ./web/genericl10n.js - - - - -function createBundle(lang, text) { - const resource = new FluentResource(text); - const bundle = new FluentBundle(lang); - const errors = bundle.addResource(resource); - if (errors.length) { - console.error("L10n errors", errors); } - return bundle; } -class genericl10n_GenericL10n extends L10n { - constructor(lang) { - super({ - lang - }); - const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage()); - this._setL10n(new DOMLocalization([], generateBundles)); - } - static async *#generateBundles(defaultLang, baseLang) { - const { - baseURL, - paths - } = await this.#getPaths(); - const langs = [baseLang]; - if (defaultLang !== baseLang) { - const shortLang = baseLang.split("-", 1)[0]; - if (shortLang !== baseLang) { - langs.push(shortLang); +;// ./node_modules/@fluent/bundle/esm/resource.js +const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm; +const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y; +const RE_VARIANT_START = /\*?\[/y; +const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y; +const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y; +const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y; +const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; +const RE_TEXT_RUN = /([^{}\n\r]+)/y; +const RE_STRING_RUN = /([^\\"\n\r]*)/y; +const RE_STRING_ESCAPE = /\\([\\"])/y; +const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; +const RE_LEADING_NEWLINES = /^\n+/; +const RE_TRAILING_SPACES = / +$/; +const RE_BLANK_LINES = / *\r?\n/g; +const RE_INDENT = /( *)$/; +const TOKEN_BRACE_OPEN = /{\s*/y; +const TOKEN_BRACE_CLOSE = /\s*}/y; +const TOKEN_BRACKET_OPEN = /\[\s*/y; +const TOKEN_BRACKET_CLOSE = /\s*] */y; +const TOKEN_PAREN_OPEN = /\s*\(\s*/y; +const TOKEN_ARROW = /\s*->\s*/y; +const TOKEN_COLON = /\s*:\s*/y; +const TOKEN_COMMA = /\s*,?\s*/y; +const TOKEN_BLANK = /\s+/y; +class FluentResource { + constructor(source) { + this.body = []; + RE_MESSAGE_START.lastIndex = 0; + let cursor = 0; + while (true) { + let next = RE_MESSAGE_START.exec(source); + if (next === null) { + break; } - langs.push(defaultLang); - } - for (const lang of langs) { - const bundle = await this.#createBundle(lang, baseURL, paths); - if (bundle) { - yield bundle; - } else if (lang === "en-us") { - yield this.#createBundleFallback(lang); + cursor = RE_MESSAGE_START.lastIndex; + try { + this.body.push(parseMessage(next[1])); + } catch (err) { + if (err instanceof SyntaxError) { + continue; + } + throw err; } } - } - static async #createBundle(lang, baseURL, paths) { - const path = paths[lang]; - if (!path) { - return null; + function test(re) { + re.lastIndex = cursor; + return re.test(source); } - const url = new URL(path, baseURL); - const text = await fetchData(url, "text"); - return createBundle(lang, text); - } - static async #getPaths() { - try { - const { - href - } = document.querySelector(`link[type="application/l10n"]`); - const paths = await fetchData(href, "json"); - return { - baseURL: href.replace(/[^/]*$/, "") || "./", - paths - }; - } catch {} - return { - baseURL: "./", - paths: Object.create(null) - }; - } - static async *#generateBundlesFallback(lang) { - yield this.#createBundleFallback(lang); - } - static async #createBundleFallback(lang) { - const text = "pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties\u2026\npdfjs-document-properties-button-label = Document Properties\u2026\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } \xD7 { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } \xD7 { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing\u2026\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document\u2026\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing\u2026\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can\u2019t see the image or when it doesn\u2019t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, \u201CA young man sits down at a table to eat a meal\u201D\npdfjs-editor-resizer-top-left =\n .aria-label = Top left corner \u2014 resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle \u2014 resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner \u2014 resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right \u2014 resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner \u2014 resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle \u2014 resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner \u2014 resize\npdfjs-editor-resizer-middle-left =\n .aria-label = Middle left \u2014 resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here\u2026\npdfjs-editor-new-alt-text-description = Short description for people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn\u2019t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading\u2026\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close"; - return createBundle(lang, text); - } -} - -;// ./web/generic_scripting.js - -async function docProperties(pdfDocument) { - const url = "", - baseUrl = url.split("#", 1)[0]; - let { - info, - metadata, - contentDispositionFilename, - contentLength - } = await pdfDocument.getMetadata(); - if (!contentLength) { - const { - length - } = await pdfDocument.getDownloadInfo(); - contentLength = length; - } - return { - ...info, - baseURL: baseUrl, - filesize: contentLength, - filename: contentDispositionFilename || getPdfFilenameFromUrl(url), - metadata: metadata?.getRaw(), - authors: metadata?.get("dc:creator"), - numPages: pdfDocument.numPages, - URL: url - }; -} -class GenericScripting { - constructor(sandboxBundleSrc) { - this._ready = new Promise((resolve, reject) => { - const sandbox = import(/*webpackIgnore: true*/sandboxBundleSrc); - sandbox.then(pdfjsSandbox => { - resolve(pdfjsSandbox.QuickJSSandbox()); - }).catch(reject); - }); - } - async createSandbox(data) { - const sandbox = await this._ready; - sandbox.create(data); - } - async dispatchEventInSandbox(event) { - const sandbox = await this._ready; - setTimeout(() => sandbox.dispatchEvent(event), 0); - } - async destroySandbox() { - const sandbox = await this._ready; - sandbox.nukeSandbox(); - } -} - -;// ./web/genericcom.js - - - - - -function initCom(app) {} -class Preferences extends BasePreferences { - async _writeToStorage(prefObj) { - localStorage.setItem("pdfjs.preferences", JSON.stringify(prefObj)); - } - async _readFromStorage(prefObj) { - return { - prefs: JSON.parse(localStorage.getItem("pdfjs.preferences")) - }; - } -} -class ExternalServices extends BaseExternalServices { - async createL10n() { - return new genericl10n_GenericL10n(AppOptions.get("localeProperties")?.lang); - } - createScripting() { - return new GenericScripting(AppOptions.get("sandboxBundleSrc")); - } -} -class MLManager { - async isEnabledFor(_name) { - return false; - } - async deleteModel(_service) { - return null; - } - isReady(_name) { - return false; - } - guess(_data) {} - toggleService(_name, _enabled) {} - static getFakeMLManager(options) { - return new FakeMLManager(options); - } -} -class FakeMLManager { - eventBus = null; - hasProgress = false; - constructor({ - enableGuessAltText, - enableAltTextModelDownload - }) { - this.enableGuessAltText = enableGuessAltText; - this.enableAltTextModelDownload = enableAltTextModelDownload; - } - setEventBus(eventBus, abortSignal) { - this.eventBus = eventBus; - } - async isEnabledFor(_name) { - return this.enableGuessAltText; - } - async deleteModel(_name) { - this.enableAltTextModelDownload = false; - return null; - } - async loadModel(_name) {} - async downloadModel(_name) { - this.hasProgress = true; - const { - promise, - resolve - } = Promise.withResolvers(); - const total = 1e8; - const end = 1.5 * total; - const increment = 5e6; - let loaded = 0; - const id = setInterval(() => { - loaded += increment; - if (loaded <= end) { - this.eventBus.dispatch("loadaiengineprogress", { - source: this, - detail: { - total, - totalLoaded: loaded, - finished: loaded + increment >= end - } - }); - return; + function consumeChar(char, errorClass) { + if (source[cursor] === char) { + cursor++; + return true; } - clearInterval(id); - this.hasProgress = false; - this.enableAltTextModelDownload = true; - resolve(true); - }, 900); - return promise; - } - isReady(_name) { - return this.enableAltTextModelDownload; - } - guess({ - request: { - data - } - }) { - return new Promise(resolve => { - setTimeout(() => { - resolve(data ? { - output: "Fake alt text." - } : { - error: true - }); - }, 3000); - }); - } - toggleService(_name, enabled) { - this.enableGuessAltText = enabled; - } -} - -;// ./web/new_alt_text_manager.js - -class NewAltTextManager { - #boundCancel = this.#cancel.bind(this); - #createAutomaticallyButton; - #currentEditor = null; - #cancelButton; - #descriptionContainer; - #dialog; - #disclaimer; - #downloadModel; - #downloadModelDescription; - #eventBus; - #firstTime = false; - #guessedAltText; - #hasAI = null; - #isEditing = null; - #imagePreview; - #imageData; - #isAILoading = false; - #wasAILoading = false; - #learnMore; - #notNowButton; - #overlayManager; - #textarea; - #title; - #uiManager; - #previousAltText = null; - constructor({ - descriptionContainer, - dialog, - imagePreview, - cancelButton, - disclaimer, - notNowButton, - saveButton, - textarea, - learnMore, - errorCloseButton, - createAutomaticallyButton, - downloadModel, - downloadModelDescription, - title - }, overlayManager, eventBus) { - this.#cancelButton = cancelButton; - this.#createAutomaticallyButton = createAutomaticallyButton; - this.#descriptionContainer = descriptionContainer; - this.#dialog = dialog; - this.#disclaimer = disclaimer; - this.#notNowButton = notNowButton; - this.#imagePreview = imagePreview; - this.#textarea = textarea; - this.#learnMore = learnMore; - this.#title = title; - this.#downloadModel = downloadModel; - this.#downloadModelDescription = downloadModelDescription; - this.#overlayManager = overlayManager; - this.#eventBus = eventBus; - dialog.addEventListener("close", this.#close.bind(this)); - dialog.addEventListener("contextmenu", event => { - if (event.target !== this.#textarea) { - event.preventDefault(); + if (errorClass) { + throw new errorClass(`Expected ${char}`); } - }); - cancelButton.addEventListener("click", this.#boundCancel); - notNowButton.addEventListener("click", this.#boundCancel); - saveButton.addEventListener("click", this.#save.bind(this)); - errorCloseButton.addEventListener("click", () => { - this.#toggleError(false); - }); - createAutomaticallyButton.addEventListener("click", async () => { - const checked = createAutomaticallyButton.getAttribute("aria-pressed") !== "true"; - this.#currentEditor._reportTelemetry({ - action: "pdfjs.image.alt_text.ai_generation_check", - data: { - status: checked - } - }); - if (this.#uiManager) { - this.#uiManager.setPreference("enableGuessAltText", checked); - await this.#uiManager.mlManager.toggleService("altText", checked); + return false; + } + function consumeToken(re, errorClass) { + if (test(re)) { + cursor = re.lastIndex; + return true; } - this.#toggleGuessAltText(checked, false); - }); - textarea.addEventListener("focus", () => { - this.#wasAILoading = this.#isAILoading; - this.#toggleLoading(false); - this.#toggleTitleAndDisclaimer(); - }); - textarea.addEventListener("blur", () => { - if (!textarea.value) { - this.#toggleLoading(this.#wasAILoading); + if (errorClass) { + throw new errorClass(`Expected ${re.toString()}`); } - this.#toggleTitleAndDisclaimer(); - }); - textarea.addEventListener("input", () => { - this.#toggleTitleAndDisclaimer(); - }); - eventBus._on("enableguessalttext", ({ - value - }) => { - this.#toggleGuessAltText(value, false); - }); - this.#overlayManager.register(dialog); - this.#learnMore.addEventListener("click", () => { - this.#currentEditor._reportTelemetry({ - action: "pdfjs.image.alt_text.info", - data: { - topic: "alt_text" - } - }); - }); - } - #toggleLoading(value) { - if (!this.#uiManager || this.#isAILoading === value) { - return; + return false; } - this.#isAILoading = value; - this.#descriptionContainer.classList.toggle("loading", value); - } - #toggleError(value) { - if (!this.#uiManager) { - return; + function match(re) { + re.lastIndex = cursor; + let result = re.exec(source); + if (result === null) { + throw new SyntaxError(`Expected ${re.toString()}`); + } + cursor = re.lastIndex; + return result; } - this.#dialog.classList.toggle("error", value); - } - async #toggleGuessAltText(value, isInitial = false) { - if (!this.#uiManager) { - return; + function match1(re) { + return match(re)[1]; } - this.#dialog.classList.toggle("aiDisabled", !value); - this.#createAutomaticallyButton.setAttribute("aria-pressed", value); - if (value) { - const { - altTextLearnMoreUrl - } = this.#uiManager.mlManager; - if (altTextLearnMoreUrl) { - this.#learnMore.href = altTextLearnMoreUrl; + function parseMessage(id) { + let value = parsePattern(); + let attributes = parseAttributes(); + if (value === null && Object.keys(attributes).length === 0) { + throw new SyntaxError("Expected message value or attributes"); } - this.#mlGuessAltText(isInitial); - } else { - this.#toggleLoading(false); - this.#isAILoading = false; - this.#toggleTitleAndDisclaimer(); + return { + id, + value, + attributes + }; } - } - #toggleNotNow() { - this.#notNowButton.classList.toggle("hidden", !this.#firstTime); - this.#cancelButton.classList.toggle("hidden", this.#firstTime); - } - #toggleAI(value) { - if (!this.#uiManager || this.#hasAI === value) { - return; - } - this.#hasAI = value; - this.#dialog.classList.toggle("noAi", !value); - this.#toggleTitleAndDisclaimer(); - } - #toggleTitleAndDisclaimer() { - const visible = this.#isAILoading || this.#guessedAltText && this.#guessedAltText === this.#textarea.value; - this.#disclaimer.hidden = !visible; - const isEditing = this.#isAILoading || !!this.#textarea.value; - if (this.#isEditing === isEditing) { - return; - } - this.#isEditing = isEditing; - this.#title.setAttribute("data-l10n-id", isEditing ? "pdfjs-editor-new-alt-text-dialog-edit-label" : "pdfjs-editor-new-alt-text-dialog-add-label"); - } - async #mlGuessAltText(isInitial) { - if (this.#isAILoading) { - return; - } - if (this.#textarea.value) { - return; - } - if (isInitial && this.#previousAltText !== null) { - return; - } - this.#guessedAltText = this.#currentEditor.guessedAltText; - if (this.#previousAltText === null && this.#guessedAltText) { - this.#addAltText(this.#guessedAltText); - return; - } - this.#toggleLoading(true); - this.#toggleTitleAndDisclaimer(); - let hasError = false; - try { - const altText = await this.#currentEditor.mlGuessAltText(this.#imageData, false); - if (altText) { - this.#guessedAltText = altText; - this.#wasAILoading = this.#isAILoading; - if (this.#isAILoading) { - this.#addAltText(altText); + function parseAttributes() { + let attrs = Object.create(null); + while (test(RE_ATTRIBUTE_START)) { + let name = match1(RE_ATTRIBUTE_START); + let value = parsePattern(); + if (value === null) { + throw new SyntaxError("Expected attribute value"); } + attrs[name] = value; } - } catch (e) { - console.error(e); - hasError = true; - } - this.#toggleLoading(false); - this.#toggleTitleAndDisclaimer(); - if (hasError && this.#uiManager) { - this.#toggleError(true); - } - } - #addAltText(altText) { - if (!this.#uiManager || this.#textarea.value) { - return; + return attrs; } - this.#textarea.value = altText; - this.#toggleTitleAndDisclaimer(); - } - #setProgress() { - this.#downloadModel.classList.toggle("hidden", false); - const callback = async ({ - detail: { - finished, - total, - totalLoaded - } - }) => { - const ONE_MEGA_BYTES = 1e6; - totalLoaded = Math.min(0.99 * total, totalLoaded); - const totalSize = this.#downloadModelDescription.ariaValueMax = Math.round(total / ONE_MEGA_BYTES); - const downloadedSize = this.#downloadModelDescription.ariaValueNow = Math.round(totalLoaded / ONE_MEGA_BYTES); - this.#downloadModelDescription.setAttribute("data-l10n-args", JSON.stringify({ - totalSize, - downloadedSize - })); - if (!finished) { - return; + function parsePattern() { + let first; + if (test(RE_TEXT_RUN)) { + first = match1(RE_TEXT_RUN); } - this.#eventBus._off("loadaiengineprogress", callback); - this.#downloadModel.classList.toggle("hidden", true); - this.#toggleAI(true); - if (!this.#uiManager) { - return; + if (source[cursor] === "{" || source[cursor] === "}") { + return parsePatternElements(first ? [first] : [], Infinity); } - const { - mlManager - } = this.#uiManager; - mlManager.toggleService("altText", true); - this.#toggleGuessAltText(await mlManager.isEnabledFor("altText"), true); - }; - this.#eventBus._on("loadaiengineprogress", callback); - } - async editAltText(uiManager, editor, firstTime) { - if (this.#currentEditor || !editor) { - return; - } - if (firstTime && editor.hasAltTextData()) { - editor.altTextFinish(); - return; - } - this.#firstTime = firstTime; - let { - mlManager - } = uiManager; - let hasAI = !!mlManager; - this.#toggleTitleAndDisclaimer(); - if (mlManager && !mlManager.isReady("altText")) { - hasAI = false; - if (mlManager.hasProgress) { - this.#setProgress(); - } else { - mlManager = null; + let indent = parseIndent(); + if (indent) { + if (first) { + return parsePatternElements([first, indent], indent.length); + } + indent.value = trim(indent.value, RE_LEADING_NEWLINES); + return parsePatternElements([indent], indent.length); } - } else { - this.#downloadModel.classList.toggle("hidden", true); - } - const isAltTextEnabledPromise = mlManager?.isEnabledFor("altText"); - this.#currentEditor = editor; - this.#uiManager = uiManager; - this.#uiManager.removeEditListeners(); - ({ - altText: this.#previousAltText - } = editor.altTextData); - this.#textarea.value = this.#previousAltText ?? ""; - const AI_MAX_IMAGE_DIMENSION = 224; - const MAX_PREVIEW_DIMENSION = 180; - let canvas, width, height; - if (mlManager) { - ({ - canvas, - width, - height, - imageData: this.#imageData - } = editor.copyCanvas(AI_MAX_IMAGE_DIMENSION, MAX_PREVIEW_DIMENSION, true)); - if (hasAI) { - this.#toggleGuessAltText(await isAltTextEnabledPromise, true); + if (first) { + return trim(first, RE_TRAILING_SPACES); } - } else { - ({ - canvas, - width, - height - } = editor.copyCanvas(AI_MAX_IMAGE_DIMENSION, MAX_PREVIEW_DIMENSION, false)); - } - canvas.setAttribute("role", "presentation"); - const { - style - } = canvas; - style.width = `${width}px`; - style.height = `${height}px`; - this.#imagePreview.append(canvas); - this.#toggleNotNow(); - this.#toggleAI(hasAI); - this.#toggleError(false); - try { - await this.#overlayManager.open(this.#dialog); - } catch (ex) { - this.#close(); - throw ex; + return null; } - } - #cancel() { - this.#currentEditor.altTextData = { - cancel: true - }; - const altText = this.#textarea.value.trim(); - this.#currentEditor._reportTelemetry({ - action: "pdfjs.image.alt_text.dismiss", - data: { - alt_text_type: altText ? "present" : "empty", - flow: this.#firstTime ? "image_add" : "alt_text_edit" + function parsePatternElements(elements = [], commonIndent) { + while (true) { + if (test(RE_TEXT_RUN)) { + elements.push(match1(RE_TEXT_RUN)); + continue; + } + if (source[cursor] === "{") { + elements.push(parsePlaceable()); + continue; + } + if (source[cursor] === "}") { + throw new SyntaxError("Unbalanced closing brace"); + } + let indent = parseIndent(); + if (indent) { + elements.push(indent); + commonIndent = Math.min(commonIndent, indent.length); + continue; + } + break; } - }); - this.#currentEditor._reportTelemetry({ - action: "pdfjs.image.image_added", - data: { - alt_text_modal: true, - alt_text_type: "skipped" + let lastIndex = elements.length - 1; + let lastElement = elements[lastIndex]; + if (typeof lastElement === "string") { + elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES); } - }); - this.#finish(); - } - #finish() { - if (this.#overlayManager.active === this.#dialog) { - this.#overlayManager.close(this.#dialog); - } - } - #close() { - const canvas = this.#imagePreview.firstChild; - canvas.remove(); - canvas.width = canvas.height = 0; - this.#imageData = null; - this.#toggleLoading(false); - this.#uiManager?.addEditListeners(); - this.#currentEditor.altTextFinish(); - this.#uiManager?.setSelected(this.#currentEditor); - this.#currentEditor = null; - this.#uiManager = null; - } - #extractWords(text) { - return new Set(text.toLowerCase().split(/[^\p{L}\p{N}]+/gu).filter(x => !!x)); - } - #save() { - const altText = this.#textarea.value.trim(); - this.#currentEditor.altTextData = { - altText, - decorative: false - }; - this.#currentEditor.altTextData.guessedAltText = this.#guessedAltText; - if (this.#guessedAltText && this.#guessedAltText !== altText) { - const guessedWords = this.#extractWords(this.#guessedAltText); - const words = this.#extractWords(altText); - this.#currentEditor._reportTelemetry({ - action: "pdfjs.image.alt_text.user_edit", - data: { - total_words: guessedWords.size, - words_removed: guessedWords.difference(words).size, - words_added: words.difference(guessedWords).size + let baked = []; + for (let element of elements) { + if (element instanceof Indent) { + element = element.value.slice(0, element.value.length - commonIndent); } - }); + if (element) { + baked.push(element); + } + } + return baked; } - this.#currentEditor._reportTelemetry({ - action: "pdfjs.image.image_added", - data: { - alt_text_modal: true, - alt_text_type: altText ? "present" : "empty" + function parsePlaceable() { + consumeToken(TOKEN_BRACE_OPEN, SyntaxError); + let selector = parseInlineExpression(); + if (consumeToken(TOKEN_BRACE_CLOSE)) { + return selector; } - }); - this.#currentEditor._reportTelemetry({ - action: "pdfjs.image.alt_text.save", - data: { - alt_text_type: altText ? "present" : "empty", - flow: this.#firstTime ? "image_add" : "alt_text_edit" + if (consumeToken(TOKEN_ARROW)) { + let variants = parseVariants(); + consumeToken(TOKEN_BRACE_CLOSE, SyntaxError); + return { + type: "select", + selector, + ...variants + }; } - }); - this.#finish(); - } - destroy() { - this.#uiManager = null; - this.#finish(); - } -} -class ImageAltTextSettings { - #aiModelSettings; - #createModelButton; - #downloadModelButton; - #dialog; - #eventBus; - #mlManager; - #overlayManager; - #showAltTextDialogButton; - constructor({ - dialog, - createModelButton, - aiModelSettings, - learnMore, - closeButton, - deleteModelButton, - downloadModelButton, - showAltTextDialogButton - }, overlayManager, eventBus, mlManager) { - this.#dialog = dialog; - this.#aiModelSettings = aiModelSettings; - this.#createModelButton = createModelButton; - this.#downloadModelButton = downloadModelButton; - this.#showAltTextDialogButton = showAltTextDialogButton; - this.#overlayManager = overlayManager; - this.#eventBus = eventBus; - this.#mlManager = mlManager; - const { - altTextLearnMoreUrl - } = mlManager; - if (altTextLearnMoreUrl) { - learnMore.href = altTextLearnMoreUrl; - } - dialog.addEventListener("contextmenu", noContextMenu); - createModelButton.addEventListener("click", async e => { - const checked = this.#togglePref("enableGuessAltText", e); - await mlManager.toggleService("altText", checked); - this.#reportTelemetry({ - type: "stamp", - action: "pdfjs.image.alt_text.settings_ai_generation_check", - data: { - status: checked + throw new SyntaxError("Unclosed placeable"); + } + function parseInlineExpression() { + if (source[cursor] === "{") { + return parsePlaceable(); + } + if (test(RE_REFERENCE)) { + let [, sigil, name, attr = null] = match(RE_REFERENCE); + if (sigil === "$") { + return { + type: "var", + name + }; } - }); - }); - showAltTextDialogButton.addEventListener("click", e => { - const checked = this.#togglePref("enableNewAltTextWhenAddingImage", e); - this.#reportTelemetry({ - type: "stamp", - action: "pdfjs.image.alt_text.settings_edit_alt_text_check", - data: { - status: checked + if (consumeToken(TOKEN_PAREN_OPEN)) { + let args = parseArguments(); + if (sigil === "-") { + return { + type: "term", + name, + attr, + args + }; + } + if (RE_FUNCTION_NAME.test(name)) { + return { + type: "func", + name, + args + }; + } + throw new SyntaxError("Function names must be all upper-case"); } - }); - }); - deleteModelButton.addEventListener("click", this.#delete.bind(this, true)); - downloadModelButton.addEventListener("click", this.#download.bind(this, true)); - closeButton.addEventListener("click", this.#finish.bind(this)); - learnMore.addEventListener("click", () => { - this.#reportTelemetry({ - type: "stamp", - action: "pdfjs.image.alt_text.info", - data: { - topic: "ai_generation" + if (sigil === "-") { + return { + type: "term", + name, + attr, + args: [] + }; } - }); - }); - eventBus._on("enablealttextmodeldownload", ({ - value - }) => { - if (value) { - this.#download(false); - } else { - this.#delete(false); - } - }); - this.#overlayManager.register(dialog); - } - #reportTelemetry(data) { - this.#eventBus.dispatch("reporttelemetry", { - source: this, - details: { - type: "editing", - data + return { + type: "mesg", + name, + attr + }; } - }); - } - async #download(isFromUI = false) { - if (isFromUI) { - this.#downloadModelButton.disabled = true; - const span = this.#downloadModelButton.firstChild; - span.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-settings-downloading-model-button"); - await this.#mlManager.downloadModel("altText"); - span.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-settings-download-model-button"); - this.#createModelButton.disabled = false; - this.#setPref("enableGuessAltText", true); - this.#mlManager.toggleService("altText", true); - this.#setPref("enableAltTextModelDownload", true); - this.#downloadModelButton.disabled = false; - } - this.#aiModelSettings.classList.toggle("download", false); - this.#createModelButton.setAttribute("aria-pressed", true); - } - async #delete(isFromUI = false) { - if (isFromUI) { - await this.#mlManager.deleteModel("altText"); - this.#setPref("enableGuessAltText", false); - this.#setPref("enableAltTextModelDownload", false); - } - this.#aiModelSettings.classList.toggle("download", true); - this.#createModelButton.disabled = true; - this.#createModelButton.setAttribute("aria-pressed", false); - } - async open({ - enableGuessAltText, - enableNewAltTextWhenAddingImage - }) { - const { - enableAltTextModelDownload - } = this.#mlManager; - this.#createModelButton.disabled = !enableAltTextModelDownload; - this.#createModelButton.setAttribute("aria-pressed", enableAltTextModelDownload && enableGuessAltText); - this.#showAltTextDialogButton.setAttribute("aria-pressed", enableNewAltTextWhenAddingImage); - this.#aiModelSettings.classList.toggle("download", !enableAltTextModelDownload); - await this.#overlayManager.open(this.#dialog); - this.#reportTelemetry({ - type: "stamp", - action: "pdfjs.image.alt_text.settings_displayed" - }); - } - #togglePref(name, { - target - }) { - const checked = target.getAttribute("aria-pressed") !== "true"; - this.#setPref(name, checked); - target.setAttribute("aria-pressed", checked); - return checked; - } - #setPref(name, value) { - this.#eventBus.dispatch("setpreference", { - source: this, - name, - value - }); - } - #finish() { - if (this.#overlayManager.active === this.#dialog) { - this.#overlayManager.close(this.#dialog); + return parseLiteral(); } - } -} - -;// ./web/alt_text_manager.js - -class AltTextManager { - #clickAC = null; - #currentEditor = null; - #cancelButton; - #dialog; - #eventBus; - #hasUsedPointer = false; - #optionDescription; - #optionDecorative; - #overlayManager; - #saveButton; - #textarea; - #uiManager; - #previousAltText = null; - #resizeAC = null; - #svgElement = null; - #rectElement = null; - #container; - #telemetryData = null; - constructor({ - dialog, - optionDescription, - optionDecorative, - textarea, - cancelButton, - saveButton - }, container, overlayManager, eventBus) { - this.#dialog = dialog; - this.#optionDescription = optionDescription; - this.#optionDecorative = optionDecorative; - this.#textarea = textarea; - this.#cancelButton = cancelButton; - this.#saveButton = saveButton; - this.#overlayManager = overlayManager; - this.#eventBus = eventBus; - this.#container = container; - const onUpdateUIState = this.#updateUIState.bind(this); - dialog.addEventListener("close", this.#close.bind(this)); - dialog.addEventListener("contextmenu", event => { - if (event.target !== this.#textarea) { - event.preventDefault(); + function parseArguments() { + let args = []; + while (true) { + switch (source[cursor]) { + case ")": + cursor++; + return args; + case undefined: + throw new SyntaxError("Unclosed argument list"); + } + args.push(parseArgument()); + consumeToken(TOKEN_COMMA); } - }); - cancelButton.addEventListener("click", this.#finish.bind(this)); - saveButton.addEventListener("click", this.#save.bind(this)); - optionDescription.addEventListener("change", onUpdateUIState); - optionDecorative.addEventListener("change", onUpdateUIState); - this.#overlayManager.register(dialog); - } - #createSVGElement() { - if (this.#svgElement) { - return; - } - const svgFactory = new DOMSVGFactory(); - const svg = this.#svgElement = svgFactory.createElement("svg"); - svg.setAttribute("width", "0"); - svg.setAttribute("height", "0"); - const defs = svgFactory.createElement("defs"); - svg.append(defs); - const mask = svgFactory.createElement("mask"); - defs.append(mask); - mask.setAttribute("id", "alttext-manager-mask"); - mask.setAttribute("maskContentUnits", "objectBoundingBox"); - let rect = svgFactory.createElement("rect"); - mask.append(rect); - rect.setAttribute("fill", "white"); - rect.setAttribute("width", "1"); - rect.setAttribute("height", "1"); - rect.setAttribute("x", "0"); - rect.setAttribute("y", "0"); - rect = this.#rectElement = svgFactory.createElement("rect"); - mask.append(rect); - rect.setAttribute("fill", "black"); - this.#dialog.append(svg); - } - async editAltText(uiManager, editor) { - if (this.#currentEditor || !editor) { - return; - } - this.#createSVGElement(); - this.#hasUsedPointer = false; - this.#clickAC = new AbortController(); - const clickOpts = { - signal: this.#clickAC.signal - }, - onClick = this.#onClick.bind(this); - for (const element of [this.#optionDescription, this.#optionDecorative, this.#textarea, this.#saveButton, this.#cancelButton]) { - element.addEventListener("click", onClick, clickOpts); } - const { - altText, - decorative - } = editor.altTextData; - if (decorative === true) { - this.#optionDecorative.checked = true; - this.#optionDescription.checked = false; - } else { - this.#optionDecorative.checked = false; - this.#optionDescription.checked = true; - } - this.#previousAltText = this.#textarea.value = altText?.trim() || ""; - this.#updateUIState(); - this.#currentEditor = editor; - this.#uiManager = uiManager; - this.#uiManager.removeEditListeners(); - this.#resizeAC = new AbortController(); - this.#eventBus._on("resize", this.#setPosition.bind(this), { - signal: this.#resizeAC.signal - }); - try { - await this.#overlayManager.open(this.#dialog); - this.#setPosition(); - } catch (ex) { - this.#close(); - throw ex; - } - } - #setPosition() { - if (!this.#currentEditor) { - return; - } - const dialog = this.#dialog; - const { - style - } = dialog; - const { - x: containerX, - y: containerY, - width: containerW, - height: containerH - } = this.#container.getBoundingClientRect(); - const { - innerWidth: windowW, - innerHeight: windowH - } = window; - const { - width: dialogW, - height: dialogH - } = dialog.getBoundingClientRect(); - const { - x, - y, - width, - height - } = this.#currentEditor.getClientDimensions(); - const MARGIN = 10; - const isLTR = this.#uiManager.direction === "ltr"; - const xs = Math.max(x, containerX); - const xe = Math.min(x + width, containerX + containerW); - const ys = Math.max(y, containerY); - const ye = Math.min(y + height, containerY + containerH); - this.#rectElement.setAttribute("width", `${(xe - xs) / windowW}`); - this.#rectElement.setAttribute("height", `${(ye - ys) / windowH}`); - this.#rectElement.setAttribute("x", `${xs / windowW}`); - this.#rectElement.setAttribute("y", `${ys / windowH}`); - let left = null; - let top = Math.max(y, 0); - top += Math.min(windowH - (top + dialogH), 0); - if (isLTR) { - if (x + width + MARGIN + dialogW < windowW) { - left = x + width + MARGIN; - } else if (x > dialogW + MARGIN) { - left = x - dialogW - MARGIN; - } - } else if (x > dialogW + MARGIN) { - left = x - dialogW - MARGIN; - } else if (x + width + MARGIN + dialogW < windowW) { - left = x + width + MARGIN; - } - if (left === null) { - top = null; - left = Math.max(x, 0); - left += Math.min(windowW - (left + dialogW), 0); - if (y > dialogH + MARGIN) { - top = y - dialogH - MARGIN; - } else if (y + height + MARGIN + dialogH < windowH) { - top = y + height + MARGIN; - } - } - if (top !== null) { - dialog.classList.add("positioned"); - if (isLTR) { - style.left = `${left}px`; - } else { - style.right = `${windowW - left - dialogW}px`; + function parseArgument() { + let expr = parseInlineExpression(); + if (expr.type !== "mesg") { + return expr; } - style.top = `${top}px`; - } else { - dialog.classList.remove("positioned"); - style.left = ""; - style.top = ""; + if (consumeToken(TOKEN_COLON)) { + return { + type: "narg", + name: expr.name, + value: parseLiteral() + }; + } + return expr; } - } - #finish() { - if (this.#overlayManager.active === this.#dialog) { - this.#overlayManager.close(this.#dialog); - } - } - #close() { - this.#currentEditor._reportTelemetry(this.#telemetryData || { - action: "alt_text_cancel", - alt_text_keyboard: !this.#hasUsedPointer - }); - this.#telemetryData = null; - this.#removeOnClickListeners(); - this.#uiManager?.addEditListeners(); - this.#resizeAC?.abort(); - this.#resizeAC = null; - this.#currentEditor.altTextFinish(); - this.#currentEditor = null; - this.#uiManager = null; - } - #updateUIState() { - this.#textarea.disabled = this.#optionDecorative.checked; - } - #save() { - const altText = this.#textarea.value.trim(); - const decorative = this.#optionDecorative.checked; - this.#currentEditor.altTextData = { - altText, - decorative - }; - this.#telemetryData = { - action: "alt_text_save", - alt_text_description: !!altText, - alt_text_edit: !!this.#previousAltText && this.#previousAltText !== altText, - alt_text_decorative: decorative, - alt_text_keyboard: !this.#hasUsedPointer - }; - this.#finish(); - } - #onClick(evt) { - if (evt.detail === 0) { - return; - } - this.#hasUsedPointer = true; - this.#removeOnClickListeners(); - } - #removeOnClickListeners() { - this.#clickAC?.abort(); - this.#clickAC = null; - } - destroy() { - this.#uiManager = null; - this.#finish(); - this.#svgElement?.remove(); - this.#svgElement = this.#rectElement = null; - } -} - -;// ./web/annotation_editor_params.js - -class AnnotationEditorParams { - constructor(options, eventBus) { - this.eventBus = eventBus; - this.#bindListeners(options); - } - #bindListeners({ - editorFreeTextFontSize, - editorFreeTextColor, - editorInkColor, - editorInkThickness, - editorInkOpacity, - editorStampAddImage, - editorFreeHighlightThickness, - editorHighlightShowAll - }) { - const dispatchEvent = (typeStr, value) => { - this.eventBus.dispatch("switchannotationeditorparams", { - source: this, - type: AnnotationEditorParamsType[typeStr], - value - }); - }; - editorFreeTextFontSize.addEventListener("input", function () { - dispatchEvent("FREETEXT_SIZE", this.valueAsNumber); - }); - editorFreeTextColor.addEventListener("input", function () { - dispatchEvent("FREETEXT_COLOR", this.value); - }); - editorInkColor.addEventListener("input", function () { - dispatchEvent("INK_COLOR", this.value); - }); - editorInkThickness.addEventListener("input", function () { - dispatchEvent("INK_THICKNESS", this.valueAsNumber); - }); - editorInkOpacity.addEventListener("input", function () { - dispatchEvent("INK_OPACITY", this.valueAsNumber); - }); - editorStampAddImage.addEventListener("click", () => { - this.eventBus.dispatch("reporttelemetry", { - source: this, - details: { - type: "editing", - data: { - action: "pdfjs.image.add_image_click" - } + function parseVariants() { + let variants = []; + let count = 0; + let star; + while (test(RE_VARIANT_START)) { + if (consumeChar("*")) { + star = count; } - }); - dispatchEvent("CREATE"); - }); - editorFreeHighlightThickness.addEventListener("input", function () { - dispatchEvent("HIGHLIGHT_THICKNESS", this.valueAsNumber); - }); - editorHighlightShowAll.addEventListener("click", function () { - const checked = this.getAttribute("aria-pressed") === "true"; - this.setAttribute("aria-pressed", !checked); - dispatchEvent("HIGHLIGHT_SHOW_ALL", !checked); - }); - this.eventBus._on("annotationeditorparamschanged", evt => { - for (const [type, value] of evt.details) { - switch (type) { - case AnnotationEditorParamsType.FREETEXT_SIZE: - editorFreeTextFontSize.value = value; - break; - case AnnotationEditorParamsType.FREETEXT_COLOR: - editorFreeTextColor.value = value; - break; - case AnnotationEditorParamsType.INK_COLOR: - editorInkColor.value = value; - break; - case AnnotationEditorParamsType.INK_THICKNESS: - editorInkThickness.value = value; - break; - case AnnotationEditorParamsType.INK_OPACITY: - editorInkOpacity.value = value; - break; - case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: - editorFreeHighlightThickness.value = value; - break; - case AnnotationEditorParamsType.HIGHLIGHT_FREE: - editorFreeHighlightThickness.disabled = !value; - break; - case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL: - editorHighlightShowAll.setAttribute("aria-pressed", value); - break; + let key = parseVariantKey(); + let value = parsePattern(); + if (value === null) { + throw new SyntaxError("Expected variant value"); } + variants[count++] = { + key, + value + }; } - }); - } -} - -;// ./web/caret_browsing.js -const PRECISION = 1e-1; -class CaretBrowsingMode { - #mainContainer; - #toolBarHeight = 0; - #viewerContainer; - constructor(abortSignal, mainContainer, viewerContainer, toolbarContainer) { - this.#mainContainer = mainContainer; - this.#viewerContainer = viewerContainer; - if (!toolbarContainer) { - return; - } - this.#toolBarHeight = toolbarContainer.getBoundingClientRect().height; - const toolbarObserver = new ResizeObserver(entries => { - for (const entry of entries) { - if (entry.target === toolbarContainer) { - this.#toolBarHeight = Math.floor(entry.borderBoxSize[0].blockSize); - break; - } + if (count === 0) { + return null; + } + if (star === undefined) { + throw new SyntaxError("Expected default variant"); } - }); - toolbarObserver.observe(toolbarContainer); - abortSignal.addEventListener("abort", () => toolbarObserver.disconnect(), { - once: true - }); - } - #isOnSameLine(rect1, rect2) { - const top1 = rect1.y; - const bot1 = rect1.bottom; - const mid1 = rect1.y + rect1.height / 2; - const top2 = rect2.y; - const bot2 = rect2.bottom; - const mid2 = rect2.y + rect2.height / 2; - return top1 <= mid2 && mid2 <= bot1 || top2 <= mid1 && mid1 <= bot2; - } - #isUnderOver(rect, x, y, isUp) { - const midY = rect.y + rect.height / 2; - return (isUp ? y >= midY : y <= midY) && rect.x - PRECISION <= x && x <= rect.right + PRECISION; - } - #isVisible(rect) { - return rect.top >= this.#toolBarHeight && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth); - } - #getCaretPosition(selection, isUp) { - const { - focusNode, - focusOffset - } = selection; - const range = document.createRange(); - range.setStart(focusNode, focusOffset); - range.setEnd(focusNode, focusOffset); - const rect = range.getBoundingClientRect(); - return [rect.x, isUp ? rect.top : rect.bottom]; - } - static #caretPositionFromPoint(x, y) { - if (!document.caretPositionFromPoint) { - const { - startContainer: offsetNode, - startOffset: offset - } = document.caretRangeFromPoint(x, y); return { - offsetNode, - offset + variants, + star }; } - return document.caretPositionFromPoint(x, y); - } - #setCaretPositionHelper(selection, caretX, select, element, rect) { - rect ||= element.getBoundingClientRect(); - if (caretX <= rect.x + PRECISION) { - if (select) { - selection.extend(element.firstChild, 0); - } else { - selection.setPosition(element.firstChild, 0); - } - return; - } - if (rect.right - PRECISION <= caretX) { - const { - lastChild - } = element; - if (select) { - selection.extend(lastChild, lastChild.length); + function parseVariantKey() { + consumeToken(TOKEN_BRACKET_OPEN, SyntaxError); + let key; + if (test(RE_NUMBER_LITERAL)) { + key = parseNumberLiteral(); } else { - selection.setPosition(lastChild, lastChild.length); + key = { + type: "str", + value: match1(RE_IDENTIFIER) + }; } - return; + consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError); + return key; } - const midY = rect.y + rect.height / 2; - let caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY); - let parentElement = caretPosition.offsetNode?.parentElement; - if (parentElement && parentElement !== element) { - const elementsAtPoint = document.elementsFromPoint(caretX, midY); - const savedVisibilities = []; - for (const el of elementsAtPoint) { - if (el === element) { - break; - } - const { - style - } = el; - savedVisibilities.push([el, style.visibility]); - style.visibility = "hidden"; - } - caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY); - parentElement = caretPosition.offsetNode?.parentElement; - for (const [el, visibility] of savedVisibilities) { - el.style.visibility = visibility; + function parseLiteral() { + if (test(RE_NUMBER_LITERAL)) { + return parseNumberLiteral(); } - } - if (parentElement !== element) { - if (select) { - selection.extend(element.firstChild, 0); - } else { - selection.setPosition(element.firstChild, 0); + if (source[cursor] === '"') { + return parseStringLiteral(); } - return; - } - if (select) { - selection.extend(caretPosition.offsetNode, caretPosition.offset); - } else { - selection.setPosition(caretPosition.offsetNode, caretPosition.offset); + throw new SyntaxError("Invalid expression"); } - } - #setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX) { - if (this.#isVisible(newLineElementRect)) { - this.#setCaretPositionHelper(selection, caretX, select, newLineElement, newLineElementRect); - return; + function parseNumberLiteral() { + let [, value, fraction = ""] = match(RE_NUMBER_LITERAL); + let precision = fraction.length; + return { + type: "num", + value: parseFloat(value), + precision + }; } - this.#mainContainer.addEventListener("scrollend", this.#setCaretPositionHelper.bind(this, selection, caretX, select, newLineElement, null), { - once: true - }); - newLineElement.scrollIntoView(); - } - #getNodeOnNextPage(textLayer, isUp) { - while (true) { - const page = textLayer.closest(".page"); - const pageNumber = parseInt(page.getAttribute("data-page-number")); - const nextPage = isUp ? pageNumber - 1 : pageNumber + 1; - textLayer = this.#viewerContainer.querySelector(`.page[data-page-number="${nextPage}"] .textLayer`); - if (!textLayer) { - return null; - } - const walker = document.createTreeWalker(textLayer, NodeFilter.SHOW_TEXT); - const node = isUp ? walker.lastChild() : walker.firstChild(); - if (node) { - return node; + function parseStringLiteral() { + consumeChar('"', SyntaxError); + let value = ""; + while (true) { + value += match1(RE_STRING_RUN); + if (source[cursor] === "\\") { + value += parseEscapeSequence(); + continue; + } + if (consumeChar('"')) { + return { + type: "str", + value + }; + } + throw new SyntaxError("Unclosed string literal"); } } - } - moveCaret(isUp, select) { - const selection = document.getSelection(); - if (selection.rangeCount === 0) { - return; - } - const { - focusNode - } = selection; - const focusElement = focusNode.nodeType !== Node.ELEMENT_NODE ? focusNode.parentElement : focusNode; - const root = focusElement.closest(".textLayer"); - if (!root) { - return; - } - const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); - walker.currentNode = focusNode; - const focusRect = focusElement.getBoundingClientRect(); - let newLineElement = null; - const nodeIterator = (isUp ? walker.previousSibling : walker.nextSibling).bind(walker); - while (nodeIterator()) { - const element = walker.currentNode.parentElement; - if (!this.#isOnSameLine(focusRect, element.getBoundingClientRect())) { - newLineElement = element; - break; + function parseEscapeSequence() { + if (test(RE_STRING_ESCAPE)) { + return match1(RE_STRING_ESCAPE); + } + if (test(RE_UNICODE_ESCAPE)) { + let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE); + let codepoint = parseInt(codepoint4 || codepoint6, 16); + return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�"; } + throw new SyntaxError("Unknown escape sequence"); } - if (!newLineElement) { - const node = this.#getNodeOnNextPage(root, isUp); - if (!node) { - return; + function parseIndent() { + let start = cursor; + consumeToken(TOKEN_BLANK); + switch (source[cursor]) { + case ".": + case "[": + case "*": + case "}": + case undefined: + return false; + case "{": + return makeIndent(source.slice(start, cursor)); } - if (select) { - const lastNode = (isUp ? walker.firstChild() : walker.lastChild()) || focusNode; - selection.extend(lastNode, isUp ? 0 : lastNode.length); - const range = document.createRange(); - range.setStart(node, isUp ? node.length : 0); - range.setEnd(node, isUp ? node.length : 0); - selection.addRange(range); - return; + if (source[cursor - 1] === " ") { + return makeIndent(source.slice(start, cursor)); } - const [caretX] = this.#getCaretPosition(selection, isUp); - const { - parentElement - } = node; - this.#setCaretPosition(select, selection, parentElement, parentElement.getBoundingClientRect(), caretX); - return; + return false; } - const [caretX, caretY] = this.#getCaretPosition(selection, isUp); - const newLineElementRect = newLineElement.getBoundingClientRect(); - if (this.#isUnderOver(newLineElementRect, caretX, caretY, isUp)) { - this.#setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX); - return; + function trim(text, re) { + return text.replace(re, ""); } - while (nodeIterator()) { - const element = walker.currentNode.parentElement; - const elementRect = element.getBoundingClientRect(); - if (!this.#isOnSameLine(newLineElementRect, elementRect)) { - break; - } - if (this.#isUnderOver(elementRect, caretX, caretY, isUp)) { - this.#setCaretPosition(select, selection, element, elementRect, caretX); - return; - } + function makeIndent(blank) { + let value = blank.replace(RE_BLANK_LINES, "\n"); + let length = RE_INDENT.exec(blank)[1].length; + return new Indent(value, length); } - this.#setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX); - } -} - -;// ./web/download_manager.js - -function download(blobUrl, filename) { - const a = document.createElement("a"); - if (!a.click) { - throw new Error('DownloadManager: "a.click()" is not supported.'); - } - a.href = blobUrl; - a.target = "_parent"; - if ("download" in a) { - a.download = filename; } - (document.body || document.documentElement).append(a); - a.click(); - a.remove(); } -class DownloadManager { - #openBlobUrls = new WeakMap(); - downloadData(data, filename, contentType) { - const blobUrl = URL.createObjectURL(new Blob([data], { - type: contentType - })); - download(blobUrl, filename); - } - openOrDownloadData(data, filename, dest = null) { - const isPdfData = isPdfFile(filename); - const contentType = isPdfData ? "application/pdf" : ""; - if (isPdfData) { - let blobUrl = this.#openBlobUrls.get(data); - if (!blobUrl) { - blobUrl = URL.createObjectURL(new Blob([data], { - type: contentType - })); - this.#openBlobUrls.set(data, blobUrl); - } - let viewerUrl; - viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename); - if (dest) { - viewerUrl += `#${escape(dest)}`; - } - try { - window.open(viewerUrl); - return true; - } catch (ex) { - console.error("openOrDownloadData:", ex); - URL.revokeObjectURL(blobUrl); - this.#openBlobUrls.delete(data); - } - } - this.downloadData(data, filename, contentType); - return false; - } - download(data, url, filename) { - let blobUrl; - if (data) { - blobUrl = URL.createObjectURL(new Blob([data], { - type: "application/pdf" - })); - } else { - if (!createValidAbsoluteUrl(url, "http://example.com")) { - console.error(`download - not a valid URL: ${url}`); - return; - } - blobUrl = url + "#pdfjs.action=download"; - } - download(blobUrl, filename); +class Indent { + constructor(value, length) { + this.value = value; + this.length = length; } } +;// ./node_modules/@fluent/bundle/esm/index.js -;// ./web/editor_undo_bar.js -class EditorUndoBar { - #closeButton = null; - #container; - #eventBus = null; - #focusTimeout = null; - #initController = null; - isOpen = false; - #message; - #showController = null; - #undoButton; - static #l10nMessages = Object.freeze({ - highlight: "pdfjs-editor-undo-bar-message-highlight", - freetext: "pdfjs-editor-undo-bar-message-freetext", - stamp: "pdfjs-editor-undo-bar-message-stamp", - ink: "pdfjs-editor-undo-bar-message-ink", - _multiple: "pdfjs-editor-undo-bar-message-multiple" - }); - constructor({ - container, - message, - undoButton, - closeButton - }, eventBus) { - this.#container = container; - this.#message = message; - this.#undoButton = undoButton; - this.#closeButton = closeButton; - this.#eventBus = eventBus; + +;// ./node_modules/@fluent/dom/esm/overlay.js +const reOverlay = /<|&#?\w+;/; +const TEXT_LEVEL_ELEMENTS = { + "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"] +}; +const LOCALIZABLE_ATTRIBUTES = { + "http://www.w3.org/1999/xhtml": { + global: ["title", "aria-label", "aria-valuetext"], + a: ["download"], + area: ["download", "alt"], + input: ["alt", "placeholder"], + menuitem: ["label"], + menu: ["label"], + optgroup: ["label"], + option: ["label"], + track: ["label"], + img: ["alt"], + textarea: ["placeholder"], + th: ["abbr"] + }, + "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": { + global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"], + description: ["value"], + key: ["key", "keycode"], + label: ["value"], + textbox: ["placeholder", "value"] } - destroy() { - this.#initController?.abort(); - this.#initController = null; - this.hide(); - } - show(undoAction, messageData) { - if (!this.#initController) { - this.#initController = new AbortController(); - const opts = { - signal: this.#initController.signal - }; - const boundHide = this.hide.bind(this); - this.#container.addEventListener("contextmenu", noContextMenu, opts); - this.#closeButton.addEventListener("click", boundHide, opts); - this.#eventBus._on("beforeprint", boundHide, opts); - this.#eventBus._on("download", boundHide, opts); - } - this.hide(); - if (typeof messageData === "string") { - this.#message.setAttribute("data-l10n-id", EditorUndoBar.#l10nMessages[messageData]); +}; +function translateElement(element, translation) { + const { + value + } = translation; + if (typeof value === "string") { + if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") { + element.textContent = value; + } else if (!reOverlay.test(value)) { + element.textContent = value; } else { - this.#message.setAttribute("data-l10n-id", EditorUndoBar.#l10nMessages._multiple); - this.#message.setAttribute("data-l10n-args", JSON.stringify({ - count: messageData - })); + const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template"); + templateElement.innerHTML = value; + overlayChildNodes(templateElement.content, element); } - this.isOpen = true; - this.#container.hidden = false; - this.#showController = new AbortController(); - this.#undoButton.addEventListener("click", () => { - undoAction(); - this.hide(); - }, { - signal: this.#showController.signal - }); - this.#focusTimeout = setTimeout(() => { - this.#container.focus(); - this.#focusTimeout = null; - }, 100); } - hide() { - if (!this.isOpen) { - return; + overlayAttributes(translation, element); +} +function overlayChildNodes(fromFragment, toElement) { + for (const childNode of fromFragment.childNodes) { + if (childNode.nodeType === childNode.TEXT_NODE) { + continue; } - this.isOpen = false; - this.#container.hidden = true; - this.#showController?.abort(); - this.#showController = null; - if (this.#focusTimeout) { - clearTimeout(this.#focusTimeout); - this.#focusTimeout = null; + if (childNode.hasAttribute("data-l10n-name")) { + const sanitized = getNodeForNamedElement(toElement, childNode); + fromFragment.replaceChild(sanitized, childNode); + continue; + } + if (isElementAllowed(childNode)) { + const sanitized = createSanitizedElement(childNode); + fromFragment.replaceChild(sanitized, childNode); + continue; } + console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed."); + fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode); } + toElement.textContent = ""; + toElement.appendChild(fromFragment); } - -;// ./web/overlay_manager.js -class OverlayManager { - #overlays = new WeakMap(); - #active = null; - get active() { - return this.#active; - } - async register(dialog, canForceClose = false) { - if (typeof dialog !== "object") { - throw new Error("Not enough parameters."); - } else if (this.#overlays.has(dialog)) { - throw new Error("The overlay is already registered."); - } - this.#overlays.set(dialog, { - canForceClose - }); - dialog.addEventListener("cancel", evt => { - this.#active = null; - }); - } - async open(dialog) { - if (!this.#overlays.has(dialog)) { - throw new Error("The overlay does not exist."); - } else if (this.#active) { - if (this.#active === dialog) { - throw new Error("The overlay is already active."); - } else if (this.#overlays.get(dialog).canForceClose) { - await this.close(); - } else { - throw new Error("Another overlay is currently active."); - } - } - this.#active = dialog; - dialog.showModal(); +function hasAttribute(attributes, name) { + if (!attributes) { + return false; } - async close(dialog = this.#active) { - if (!this.#overlays.has(dialog)) { - throw new Error("The overlay does not exist."); - } else if (!this.#active) { - throw new Error("The overlay is currently not active."); - } else if (this.#active !== dialog) { - throw new Error("Another overlay is currently active."); + for (let attr of attributes) { + if (attr.name === name) { + return true; } - dialog.close(); - this.#active = null; } + return false; } - -;// ./web/password_prompt.js - -class PasswordPrompt { - #activeCapability = null; - #updateCallback = null; - #reason = null; - constructor(options, overlayManager, isViewerEmbedded = false) { - this.dialog = options.dialog; - this.label = options.label; - this.input = options.input; - this.submitButton = options.submitButton; - this.cancelButton = options.cancelButton; - this.overlayManager = overlayManager; - this._isViewerEmbedded = isViewerEmbedded; - this.submitButton.addEventListener("click", this.#verify.bind(this)); - this.cancelButton.addEventListener("click", this.close.bind(this)); - this.input.addEventListener("keydown", e => { - if (e.keyCode === 13) { - this.#verify(); - } - }); - this.overlayManager.register(this.dialog, true); - this.dialog.addEventListener("close", this.#cancel.bind(this)); - } - async open() { - await this.#activeCapability?.promise; - this.#activeCapability = Promise.withResolvers(); - try { - await this.overlayManager.open(this.dialog); - } catch (ex) { - this.#activeCapability.resolve(); - throw ex; - } - const passwordIncorrect = this.#reason === PasswordResponses.INCORRECT_PASSWORD; - if (!this._isViewerEmbedded || passwordIncorrect) { - this.input.focus(); +function overlayAttributes(fromElement, toElement) { + const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null; + for (const attr of Array.from(toElement.attributes)) { + if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) { + toElement.removeAttribute(attr.name); } - this.label.setAttribute("data-l10n-id", passwordIncorrect ? "pdfjs-password-invalid" : "pdfjs-password-label"); } - async close() { - if (this.overlayManager.active === this.dialog) { - this.overlayManager.close(this.dialog); - } + if (!fromElement.attributes) { + return; } - #verify() { - const password = this.input.value; - if (password?.length > 0) { - this.#invokeCallback(password); + for (const attr of Array.from(fromElement.attributes)) { + if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) { + toElement.setAttribute(attr.name, attr.value); } } - #cancel() { - this.#invokeCallback(new Error("PasswordPrompt cancelled.")); - this.#activeCapability.resolve(); - } - #invokeCallback(password) { - if (!this.#updateCallback) { - return; - } - this.close(); - this.input.value = ""; - this.#updateCallback(password); - this.#updateCallback = null; +} +function getNodeForNamedElement(sourceElement, translatedChild) { + const childName = translatedChild.getAttribute("data-l10n-name"); + const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`); + if (!sourceChild) { + console.warn(`An element named "${childName}" wasn't found in the source.`); + return createTextNodeFromTextContent(translatedChild); } - async setUpdateCallback(updateCallback, reason) { - if (this.#activeCapability) { - await this.#activeCapability.promise; - } - this.#updateCallback = updateCallback; - this.#reason = reason; + if (sourceChild.localName !== translatedChild.localName) { + console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`); + return createTextNodeFromTextContent(translatedChild); } + sourceElement.removeChild(sourceChild); + const clone = sourceChild.cloneNode(false); + return shallowPopulateUsing(translatedChild, clone); } - -;// ./web/base_tree_viewer.js - -const TREEITEM_OFFSET_TOP = -100; -const TREEITEM_SELECTED_CLASS = "selected"; -class BaseTreeViewer { - constructor(options) { - this.container = options.container; - this.eventBus = options.eventBus; - this._l10n = options.l10n; - this.reset(); +function createSanitizedElement(element) { + const clone = element.ownerDocument.createElement(element.localName); + return shallowPopulateUsing(element, clone); +} +function createTextNodeFromTextContent(element) { + return element.ownerDocument.createTextNode(element.textContent); +} +function isElementAllowed(element) { + const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI]; + return allowed && allowed.includes(element.localName); +} +function isAttrNameLocalizable(name, element, explicitlyAllowed = null) { + if (explicitlyAllowed && explicitlyAllowed.includes(name)) { + return true; } - reset() { - this._pdfDocument = null; - this._lastToggleIsShow = true; - this._currentTreeItem = null; - this.container.textContent = ""; - this.container.classList.remove("treeWithDeepNesting"); + const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI]; + if (!allowed) { + return false; } - _dispatchEvent(count) { - throw new Error("Not implemented: _dispatchEvent"); + const attrName = name.toLowerCase(); + const elemName = element.localName; + if (allowed.global.includes(attrName)) { + return true; } - _bindLink(element, params) { - throw new Error("Not implemented: _bindLink"); + if (!allowed[elemName]) { + return false; } - _normalizeTextContent(str) { - return removeNullCharacters(str, true) || "\u2013"; + if (allowed[elemName].includes(attrName)) { + return true; } - _addToggleButton(div, hidden = false) { - const toggler = document.createElement("div"); - toggler.className = "treeItemToggler"; - if (hidden) { - toggler.classList.add("treeItemsHidden"); + if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") { + const type = element.type.toLowerCase(); + if (type === "submit" || type === "button" || type === "reset") { + return true; } - toggler.onclick = evt => { - evt.stopPropagation(); - toggler.classList.toggle("treeItemsHidden"); - if (evt.shiftKey) { - const shouldShowAll = !toggler.classList.contains("treeItemsHidden"); - this._toggleTreeItem(div, shouldShowAll); - } - }; - div.prepend(toggler); } - _toggleTreeItem(root, show = false) { - this._l10n.pause(); - this._lastToggleIsShow = show; - for (const toggler of root.querySelectorAll(".treeItemToggler")) { - toggler.classList.toggle("treeItemsHidden", !show); + return false; +} +function shallowPopulateUsing(fromElement, toElement) { + toElement.textContent = fromElement.textContent; + overlayAttributes(fromElement, toElement); + return toElement; +} +;// ./node_modules/cached-iterable/src/cached_iterable.mjs +class CachedIterable extends Array { + static from(iterable) { + if (iterable instanceof this) { + return iterable; } - this._l10n.resume(); - } - _toggleAllTreeItems() { - this._toggleTreeItem(this.container, !this._lastToggleIsShow); + return new this(iterable); } - _finishRendering(fragment, count, hasAnyNesting = false) { - if (hasAnyNesting) { - this.container.classList.add("treeWithDeepNesting"); - this._lastToggleIsShow = !fragment.querySelector(".treeItemsHidden"); +} +;// ./node_modules/cached-iterable/src/cached_sync_iterable.mjs + +class CachedSyncIterable extends CachedIterable { + constructor(iterable) { + super(); + if (Symbol.iterator in Object(iterable)) { + this.iterator = iterable[Symbol.iterator](); + } else { + throw new TypeError("Argument must implement the iteration protocol."); } - this._l10n.pause(); - this.container.append(fragment); - this._l10n.resume(); - this._dispatchEvent(count); - } - render(params) { - throw new Error("Not implemented: render"); } - _updateCurrentTreeItem(treeItem = null) { - if (this._currentTreeItem) { - this._currentTreeItem.classList.remove(TREEITEM_SELECTED_CLASS); - this._currentTreeItem = null; - } - if (treeItem) { - treeItem.classList.add(TREEITEM_SELECTED_CLASS); - this._currentTreeItem = treeItem; - } + [Symbol.iterator]() { + const cached = this; + let cur = 0; + return { + next() { + if (cached.length <= cur) { + cached.push(cached.iterator.next()); + } + return cached[cur++]; + } + }; } - _scrollToCurrentTreeItem(treeItem) { - if (!treeItem) { - return; - } - this._l10n.pause(); - let currentNode = treeItem.parentNode; - while (currentNode && currentNode !== this.container) { - if (currentNode.classList.contains("treeItem")) { - const toggler = currentNode.firstElementChild; - toggler?.classList.remove("treeItemsHidden"); + touchNext(count = 1) { + let idx = 0; + while (idx++ < count) { + const last = this[this.length - 1]; + if (last && last.done) { + break; } - currentNode = currentNode.parentNode; + this.push(this.iterator.next()); } - this._l10n.resume(); - this._updateCurrentTreeItem(treeItem); - this.container.scrollTo(treeItem.offsetLeft, treeItem.offsetTop + TREEITEM_OFFSET_TOP); + return this[this.length - 1]; } } +;// ./node_modules/cached-iterable/src/cached_async_iterable.mjs -;// ./web/pdf_attachment_viewer.js - - -class PDFAttachmentViewer extends BaseTreeViewer { - constructor(options) { - super(options); - this.downloadManager = options.downloadManager; - this.eventBus._on("fileattachmentannotation", this.#appendAttachment.bind(this)); - } - reset(keepRenderedCapability = false) { - super.reset(); - this._attachments = null; - if (!keepRenderedCapability) { - this._renderedCapability = Promise.withResolvers(); - } - this._pendingDispatchEvent = false; - } - async _dispatchEvent(attachmentsCount) { - this._renderedCapability.resolve(); - if (attachmentsCount === 0 && !this._pendingDispatchEvent) { - this._pendingDispatchEvent = true; - await waitOnEventOrTimeout({ - target: this.eventBus, - name: "annotationlayerrendered", - delay: 1000 - }); - if (!this._pendingDispatchEvent) { - return; - } +class CachedAsyncIterable extends CachedIterable { + constructor(iterable) { + super(); + if (Symbol.asyncIterator in Object(iterable)) { + this.iterator = iterable[Symbol.asyncIterator](); + } else if (Symbol.iterator in Object(iterable)) { + this.iterator = iterable[Symbol.iterator](); + } else { + throw new TypeError("Argument must implement the iteration protocol."); } - this._pendingDispatchEvent = false; - this.eventBus.dispatch("attachmentsloaded", { - source: this, - attachmentsCount - }); } - _bindLink(element, { - content, - description, - filename - }) { - if (description) { - element.title = description; - } - element.onclick = () => { - this.downloadManager.openOrDownloadData(content, filename); - return false; + [Symbol.asyncIterator]() { + const cached = this; + let cur = 0; + return { + async next() { + if (cached.length <= cur) { + cached.push(cached.iterator.next()); + } + return cached[cur++]; + } }; } - render({ - attachments, - keepRenderedCapability = false - }) { - if (this._attachments) { - this.reset(keepRenderedCapability); - } - this._attachments = attachments || null; - if (!attachments) { - this._dispatchEvent(0); - return; - } - const fragment = document.createDocumentFragment(); - let attachmentsCount = 0; - for (const name in attachments) { - const item = attachments[name]; - const div = document.createElement("div"); - div.className = "treeItem"; - const element = document.createElement("a"); - this._bindLink(element, item); - element.textContent = this._normalizeTextContent(item.filename); - div.append(element); - fragment.append(div); - attachmentsCount++; - } - this._finishRendering(fragment, attachmentsCount); - } - #appendAttachment(item) { - const renderedPromise = this._renderedCapability.promise; - renderedPromise.then(() => { - if (renderedPromise !== this._renderedCapability.promise) { - return; - } - const attachments = this._attachments || Object.create(null); - for (const name in attachments) { - if (item.filename === name) { - return; - } + async touchNext(count = 1) { + let idx = 0; + while (idx++ < count) { + const last = this[this.length - 1]; + if (last && (await last).done) { + break; } - attachments[item.filename] = item; - this.render({ - attachments, - keepRenderedCapability: true - }); - }); + this.push(this.iterator.next()); + } + return this[this.length - 1]; } } +;// ./node_modules/cached-iterable/src/index.mjs -;// ./web/grab_to_pan.js -const CSS_CLASS_GRAB = "grab-to-pan-grab"; -class GrabToPan { - #activateAC = null; - #mouseDownAC = null; - #scrollAC = null; - constructor({ - element - }) { - this.element = element; - this.document = element.ownerDocument; - const overlay = this.overlay = document.createElement("div"); - overlay.className = "grab-to-pan-grabbing"; - } - activate() { - if (!this.#activateAC) { - this.#activateAC = new AbortController(); - this.element.addEventListener("mousedown", this.#onMouseDown.bind(this), { - capture: true, - signal: this.#activateAC.signal - }); - this.element.classList.add(CSS_CLASS_GRAB); - } +;// ./node_modules/@fluent/dom/esm/localization.js + +class Localization { + constructor(resourceIds = [], generateBundles) { + this.resourceIds = resourceIds; + this.generateBundles = generateBundles; + this.onChange(true); } - deactivate() { - if (this.#activateAC) { - this.#activateAC.abort(); - this.#activateAC = null; - this.#endPan(); - this.element.classList.remove(CSS_CLASS_GRAB); - } + addResourceIds(resourceIds, eager = false) { + this.resourceIds.push(...resourceIds); + this.onChange(eager); + return this.resourceIds.length; } - toggle() { - if (this.#activateAC) { - this.deactivate(); - } else { - this.activate(); + removeResourceIds(resourceIds) { + this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r)); + this.onChange(); + return this.resourceIds.length; + } + async formatWithFallback(keys, method) { + const translations = []; + let hasAtLeastOneBundle = false; + for await (const bundle of this.bundles) { + hasAtLeastOneBundle = true; + const missingIds = keysFromBundle(method, bundle, keys, translations); + if (missingIds.size === 0) { + break; + } + if (typeof console !== "undefined") { + const locale = bundle.locales[0]; + const ids = Array.from(missingIds).join(", "); + console.warn(`[fluent] Missing translations in ${locale}: ${ids}`); + } + } + if (!hasAtLeastOneBundle && typeof console !== "undefined") { + console.warn(`[fluent] Request for keys failed because no resource bundles got generated. + keys: ${JSON.stringify(keys)}. + resourceIds: ${JSON.stringify(this.resourceIds)}.`); } + return translations; } - ignoreTarget(node) { - return node.matches("a[href], a[href] *, input, textarea, button, button *, select, option"); + formatMessages(keys) { + return this.formatWithFallback(keys, messageFromBundle); } - #onMouseDown(event) { - if (event.button !== 0 || this.ignoreTarget(event.target)) { - return; - } - if (event.originalTarget) { - try { - event.originalTarget.tagName; - } catch { - return; - } + formatValues(keys) { + return this.formatWithFallback(keys, valueFromBundle); + } + async formatValue(id, args) { + const [val] = await this.formatValues([{ + id, + args + }]); + return val; + } + handleEvent() { + this.onChange(); + } + onChange(eager = false) { + this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds)); + if (eager) { + this.bundles.touchNext(2); } - this.scrollLeftStart = this.element.scrollLeft; - this.scrollTopStart = this.element.scrollTop; - this.clientXStart = event.clientX; - this.clientYStart = event.clientY; - this.#mouseDownAC = new AbortController(); - const boundEndPan = this.#endPan.bind(this), - mouseOpts = { - capture: true, - signal: this.#mouseDownAC.signal + } +} +function valueFromBundle(bundle, errors, message, args) { + if (message.value) { + return bundle.formatPattern(message.value, args, errors); + } + return null; +} +function messageFromBundle(bundle, errors, message, args) { + const formatted = { + value: null, + attributes: null + }; + if (message.value) { + formatted.value = bundle.formatPattern(message.value, args, errors); + } + let attrNames = Object.keys(message.attributes); + if (attrNames.length > 0) { + formatted.attributes = new Array(attrNames.length); + for (let [i, name] of attrNames.entries()) { + let value = bundle.formatPattern(message.attributes[name], args, errors); + formatted.attributes[i] = { + name, + value }; - this.document.addEventListener("mousemove", this.#onMouseMove.bind(this), mouseOpts); - this.document.addEventListener("mouseup", boundEndPan, mouseOpts); - this.#scrollAC = new AbortController(); - this.element.addEventListener("scroll", boundEndPan, { - capture: true, - signal: this.#scrollAC.signal - }); - stopEvent(event); - const focusedElement = document.activeElement; - if (focusedElement && !focusedElement.contains(event.target)) { - focusedElement.blur(); } } - #onMouseMove(event) { - this.#scrollAC?.abort(); - this.#scrollAC = null; - if (!(event.buttons & 1)) { - this.#endPan(); + return formatted; +} +function keysFromBundle(method, bundle, keys, translations) { + const messageErrors = []; + const missingIds = new Set(); + keys.forEach(({ + id, + args + }, i) => { + if (translations[i] !== undefined) { return; } - const xDiff = event.clientX - this.clientXStart; - const yDiff = event.clientY - this.clientYStart; - this.element.scrollTo({ - top: this.scrollTopStart - yDiff, - left: this.scrollLeftStart - xDiff, - behavior: "instant" - }); - if (!this.overlay.parentNode) { - document.body.append(this.overlay); + let message = bundle.getMessage(id); + if (message) { + messageErrors.length = 0; + translations[i] = method(bundle, messageErrors, message, args); + if (messageErrors.length > 0 && typeof console !== "undefined") { + const locale = bundle.locales[0]; + const errors = messageErrors.join(", "); + console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`); + } + } else { + missingIds.add(id); } - } - #endPan() { - this.#mouseDownAC?.abort(); - this.#mouseDownAC = null; - this.#scrollAC?.abort(); - this.#scrollAC = null; - this.overlay.remove(); - } + }); + return missingIds; } - -;// ./web/pdf_cursor_tools.js - +;// ./node_modules/@fluent/dom/esm/dom_localization.js -class PDFCursorTools { - #active = CursorTool.SELECT; - #prevActive = null; - constructor({ - container, - eventBus, - cursorToolOnLoad = CursorTool.SELECT - }) { - this.container = container; - this.eventBus = eventBus; - this.#addEventListeners(); - Promise.resolve().then(() => { - this.switchTool(cursorToolOnLoad); - }); +const L10NID_ATTR_NAME = "data-l10n-id"; +const L10NARGS_ATTR_NAME = "data-l10n-args"; +const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`; +class DOMLocalization extends Localization { + constructor(resourceIds, generateBundles) { + super(resourceIds, generateBundles); + this.roots = new Set(); + this.pendingrAF = null; + this.pendingElements = new Set(); + this.windowElement = null; + this.mutationObserver = null; + this.observerConfig = { + attributes: true, + characterData: false, + childList: true, + subtree: true, + attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME] + }; } - get activeTool() { - return this.#active; + onChange(eager = false) { + super.onChange(eager); + if (this.roots) { + this.translateRoots(); + } } - switchTool(tool) { - if (this.#prevActive !== null) { - return; + setAttributes(element, id, args) { + element.setAttribute(L10NID_ATTR_NAME, id); + if (args) { + element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args)); + } else { + element.removeAttribute(L10NARGS_ATTR_NAME); } - this.#switchTool(tool); + return element; } - #switchTool(tool, disabled = false) { - if (tool === this.#active) { - if (this.#prevActive !== null) { - this.eventBus.dispatch("cursortoolchanged", { - source: this, - tool, - disabled - }); + getAttributes(element) { + return { + id: element.getAttribute(L10NID_ATTR_NAME), + args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) + }; + } + connectRoot(newRoot) { + for (const root of this.roots) { + if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) { + throw new Error("Cannot add a root that overlaps with existing root."); } - return; } - const disableActiveTool = () => { - switch (this.#active) { - case CursorTool.SELECT: - break; - case CursorTool.HAND: - this._handTool.deactivate(); - break; - case CursorTool.ZOOM: + if (this.windowElement) { + if (this.windowElement !== newRoot.ownerDocument.defaultView) { + throw new Error(`Cannot connect a root: + DOMLocalization already has a root from a different window.`); } - }; - switch (tool) { - case CursorTool.SELECT: - disableActiveTool(); - break; - case CursorTool.HAND: - disableActiveTool(); - this._handTool.activate(); - break; - case CursorTool.ZOOM: - default: - console.error(`switchTool: "${tool}" is an unsupported value.`); - return; + } else { + this.windowElement = newRoot.ownerDocument.defaultView; + this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations)); } - this.#active = tool; - this.eventBus.dispatch("cursortoolchanged", { - source: this, - tool, - disabled - }); + this.roots.add(newRoot); + this.mutationObserver.observe(newRoot, this.observerConfig); } - #addEventListeners() { - this.eventBus._on("switchcursortool", evt => { - if (!evt.reset) { - this.switchTool(evt.tool); - } else if (this.#prevActive !== null) { - annotationEditorMode = AnnotationEditorType.NONE; - presentationModeState = PresentationModeState.NORMAL; - enableActive(); - } - }); - let annotationEditorMode = AnnotationEditorType.NONE, - presentationModeState = PresentationModeState.NORMAL; - const disableActive = () => { - this.#prevActive ??= this.#active; - this.#switchTool(CursorTool.SELECT, true); - }; - const enableActive = () => { - if (this.#prevActive !== null && annotationEditorMode === AnnotationEditorType.NONE && presentationModeState === PresentationModeState.NORMAL) { - this.#switchTool(this.#prevActive); - this.#prevActive = null; - } - }; - this.eventBus._on("annotationeditormodechanged", ({ - mode - }) => { - annotationEditorMode = mode; - if (mode === AnnotationEditorType.NONE) { - enableActive(); - } else { - disableActive(); - } - }); - this.eventBus._on("presentationmodechanged", ({ - state - }) => { - presentationModeState = state; - if (state === PresentationModeState.NORMAL) { - enableActive(); - } else if (state === PresentationModeState.FULLSCREEN) { - disableActive(); + disconnectRoot(root) { + this.roots.delete(root); + this.pauseObserving(); + if (this.roots.size === 0) { + this.mutationObserver = null; + if (this.windowElement && this.pendingrAF) { + this.windowElement.cancelAnimationFrame(this.pendingrAF); } - }); - } - get _handTool() { - return shadow(this, "_handTool", new GrabToPan({ - element: this.container - })); - } -} - -;// ./web/pdf_document_properties.js - - -const NON_METRIC_LOCALES = ["en-us", "en-lr", "my"]; -const US_PAGE_NAMES = { - "8.5x11": "pdfjs-document-properties-page-size-name-letter", - "8.5x14": "pdfjs-document-properties-page-size-name-legal" -}; -const METRIC_PAGE_NAMES = { - "297x420": "pdfjs-document-properties-page-size-name-a-three", - "210x297": "pdfjs-document-properties-page-size-name-a-four" -}; -function getPageName(size, isPortrait, pageNames) { - const width = isPortrait ? size.width : size.height; - const height = isPortrait ? size.height : size.width; - return pageNames[`${width}x${height}`]; -} -class PDFDocumentProperties { - #fieldData = null; - constructor({ - dialog, - fields, - closeButton - }, overlayManager, eventBus, l10n, fileNameLookup) { - this.dialog = dialog; - this.fields = fields; - this.overlayManager = overlayManager; - this.l10n = l10n; - this._fileNameLookup = fileNameLookup; - this.#reset(); - closeButton.addEventListener("click", this.close.bind(this)); - this.overlayManager.register(this.dialog); - eventBus._on("pagechanging", evt => { - this._currentPageNumber = evt.pageNumber; - }); - eventBus._on("rotationchanging", evt => { - this._pagesRotation = evt.pagesRotation; - }); - } - async open() { - await Promise.all([this.overlayManager.open(this.dialog), this._dataAvailableCapability.promise]); - const currentPageNumber = this._currentPageNumber; - const pagesRotation = this._pagesRotation; - if (this.#fieldData && currentPageNumber === this.#fieldData._currentPageNumber && pagesRotation === this.#fieldData._pagesRotation) { - this.#updateUI(); - return; - } - const [{ - info, - contentLength - }, pdfPage] = await Promise.all([this.pdfDocument.getMetadata(), this.pdfDocument.getPage(currentPageNumber)]); - const [fileName, fileSize, creationDate, modificationDate, pageSize, isLinearized] = await Promise.all([this._fileNameLookup(), this.#parseFileSize(contentLength), this.#parseDate(info.CreationDate), this.#parseDate(info.ModDate), this.#parsePageSize(getPageSizeInches(pdfPage), pagesRotation), this.#parseLinearization(info.IsLinearized)]); - this.#fieldData = Object.freeze({ - fileName, - fileSize, - title: info.Title, - author: info.Author, - subject: info.Subject, - keywords: info.Keywords, - creationDate, - modificationDate, - creator: info.Creator, - producer: info.Producer, - version: info.PDFFormatVersion, - pageCount: this.pdfDocument.numPages, - pageSize, - linearized: isLinearized, - _currentPageNumber: currentPageNumber, - _pagesRotation: pagesRotation - }); - this.#updateUI(); - const { - length - } = await this.pdfDocument.getDownloadInfo(); - if (contentLength === length) { - return; + this.windowElement = null; + this.pendingrAF = null; + this.pendingElements.clear(); + return true; } - const data = Object.assign(Object.create(null), this.#fieldData); - data.fileSize = await this.#parseFileSize(length); - this.#fieldData = Object.freeze(data); - this.#updateUI(); + this.resumeObserving(); + return false; } - async close() { - this.overlayManager.close(this.dialog); + translateRoots() { + const roots = Array.from(this.roots); + return Promise.all(roots.map(root => this.translateFragment(root))); } - setDocument(pdfDocument) { - if (this.pdfDocument) { - this.#reset(); - this.#updateUI(); - } - if (!pdfDocument) { + pauseObserving() { + if (!this.mutationObserver) { return; } - this.pdfDocument = pdfDocument; - this._dataAvailableCapability.resolve(); - } - #reset() { - this.pdfDocument = null; - this.#fieldData = null; - this._dataAvailableCapability = Promise.withResolvers(); - this._currentPageNumber = 1; - this._pagesRotation = 0; + this.translateMutations(this.mutationObserver.takeRecords()); + this.mutationObserver.disconnect(); } - #updateUI() { - if (this.#fieldData && this.overlayManager.active !== this.dialog) { + resumeObserving() { + if (!this.mutationObserver) { return; } - for (const id in this.fields) { - const content = this.#fieldData?.[id]; - this.fields[id].textContent = content || content === 0 ? content : "-"; + for (const root of this.roots) { + this.mutationObserver.observe(root, this.observerConfig); } } - async #parseFileSize(b = 0) { - const kb = b / 1024, - mb = kb / 1024; - return kb ? this.l10n.get(mb >= 1 ? "pdfjs-document-properties-size-mb" : "pdfjs-document-properties-size-kb", { - mb, - kb, - b - }) : undefined; - } - async #parsePageSize(pageSizeInches, pagesRotation) { - if (!pageSizeInches) { - return undefined; - } - if (pagesRotation % 180 !== 0) { - pageSizeInches = { - width: pageSizeInches.height, - height: pageSizeInches.width - }; + translateMutations(mutations) { + for (const mutation of mutations) { + switch (mutation.type) { + case "attributes": + if (mutation.target.hasAttribute("data-l10n-id")) { + this.pendingElements.add(mutation.target); + } + break; + case "childList": + for (const addedNode of mutation.addedNodes) { + if (addedNode.nodeType === addedNode.ELEMENT_NODE) { + if (addedNode.childElementCount) { + for (const element of this.getTranslatables(addedNode)) { + this.pendingElements.add(element); + } + } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) { + this.pendingElements.add(addedNode); + } + } + } + break; + } } - const isPortrait = isPortraitOrientation(pageSizeInches), - nonMetric = NON_METRIC_LOCALES.includes(this.l10n.getLanguage()); - let sizeInches = { - width: Math.round(pageSizeInches.width * 100) / 100, - height: Math.round(pageSizeInches.height * 100) / 100 - }; - let sizeMillimeters = { - width: Math.round(pageSizeInches.width * 25.4 * 10) / 10, - height: Math.round(pageSizeInches.height * 25.4 * 10) / 10 - }; - let nameId = getPageName(sizeInches, isPortrait, US_PAGE_NAMES) || getPageName(sizeMillimeters, isPortrait, METRIC_PAGE_NAMES); - if (!nameId && !(Number.isInteger(sizeMillimeters.width) && Number.isInteger(sizeMillimeters.height))) { - const exactMillimeters = { - width: pageSizeInches.width * 25.4, - height: pageSizeInches.height * 25.4 - }; - const intMillimeters = { - width: Math.round(sizeMillimeters.width), - height: Math.round(sizeMillimeters.height) - }; - if (Math.abs(exactMillimeters.width - intMillimeters.width) < 0.1 && Math.abs(exactMillimeters.height - intMillimeters.height) < 0.1) { - nameId = getPageName(intMillimeters, isPortrait, METRIC_PAGE_NAMES); - if (nameId) { - sizeInches = { - width: Math.round(intMillimeters.width / 25.4 * 100) / 100, - height: Math.round(intMillimeters.height / 25.4 * 100) / 100 - }; - sizeMillimeters = intMillimeters; - } + if (this.pendingElements.size > 0) { + if (this.pendingrAF === null) { + this.pendingrAF = this.windowElement.requestAnimationFrame(() => { + this.translateElements(Array.from(this.pendingElements)); + this.pendingElements.clear(); + this.pendingrAF = null; + }); } } - const [{ - width, - height - }, unit, name, orientation] = await Promise.all([nonMetric ? sizeInches : sizeMillimeters, this.l10n.get(nonMetric ? "pdfjs-document-properties-page-size-unit-inches" : "pdfjs-document-properties-page-size-unit-millimeters"), nameId && this.l10n.get(nameId), this.l10n.get(isPortrait ? "pdfjs-document-properties-page-size-orientation-portrait" : "pdfjs-document-properties-page-size-orientation-landscape")]); - return this.l10n.get(name ? "pdfjs-document-properties-page-size-dimension-name-string" : "pdfjs-document-properties-page-size-dimension-string", { - width, - height, - unit, - name, - orientation - }); } - async #parseDate(inputDate) { - const dateObj = PDFDateString.toDateObject(inputDate); - return dateObj ? this.l10n.get("pdfjs-document-properties-date-time-string", { - dateObj: dateObj.valueOf() - }) : undefined; + translateFragment(frag) { + return this.translateElements(this.getTranslatables(frag)); } - #parseLinearization(isLinearized) { - return this.l10n.get(isLinearized ? "pdfjs-document-properties-linearized-yes" : "pdfjs-document-properties-linearized-no"); + async translateElements(elements) { + if (!elements.length) { + return undefined; + } + const keys = elements.map(this.getKeysForElement); + const translations = await this.formatMessages(keys); + return this.applyTranslations(elements, translations); } -} - -;// ./web/pdf_find_utils.js -const CharacterType = { - SPACE: 0, - ALPHA_LETTER: 1, - PUNCT: 2, - HAN_LETTER: 3, - KATAKANA_LETTER: 4, - HIRAGANA_LETTER: 5, - HALFWIDTH_KATAKANA_LETTER: 6, - THAI_LETTER: 7 -}; -function isAlphabeticalScript(charCode) { - return charCode < 0x2e80; -} -function isAscii(charCode) { - return (charCode & 0xff80) === 0; -} -function isAsciiAlpha(charCode) { - return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; -} -function isAsciiDigit(charCode) { - return charCode >= 0x30 && charCode <= 0x39; -} -function isAsciiSpace(charCode) { - return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; -} -function isHan(charCode) { - return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; -} -function isKatakana(charCode) { - return charCode >= 0x30a0 && charCode <= 0x30ff; -} -function isHiragana(charCode) { - return charCode >= 0x3040 && charCode <= 0x309f; -} -function isHalfwidthKatakana(charCode) { - return charCode >= 0xff60 && charCode <= 0xff9f; -} -function isThai(charCode) { - return (charCode & 0xff80) === 0x0e00; -} -function getCharacterType(charCode) { - if (isAlphabeticalScript(charCode)) { - if (isAscii(charCode)) { - if (isAsciiSpace(charCode)) { - return CharacterType.SPACE; - } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { - return CharacterType.ALPHA_LETTER; + applyTranslations(elements, translations) { + this.pauseObserving(); + for (let i = 0; i < elements.length; i++) { + if (translations[i] !== undefined) { + translateElement(elements[i], translations[i]); } - return CharacterType.PUNCT; - } else if (isThai(charCode)) { - return CharacterType.THAI_LETTER; - } else if (charCode === 0xa0) { - return CharacterType.SPACE; } - return CharacterType.ALPHA_LETTER; + this.resumeObserving(); } - if (isHan(charCode)) { - return CharacterType.HAN_LETTER; - } else if (isKatakana(charCode)) { - return CharacterType.KATAKANA_LETTER; - } else if (isHiragana(charCode)) { - return CharacterType.HIRAGANA_LETTER; - } else if (isHalfwidthKatakana(charCode)) { - return CharacterType.HALFWIDTH_KATAKANA_LETTER; + getTranslatables(element) { + const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY)); + if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) { + nodes.push(element); + } + return nodes; + } + getKeysForElement(element) { + return { + id: element.getAttribute(L10NID_ATTR_NAME), + args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) + }; } - return CharacterType.ALPHA_LETTER; -} -let NormalizeWithNFKC; -function getNormalizeWithNFKC() { - NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`; - return NormalizeWithNFKC; } - -;// ./web/pdf_find_controller.js +;// ./node_modules/@fluent/dom/esm/index.js -const FindState = { - FOUND: 0, - NOT_FOUND: 1, - WRAPPED: 2, - PENDING: 3 -}; -const FIND_TIMEOUT = 250; -const MATCH_SCROLL_OFFSET_TOP = -50; -const MATCH_SCROLL_OFFSET_LEFT = -400; -const CHARACTERS_TO_NORMALIZE = { - "\u2010": "-", - "\u2018": "'", - "\u2019": "'", - "\u201A": "'", - "\u201B": "'", - "\u201C": '"', - "\u201D": '"', - "\u201E": '"', - "\u201F": '"', - "\u00BC": "1/4", - "\u00BD": "1/2", - "\u00BE": "3/4" -}; -const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]); -let DIACRITICS_EXCEPTION_STR; -const DIACRITICS_REG_EXP = /\p{M}+/gu; -const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; -const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; -const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; -const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; -const SYLLABLES_LENGTHS = new Map(); -const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; -const NFKC_CHARS_TO_NORMALIZE = new Map(); -let noSyllablesRegExp = null; -let withSyllablesRegExp = null; -function normalize(text) { - const syllablePositions = []; - let m; - while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { - let { - index - } = m; - for (const char of m[0]) { - let len = SYLLABLES_LENGTHS.get(char); - if (!len) { - len = char.normalize("NFD").length; - SYLLABLES_LENGTHS.set(char, len); - } - syllablePositions.push([len, index++]); - } +;// ./web/l10n.js +class L10n { + #dir; + #elements; + #lang; + #l10n; + constructor({ + lang, + isRTL + }, l10n = null) { + this.#lang = L10n.#fixupLangCode(lang); + this.#l10n = l10n; + this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr"; } - let normalizationRegex; - if (syllablePositions.length === 0 && noSyllablesRegExp) { - normalizationRegex = noSyllablesRegExp; - } else if (syllablePositions.length > 0 && withSyllablesRegExp) { - normalizationRegex = withSyllablesRegExp; - } else { - const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); - const toNormalizeWithNFKC = getNormalizeWithNFKC(); - const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])"; - const HKDiacritics = "(?:\u3099|\u309A)"; - const CompoundWord = "\\p{Ll}-\\n\\p{Lu}"; - const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(${CompoundWord})|(\\S-\\n)|(${CJK}\\n)|(\\n)`; - if (syllablePositions.length === 0) { - normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); - } else { - normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); + _setL10n(l10n) { + this.#l10n = l10n; + } + getLanguage() { + return this.#lang; + } + getDirection() { + return this.#dir; + } + async get(ids, args = null, fallback) { + if (Array.isArray(ids)) { + ids = ids.map(id => ({ + id + })); + const messages = await this.#l10n.formatMessages(ids); + return messages.map(message => message.value); } + const messages = await this.#l10n.formatMessages([{ + id: ids, + args + }]); + return messages[0]?.value || fallback; } - const rawDiacriticsPositions = []; - while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { - rawDiacriticsPositions.push([m[0].length, m.index]); + async translate(element) { + (this.#elements ||= new Set()).add(element); + try { + this.#l10n.connectRoot(element); + await this.#l10n.translateRoots(); + } catch {} } - let normalized = text.normalize("NFD"); - const positions = [0, 0]; - let rawDiacriticsIndex = 0; - let syllableIndex = 0; - let shift = 0; - let shiftOrigin = 0; - let eol = 0; - let hasDiacritics = false; - normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, p9, i) => { - i -= shiftOrigin; - if (p1) { - const replacement = CHARACTERS_TO_NORMALIZE[p1]; - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); - } - shift -= jj - 1; - return replacement; + async translateOnce(element) { + try { + await this.#l10n.translateElements([element]); + } catch (ex) { + console.error("translateOnce:", ex); } - if (p2) { - let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2); - if (!replacement) { - replacement = p2.normalize("NFKC"); - NFKC_CHARS_TO_NORMALIZE.set(p2, replacement); - } - const jj = replacement.length; - for (let j = 1; j < jj; j++) { - positions.push(i - shift + j, shift - j); + } + async destroy() { + if (this.#elements) { + for (const element of this.#elements) { + this.#l10n.disconnectRoot(element); } - shift -= jj - 1; - return replacement; + this.#elements.clear(); + this.#elements = null; } - if (p3) { - hasDiacritics = true; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - ++rawDiacriticsIndex; - } else { - positions.push(i - 1 - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; + this.#l10n.pauseObserving(); + } + pause() { + this.#l10n.pauseObserving(); + } + resume() { + this.#l10n.resumeObserving(); + } + static #fixupLangCode(langCode) { + langCode = langCode?.toLowerCase() || "en-us"; + const PARTIAL_LANG_CODES = { + en: "en-us", + es: "es-es", + fy: "fy-nl", + ga: "ga-ie", + gu: "gu-in", + hi: "hi-in", + hy: "hy-am", + nb: "nb-no", + ne: "ne-np", + nn: "nn-no", + pa: "pa-in", + pt: "pt-pt", + sv: "sv-se", + zh: "zh-cn" + }; + return PARTIAL_LANG_CODES[langCode] || langCode; + } + static #isRTL(lang) { + const shortCode = lang.split("-", 1)[0]; + return ["ar", "he", "fa", "ps", "ur"].includes(shortCode); + } +} +const GenericL10n = null; + +;// ./web/genericl10n.js + + + + +function createBundle(lang, text) { + const resource = new FluentResource(text); + const bundle = new FluentBundle(lang); + const errors = bundle.addResource(resource); + if (errors.length) { + console.error("L10n errors", errors); + } + return bundle; +} +class genericl10n_GenericL10n extends L10n { + constructor(lang) { + super({ + lang + }); + const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage()); + this._setL10n(new DOMLocalization([], generateBundles)); + } + static async *#generateBundles(defaultLang, baseLang) { + const { + baseURL, + paths + } = await this.#getPaths(); + const langs = [baseLang]; + if (defaultLang !== baseLang) { + const shortLang = baseLang.split("-", 1)[0]; + if (shortLang !== baseLang) { + langs.push(shortLang); } - positions.push(i - shift + 1, shift); - shiftOrigin += 1; - eol += 1; - return p3.charAt(0); + langs.push(defaultLang); } - if (p4) { - const hasTrailingDashEOL = p4.endsWith("\n"); - const len = hasTrailingDashEOL ? p4.length - 2 : p4.length; - hasDiacritics = true; - let jj = len; - if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { - jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; - ++rawDiacriticsIndex; - } - for (let j = 1; j <= jj; j++) { - positions.push(i - 1 - shift + j, shift - j); - } - shift -= jj; - shiftOrigin += jj; - if (hasTrailingDashEOL) { - i += len - 1; - positions.push(i - shift + 1, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p4.slice(0, len); + for (const lang of langs) { + const bundle = await this.#createBundle(lang, baseURL, paths); + if (bundle) { + yield bundle; + } else if (lang === "en-us") { + yield this.#createBundleFallback(lang); } - return p4; - } - if (p5) { - shiftOrigin += 1; - eol += 1; - return p5.replace("\n", ""); - } - if (p6) { - const len = p6.length - 2; - positions.push(i - shift + len, 1 + shift); - shift += 1; - shiftOrigin += 1; - eol += 1; - return p6.slice(0, -2); - } - if (p7) { - const len = p7.length - 1; - positions.push(i - shift + len, shift); - shiftOrigin += 1; - eol += 1; - return p7.slice(0, -1); - } - if (p8) { - positions.push(i - shift + 1, shift - 1); - shift -= 1; - shiftOrigin += 1; - eol += 1; - return " "; } - if (i + eol === syllablePositions[syllableIndex]?.[1]) { - const newCharLen = syllablePositions[syllableIndex][0] - 1; - ++syllableIndex; - for (let j = 1; j <= newCharLen; j++) { - positions.push(i - (shift - j), shift - j); - } - shift -= newCharLen; - shiftOrigin += newCharLen; + } + static async #createBundle(lang, baseURL, paths) { + const path = paths[lang]; + if (!path) { + return null; } - return p9; - }); - positions.push(normalized.length, shift); - const starts = new Uint32Array(positions.length >> 1); - const shifts = new Int32Array(positions.length >> 1); - for (let i = 0, ii = positions.length; i < ii; i += 2) { - starts[i >> 1] = positions[i]; - shifts[i >> 1] = positions[i + 1]; + const url = new URL(path, baseURL); + const text = await fetchData(url, "text"); + return createBundle(lang, text); } - return [normalized, [starts, shifts], hasDiacritics]; -} -function getOriginalIndex(diffs, pos, len) { - if (!diffs) { - return [pos, len]; + static async #getPaths() { + try { + const { + href + } = document.querySelector(`link[type="application/l10n"]`); + const paths = await fetchData(href, "json"); + return { + baseURL: href.replace(/[^/]*$/, "") || "./", + paths + }; + } catch {} + return { + baseURL: "./", + paths: Object.create(null) + }; } - const [starts, shifts] = diffs; - const start = pos; - const end = pos + len - 1; - let i = binarySearchFirstItem(starts, x => x >= start); - if (starts[i] > start) { - --i; + static async *#generateBundlesFallback(lang) { + yield this.#createBundleFallback(lang); } - let j = binarySearchFirstItem(starts, x => x >= end, i); - if (starts[j] > end) { - --j; + static async #createBundleFallback(lang) { + const text = "pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties\u2026\npdfjs-document-properties-button-label = Document Properties\u2026\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } \xD7 { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } \xD7 { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing\u2026\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document\u2026\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing\u2026\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can\u2019t see the image or when it doesn\u2019t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, \u201CA young man sits down at a table to eat a meal\u201D\npdfjs-editor-resizer-top-left =\n .aria-label = Top left corner \u2014 resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle \u2014 resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner \u2014 resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right \u2014 resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner \u2014 resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle \u2014 resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner \u2014 resize\npdfjs-editor-resizer-middle-left =\n .aria-label = Middle left \u2014 resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here\u2026\npdfjs-editor-new-alt-text-description = Short description for people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn\u2019t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading\u2026\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close"; + return createBundle(lang, text); } - const oldStart = start + shifts[i]; - const oldEnd = end + shifts[j]; - const oldLen = oldEnd + 1 - oldStart; - return [oldStart, oldLen]; } -class PDFFindController { - #state = null; - #updateMatchesCountOnProgress = true; - #visitedPagesCount = 0; + +;// ./web/pdf_history.js + + +const HASH_CHANGE_TIMEOUT = 1000; +const POSITION_UPDATED_THRESHOLD = 50; +const UPDATE_VIEWAREA_TIMEOUT = 1000; +function getCurrentHash() { + return document.location.hash; +} +class PDFHistory { + #eventAbortController = null; constructor({ linkService, - eventBus, - updateMatchesCountOnProgress = true + eventBus }) { - this._linkService = linkService; - this._eventBus = eventBus; - this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress; - this.onIsPageVisible = null; - this.#reset(); - eventBus._on("find", this.#onFind.bind(this)); - eventBus._on("findbarclose", this.#onFindBarClose.bind(this)); - } - get highlightMatches() { - return this._highlightMatches; - } - get pageMatches() { - return this._pageMatches; - } - get pageMatchesLength() { - return this._pageMatchesLength; - } - get selected() { - return this._selected; - } - get state() { - return this.#state; + this.linkService = linkService; + this.eventBus = eventBus; + this._initialized = false; + this._fingerprint = ""; + this.reset(); + this.eventBus._on("pagesinit", () => { + this._isPagesLoaded = false; + this.eventBus._on("pagesloaded", evt => { + this._isPagesLoaded = !!evt.pagesCount; + }, { + once: true + }); + }); } - setDocument(pdfDocument) { - if (this._pdfDocument) { - this.#reset(); - } - if (!pdfDocument) { + initialize({ + fingerprint, + resetHistory = false, + updateUrl = false + }) { + if (!fingerprint || typeof fingerprint !== "string") { + console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); return; } - this._pdfDocument = pdfDocument; - this._firstPageCapability.resolve(); - } - #onFind(state) { - if (!state) { + if (this._initialized) { + this.reset(); + } + const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; + this._fingerprint = fingerprint; + this._updateUrl = updateUrl === true; + this._initialized = true; + this.#bindEvents(); + const state = window.history.state; + this._popStateInProgress = false; + this._blockHashChange = 0; + this._currentHash = getCurrentHash(); + this._numPositionUpdates = 0; + this._uid = this._maxUid = 0; + this._destination = null; + this._position = null; + if (!this.#isValidState(state, true) || resetHistory) { + const { + hash, + page, + rotation + } = this.#parseCurrentHash(true); + if (!hash || reInitialized || resetHistory) { + this.#pushOrReplaceState(null, true); + return; + } + this.#pushOrReplaceState({ + hash, + page, + rotation + }, true); return; } - const pdfDocument = this._pdfDocument; - const { - type - } = state; - if (this.#state === null || this.#shouldDirtyMatch(state)) { - this._dirtyMatch = true; + const destination = state.destination; + this.#updateInternalState(destination, state.uid, true); + if (destination.rotation !== undefined) { + this._initialRotation = destination.rotation; } - this.#state = state; - if (type !== "highlightallchange") { - this.#updateUIState(FindState.PENDING); + if (destination.dest) { + this._initialBookmark = JSON.stringify(destination.dest); + this._destination.page = null; + } else if (destination.hash) { + this._initialBookmark = destination.hash; + } else if (destination.page) { + this._initialBookmark = `page=${destination.page}`; } - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { - return; - } - this.#extractText(); - const findbarClosed = !this._highlightMatches; - const pendingTimeout = !!this._findTimeout; - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (!type) { - this._findTimeout = setTimeout(() => { - this.#nextMatch(); - this._findTimeout = null; - }, FIND_TIMEOUT); - } else if (this._dirtyMatch) { - this.#nextMatch(); - } else if (type === "again") { - this.#nextMatch(); - if (findbarClosed && this.#state.highlightAll) { - this.#updateAllPages(); - } - } else if (type === "highlightallchange") { - if (pendingTimeout) { - this.#nextMatch(); - } else { - this._highlightMatches = true; - } - this.#updateAllPages(); - } else { - this.#nextMatch(); - } - }); } - scrollMatchIntoView({ - element = null, - selectedLeft = 0, - pageIndex = -1, - matchIndex = -1 + reset() { + if (this._initialized) { + this.#pageHide(); + this._initialized = false; + this.#unbindEvents(); + } + if (this._updateViewareaTimeout) { + clearTimeout(this._updateViewareaTimeout); + this._updateViewareaTimeout = null; + } + this._initialBookmark = null; + this._initialRotation = null; + } + push({ + namedDest = null, + explicitDest, + pageNumber }) { - if (!this._scrollMatches || !element) { + if (!this._initialized) { return; - } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { + } + if (namedDest && typeof namedDest !== "string") { + console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); return; - } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { + } else if (!Array.isArray(explicitDest)) { + console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); return; - } - this._scrollMatches = false; - const spot = { - top: MATCH_SCROLL_OFFSET_TOP, - left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT - }; - scrollIntoView(element, spot, true); - } - #reset() { - this._highlightMatches = false; - this._scrollMatches = false; - this._pdfDocument = null; - this._pageMatches = []; - this._pageMatchesLength = []; - this.#visitedPagesCount = 0; - this.#state = null; - this._selected = { - pageIdx: -1, - matchIdx: -1 - }; - this._offset = { - pageIdx: null, - matchIdx: null, - wrapped: false - }; - this._extractTextPromises = []; - this._pageContents = []; - this._pageDiffs = []; - this._hasDiacritics = []; - this._matchesCountTotal = 0; - this._pagesToSearch = null; - this._pendingFindMatches = new Set(); - this._resumePageIdx = null; - this._dirtyMatch = false; - clearTimeout(this._findTimeout); - this._findTimeout = null; - this._firstPageCapability = Promise.withResolvers(); - } - get #query() { - const { - query - } = this.#state; - if (typeof query === "string") { - if (query !== this._rawQuery) { - this._rawQuery = query; - [this._normalizedQuery] = normalize(query); + } else if (!this.#isValidPage(pageNumber)) { + if (pageNumber !== null || this._destination) { + console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); + return; } - return this._normalizedQuery; } - return (query || []).filter(q => !!q).map(q => normalize(q)[0]); - } - #shouldDirtyMatch(state) { - const newQuery = state.query, - prevQuery = this.#state.query; - const newType = typeof newQuery, - prevType = typeof prevQuery; - if (newType !== prevType) { - return true; + const hash = namedDest || JSON.stringify(explicitDest); + if (!hash) { + return; } - if (newType === "string") { - if (newQuery !== prevQuery) { - return true; + let forceReplace = false; + if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { + if (this._destination.page) { + return; } - } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) { - return true; + forceReplace = true; } - switch (state.type) { - case "again": - const pageNumber = this._selected.pageIdx + 1; - const linkService = this._linkService; - return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true); - case "highlightallchange": - return false; + if (this._popStateInProgress && !forceReplace) { + return; } - return true; - } - #isEntireWord(content, startIdx, length) { - let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP); - if (match) { - const first = content.charCodeAt(startIdx); - const limit = match[1].charCodeAt(0); - if (getCharacterType(first) === getCharacterType(limit)) { - return false; - } - } - match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP); - if (match) { - const last = content.charCodeAt(startIdx + length - 1); - const limit = match[1].charCodeAt(0); - if (getCharacterType(last) === getCharacterType(limit)) { - return false; - } + this.#pushOrReplaceState({ + dest: explicitDest, + hash, + page: pageNumber, + rotation: this.linkService.rotation + }, forceReplace); + if (!this._popStateInProgress) { + this._popStateInProgress = true; + Promise.resolve().then(() => { + this._popStateInProgress = false; + }); } - return true; } - #convertToRegExpString(query, hasDiacritics) { - const { - matchDiacritics - } = this.#state; - let isUnicode = false; - query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => { - if (p1) { - return `[ ]*\\${p1}[ ]*`; - } - if (p2) { - return `[ ]*${p2}[ ]*`; - } - if (p3) { - return "[ ]+"; - } - if (matchDiacritics) { - return p4 || p5; - } - if (p4) { - return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : ""; - } - if (hasDiacritics) { - isUnicode = true; - return `${p5}\\p{M}*`; - } - return p5; - }); - const trailingSpaces = "[ ]*"; - if (query.endsWith(trailingSpaces)) { - query = query.slice(0, query.length - trailingSpaces.length); - } - if (matchDiacritics) { - if (hasDiacritics) { - DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION); - isUnicode = true; - query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`; - } + pushPage(pageNumber) { + if (!this._initialized) { + return; } - return [isUnicode, query]; - } - #calculateMatch(pageIndex) { - const query = this.#query; - if (query.length === 0) { + if (!this.#isValidPage(pageNumber)) { + console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); return; } - const pageContent = this._pageContents[pageIndex]; - const matcherResult = this.match(query, pageContent, pageIndex); - const matches = this._pageMatches[pageIndex] = []; - const matchesLength = this._pageMatchesLength[pageIndex] = []; - const diffs = this._pageDiffs[pageIndex]; - matcherResult?.forEach(({ - index, - length - }) => { - const [matchPos, matchLen] = getOriginalIndex(diffs, index, length); - if (matchLen) { - matches.push(matchPos); - matchesLength.push(matchLen); - } - }); - if (this.#state.highlightAll) { - this.#updatePage(pageIndex); + if (this._destination?.page === pageNumber) { + return; } - if (this._resumePageIdx === pageIndex) { - this._resumePageIdx = null; - this.#nextPageMatch(); + if (this._popStateInProgress) { + return; } - const pageMatchesCount = matches.length; - this._matchesCountTotal += pageMatchesCount; - if (this.#updateMatchesCountOnProgress) { - if (pageMatchesCount > 0) { - this.#updateUIResultsCount(); - } - } else if (++this.#visitedPagesCount === this._linkService.pagesCount) { - this.#updateUIResultsCount(); + this.#pushOrReplaceState({ + dest: null, + hash: `page=${pageNumber}`, + page: pageNumber, + rotation: this.linkService.rotation + }); + if (!this._popStateInProgress) { + this._popStateInProgress = true; + Promise.resolve().then(() => { + this._popStateInProgress = false; + }); } } - match(query, pageContent, pageIndex) { - const hasDiacritics = this._hasDiacritics[pageIndex]; - let isUnicode = false; - if (typeof query === "string") { - [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics); - } else { - query = query.sort().reverse().map(q => { - const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics); - isUnicode ||= isUnicodePart; - return `(${queryPart})`; - }).join("|"); + pushCurrentPosition() { + if (!this._initialized || this._popStateInProgress) { + return; } - if (!query) { - return undefined; + this.#tryPushCurrentPosition(); + } + back() { + if (!this._initialized || this._popStateInProgress) { + return; } - const { - caseSensitive, - entireWord - } = this.#state; - const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`; - query = new RegExp(query, flags); - const matches = []; - let match; - while ((match = query.exec(pageContent)) !== null) { - if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) { - continue; - } - matches.push({ - index: match.index, - length: match[0].length - }); + const state = window.history.state; + if (this.#isValidState(state) && state.uid > 0) { + window.history.back(); } - return matches; } - #extractText() { - if (this._extractTextPromises.length > 0) { + forward() { + if (!this._initialized || this._popStateInProgress) { return; } - let deferred = Promise.resolve(); - const textOptions = { - disableNormalization: true - }; - for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { - const { - promise, - resolve - } = Promise.withResolvers(); - this._extractTextPromises[i] = promise; - deferred = deferred.then(() => { - return this._pdfDocument.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => { - const strBuf = []; - for (const textItem of textContent.items) { - strBuf.push(textItem.str); - if (textItem.hasEOL) { - strBuf.push("\n"); - } - } - [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join("")); - resolve(); - }, reason => { - console.error(`Unable to get text content for page ${i + 1}`, reason); - this._pageContents[i] = ""; - this._pageDiffs[i] = null; - this._hasDiacritics[i] = false; - resolve(); - }); - }); + const state = window.history.state; + if (this.#isValidState(state) && state.uid < this._maxUid) { + window.history.forward(); } } - #updatePage(index) { - if (this._scrollMatches && this._selected.pageIdx === index) { - this._linkService.page = index + 1; - } - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: index - }); + get popStateInProgress() { + return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); } - #updateAllPages() { - this._eventBus.dispatch("updatetextlayermatches", { - source: this, - pageIndex: -1 - }); + get initialBookmark() { + return this._initialized ? this._initialBookmark : null; } - #nextMatch() { - const previous = this.#state.findPrevious; - const currentPageIndex = this._linkService.page - 1; - const numPages = this._linkService.pagesCount; - this._highlightMatches = true; - if (this._dirtyMatch) { - this._dirtyMatch = false; - this._selected.pageIdx = this._selected.matchIdx = -1; - this._offset.pageIdx = currentPageIndex; - this._offset.matchIdx = null; - this._offset.wrapped = false; - this._resumePageIdx = null; - this._pageMatches.length = 0; - this._pageMatchesLength.length = 0; - this.#visitedPagesCount = 0; - this._matchesCountTotal = 0; - this.#updateAllPages(); - for (let i = 0; i < numPages; i++) { - if (this._pendingFindMatches.has(i)) { - continue; - } - this._pendingFindMatches.add(i); - this._extractTextPromises[i].then(() => { - this._pendingFindMatches.delete(i); - this.#calculateMatch(i); - }); + get initialRotation() { + return this._initialized ? this._initialRotation : null; + } + #pushOrReplaceState(destination, forceReplace = false) { + const shouldReplace = forceReplace || !this._destination; + const newState = { + fingerprint: this._fingerprint, + uid: shouldReplace ? this._uid : this._uid + 1, + destination + }; + this.#updateInternalState(destination, newState.uid); + let newUrl; + if (this._updateUrl && destination?.hash) { + const baseUrl = document.location.href.split("#", 1)[0]; + if (!baseUrl.startsWith("file://")) { + newUrl = `${baseUrl}#${destination.hash}`; } } - const query = this.#query; - if (query.length === 0) { - this.#updateUIState(FindState.FOUND); - return; + if (shouldReplace) { + window.history.replaceState(newState, "", newUrl); + } else { + window.history.pushState(newState, "", newUrl); } - if (this._resumePageIdx) { - return; - } - const offset = this._offset; - this._pagesToSearch = numPages; - if (offset.matchIdx !== null) { - const numPageMatches = this._pageMatches[offset.pageIdx].length; - if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { - offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; - this.#updateMatch(true); - return; - } - this.#advanceOffsetPage(previous); - } - this.#nextPageMatch(); } - #matchesReady(matches) { - const offset = this._offset; - const numMatches = matches.length; - const previous = this.#state.findPrevious; - if (numMatches) { - offset.matchIdx = previous ? numMatches - 1 : 0; - this.#updateMatch(true); - return true; + #tryPushCurrentPosition(temporary = false) { + if (!this._position) { + return; } - this.#advanceOffsetPage(previous); - if (offset.wrapped) { - offset.matchIdx = null; - if (this._pagesToSearch < 0) { - this.#updateMatch(false); - return true; - } + let position = this._position; + if (temporary) { + position = Object.assign(Object.create(null), this._position); + position.temporary = true; } - return false; - } - #nextPageMatch() { - if (this._resumePageIdx !== null) { - console.error("There can only be one pending page."); + if (!this._destination) { + this.#pushOrReplaceState(position); + return; } - let matches = null; - do { - const pageIdx = this._offset.pageIdx; - matches = this._pageMatches[pageIdx]; - if (!matches) { - this._resumePageIdx = pageIdx; - break; - } - } while (!this.#matchesReady(matches)); - } - #advanceOffsetPage(previous) { - const offset = this._offset; - const numPages = this._linkService.pagesCount; - offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; - offset.matchIdx = null; - this._pagesToSearch--; - if (offset.pageIdx >= numPages || offset.pageIdx < 0) { - offset.pageIdx = previous ? numPages - 1 : 0; - offset.wrapped = true; + if (this._destination.temporary) { + this.#pushOrReplaceState(position, true); + return; } - } - #updateMatch(found = false) { - let state = FindState.NOT_FOUND; - const wrapped = this._offset.wrapped; - this._offset.wrapped = false; - if (found) { - const previousPage = this._selected.pageIdx; - this._selected.pageIdx = this._offset.pageIdx; - this._selected.matchIdx = this._offset.matchIdx; - state = wrapped ? FindState.WRAPPED : FindState.FOUND; - if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { - this.#updatePage(previousPage); - } + if (this._destination.hash === position.hash) { + return; } - this.#updateUIState(state, this.#state.findPrevious); - if (this._selected.pageIdx !== -1) { - this._scrollMatches = true; - this.#updatePage(this._selected.pageIdx); + if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { + return; } - } - #onFindBarClose(evt) { - const pdfDocument = this._pdfDocument; - this._firstPageCapability.promise.then(() => { - if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { + let forceReplace = false; + if (this._destination.page >= position.first && this._destination.page <= position.page) { + if (this._destination.dest !== undefined || !this._destination.first) { return; } - if (this._findTimeout) { - clearTimeout(this._findTimeout); - this._findTimeout = null; - } - if (this._resumePageIdx) { - this._resumePageIdx = null; - this._dirtyMatch = true; - } - this.#updateUIState(FindState.FOUND); - this._highlightMatches = false; - this.#updateAllPages(); - }); - } - #requestMatchesCount() { - const { - pageIdx, - matchIdx - } = this._selected; - let current = 0, - total = this._matchesCountTotal; - if (matchIdx !== -1) { - for (let i = 0; i < pageIdx; i++) { - current += this._pageMatches[i]?.length || 0; - } - current += matchIdx + 1; - } - if (current < 1 || current > total) { - current = total = 0; + forceReplace = true; } - return { - current, - total - }; + this.#pushOrReplaceState(position, forceReplace); } - #updateUIResultsCount() { - this._eventBus.dispatch("updatefindmatchescount", { - source: this, - matchesCount: this.#requestMatchesCount() - }); + #isValidPage(val) { + return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; } - #updateUIState(state, previous = false) { - if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) { - return; + #isValidState(state, checkReload = false) { + if (!state) { + return false; } - this._eventBus.dispatch("updatefindcontrolstate", { - source: this, - state, - previous, - entireWord: this.#state?.entireWord ?? null, - matchesCount: this.#requestMatchesCount(), - rawQuery: this.#state?.query ?? null - }); - } -} - -;// ./web/pdf_find_bar.js - - -const MATCHES_COUNT_LIMIT = 1000; -class PDFFindBar { - #mainContainer; - #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); - constructor(options, mainContainer, eventBus) { - this.opened = false; - this.bar = options.bar; - this.toggleButton = options.toggleButton; - this.findField = options.findField; - this.highlightAll = options.highlightAllCheckbox; - this.caseSensitive = options.caseSensitiveCheckbox; - this.matchDiacritics = options.matchDiacriticsCheckbox; - this.entireWord = options.entireWordCheckbox; - this.findMsg = options.findMsg; - this.findResultsCount = options.findResultsCount; - this.findPreviousButton = options.findPreviousButton; - this.findNextButton = options.findNextButton; - this.eventBus = eventBus; - this.#mainContainer = mainContainer; - const checkedInputs = new Map([[this.highlightAll, "highlightallchange"], [this.caseSensitive, "casesensitivitychange"], [this.entireWord, "entirewordchange"], [this.matchDiacritics, "diacriticmatchingchange"]]); - this.toggleButton.addEventListener("click", () => { - this.toggle(); - }); - this.findField.addEventListener("input", () => { - this.dispatchEvent(""); - }); - this.bar.addEventListener("keydown", ({ - keyCode, - shiftKey, - target - }) => { - switch (keyCode) { - case 13: - if (target === this.findField) { - this.dispatchEvent("again", shiftKey); - } else if (checkedInputs.has(target)) { - target.checked = !target.checked; - this.dispatchEvent(checkedInputs.get(target)); - } - break; - case 27: - this.close(); - break; + if (state.fingerprint !== this._fingerprint) { + if (checkReload) { + if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { + return false; + } + const [perfEntry] = performance.getEntriesByType("navigation"); + if (perfEntry?.type !== "reload") { + return false; + } + } else { + return false; } - }); - this.findPreviousButton.addEventListener("click", () => { - this.dispatchEvent("again", true); - }); - this.findNextButton.addEventListener("click", () => { - this.dispatchEvent("again", false); - }); - for (const [elem, evtName] of checkedInputs) { - elem.addEventListener("click", () => { - this.dispatchEvent(evtName); - }); } - } - reset() { - this.updateUIState(); - } - dispatchEvent(type, findPrev = false) { - this.eventBus.dispatch("find", { - source: this, - type, - query: this.findField.value, - caseSensitive: this.caseSensitive.checked, - entireWord: this.entireWord.checked, - highlightAll: this.highlightAll.checked, - findPrevious: findPrev, - matchDiacritics: this.matchDiacritics.checked - }); - } - updateUIState(state, previous, matchesCount) { - const { - findField, - findMsg - } = this; - let findMsgId = "", - status = ""; - switch (state) { - case FindState.FOUND: - break; - case FindState.PENDING: - status = "pending"; - break; - case FindState.NOT_FOUND: - findMsgId = "pdfjs-find-not-found"; - status = "notFound"; - break; - case FindState.WRAPPED: - findMsgId = previous ? "pdfjs-find-reached-top" : "pdfjs-find-reached-bottom"; - break; + if (!Number.isInteger(state.uid) || state.uid < 0) { + return false; } - findField.setAttribute("data-status", status); - findField.setAttribute("aria-invalid", state === FindState.NOT_FOUND); - findMsg.setAttribute("data-status", status); - if (findMsgId) { - findMsg.setAttribute("data-l10n-id", findMsgId); - } else { - findMsg.removeAttribute("data-l10n-id"); - findMsg.textContent = ""; + if (state.destination === null || typeof state.destination !== "object") { + return false; } - this.updateResultsCount(matchesCount); + return true; } - updateResultsCount({ - current = 0, - total = 0 - } = {}) { - const { - findResultsCount - } = this; - if (total > 0) { - const limit = MATCHES_COUNT_LIMIT; - findResultsCount.setAttribute("data-l10n-id", total > limit ? "pdfjs-find-match-count-limit" : "pdfjs-find-match-count"); - findResultsCount.setAttribute("data-l10n-args", JSON.stringify({ - limit, - current, - total - })); - } else { - findResultsCount.removeAttribute("data-l10n-id"); - findResultsCount.textContent = ""; + #updateInternalState(destination, uid, removeTemporary = false) { + if (this._updateViewareaTimeout) { + clearTimeout(this._updateViewareaTimeout); + this._updateViewareaTimeout = null; + } + if (removeTemporary && destination?.temporary) { + delete destination.temporary; } + this._destination = destination; + this._uid = uid; + this._maxUid = Math.max(this._maxUid, uid); + this._numPositionUpdates = 0; } - open() { - if (!this.opened) { - this.#resizeObserver.observe(this.#mainContainer); - this.#resizeObserver.observe(this.bar); - this.opened = true; - toggleExpandedBtn(this.toggleButton, true, this.bar); + #parseCurrentHash(checkNameddest = false) { + const hash = unescape(getCurrentHash()).substring(1); + const params = parseQueryString(hash); + const nameddest = params.get("nameddest") || ""; + let page = params.get("page") | 0; + if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) { + page = null; } - this.findField.select(); - this.findField.focus(); + return { + hash, + page, + rotation: this.linkService.rotation + }; } - close() { - if (!this.opened) { + #updateViewarea({ + location + }) { + if (this._updateViewareaTimeout) { + clearTimeout(this._updateViewareaTimeout); + this._updateViewareaTimeout = null; + } + this._position = { + hash: location.pdfOpenParams.substring(1), + page: this.linkService.page, + first: location.pageNumber, + rotation: location.rotation + }; + if (this._popStateInProgress) { return; } - this.#resizeObserver.disconnect(); - this.opened = false; - toggleExpandedBtn(this.toggleButton, false, this.bar); - this.eventBus.dispatch("findbarclose", { - source: this - }); - } - toggle() { - if (this.opened) { - this.close(); - } else { - this.open(); + if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { + this._numPositionUpdates++; } - } - #resizeObserverCallback() { - const { - bar - } = this; - bar.classList.remove("wrapContainers"); - const findbarHeight = bar.clientHeight; - const inputContainerHeight = bar.firstElementChild.clientHeight; - if (findbarHeight > inputContainerHeight) { - bar.classList.add("wrapContainers"); + if (UPDATE_VIEWAREA_TIMEOUT > 0) { + this._updateViewareaTimeout = setTimeout(() => { + if (!this._popStateInProgress) { + this.#tryPushCurrentPosition(true); + } + this._updateViewareaTimeout = null; + }, UPDATE_VIEWAREA_TIMEOUT); } } -} - -;// ./web/pdf_history.js - - -const HASH_CHANGE_TIMEOUT = 1000; -const POSITION_UPDATED_THRESHOLD = 50; -const UPDATE_VIEWAREA_TIMEOUT = 1000; -function getCurrentHash() { - return document.location.hash; -} -class PDFHistory { - #eventAbortController = null; - constructor({ - linkService, - eventBus - }) { - this.linkService = linkService; - this.eventBus = eventBus; - this._initialized = false; - this._fingerprint = ""; - this.reset(); - this.eventBus._on("pagesinit", () => { - this._isPagesLoaded = false; - this.eventBus._on("pagesloaded", evt => { - this._isPagesLoaded = !!evt.pagesCount; - }, { - once: true - }); - }); - } - initialize({ - fingerprint, - resetHistory = false, - updateUrl = false + #popState({ + state }) { - if (!fingerprint || typeof fingerprint !== "string") { - console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); - return; - } - if (this._initialized) { - this.reset(); - } - const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; - this._fingerprint = fingerprint; - this._updateUrl = updateUrl === true; - this._initialized = true; - this.#bindEvents(); - const state = window.history.state; - this._popStateInProgress = false; - this._blockHashChange = 0; - this._currentHash = getCurrentHash(); - this._numPositionUpdates = 0; - this._uid = this._maxUid = 0; - this._destination = null; - this._position = null; - if (!this.#isValidState(state, true) || resetHistory) { + const newHash = getCurrentHash(), + hashChanged = this._currentHash !== newHash; + this._currentHash = newHash; + if (!state) { + this._uid++; const { hash, page, rotation - } = this.#parseCurrentHash(true); - if (!hash || reInitialized || resetHistory) { - this.#pushOrReplaceState(null, true); - return; - } + } = this.#parseCurrentHash(); this.#pushOrReplaceState({ hash, page, @@ -6248,9118 +3922,4514 @@ class PDFHistory { }, true); return; } + if (!this.#isValidState(state)) { + return; + } + this._popStateInProgress = true; + if (hashChanged) { + this._blockHashChange++; + waitOnEventOrTimeout({ + target: window, + name: "hashchange", + delay: HASH_CHANGE_TIMEOUT + }).then(() => { + this._blockHashChange--; + }); + } const destination = state.destination; this.#updateInternalState(destination, state.uid, true); - if (destination.rotation !== undefined) { - this._initialRotation = destination.rotation; + if (isValidRotation(destination.rotation)) { + this.linkService.rotation = destination.rotation; } if (destination.dest) { - this._initialBookmark = JSON.stringify(destination.dest); - this._destination.page = null; + this.linkService.goToDestination(destination.dest); } else if (destination.hash) { - this._initialBookmark = destination.hash; + this.linkService.setHash(destination.hash); } else if (destination.page) { - this._initialBookmark = `page=${destination.page}`; + this.linkService.page = destination.page; } + Promise.resolve().then(() => { + this._popStateInProgress = false; + }); } - reset() { - if (this._initialized) { - this.#pageHide(); - this._initialized = false; - this.#unbindEvents(); - } - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; + #pageHide() { + if (!this._destination || this._destination.temporary) { + this.#tryPushCurrentPosition(); } - this._initialBookmark = null; - this._initialRotation = null; } - push({ - namedDest = null, - explicitDest, - pageNumber - }) { - if (!this._initialized) { + #bindEvents() { + if (this.#eventAbortController) { return; } - if (namedDest && typeof namedDest !== "string") { - console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); - return; - } else if (!Array.isArray(explicitDest)) { - console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); - return; - } else if (!this.#isValidPage(pageNumber)) { - if (pageNumber !== null || this._destination) { - console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); - return; - } + this.#eventAbortController = new AbortController(); + const { + signal + } = this.#eventAbortController; + this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), { + signal + }); + window.addEventListener("popstate", this.#popState.bind(this), { + signal + }); + window.addEventListener("pagehide", this.#pageHide.bind(this), { + signal + }); + } + #unbindEvents() { + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + } +} +function isDestHashesEqual(destHash, pushHash) { + if (typeof destHash !== "string" || typeof pushHash !== "string") { + return false; + } + if (destHash === pushHash) { + return true; + } + const nameddest = parseQueryString(destHash).get("nameddest"); + if (nameddest === pushHash) { + return true; + } + return false; +} +function isDestArraysEqual(firstDest, secondDest) { + function isEntryEqual(first, second) { + if (typeof first !== typeof second) { + return false; } - const hash = namedDest || JSON.stringify(explicitDest); - if (!hash) { - return; + if (Array.isArray(first) || Array.isArray(second)) { + return false; } - let forceReplace = false; - if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { - if (this._destination.page) { - return; + if (first !== null && typeof first === "object" && second !== null) { + if (Object.keys(first).length !== Object.keys(second).length) { + return false; } - forceReplace = true; - } - if (this._popStateInProgress && !forceReplace) { - return; - } - this.#pushOrReplaceState({ - dest: explicitDest, - hash, - page: pageNumber, - rotation: this.linkService.rotation - }, forceReplace); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); + for (const key in first) { + if (!isEntryEqual(first[key], second[key])) { + return false; + } + } + return true; } + return first === second || Number.isNaN(first) && Number.isNaN(second); } - pushPage(pageNumber) { - if (!this._initialized) { - return; + if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { + return false; + } + if (firstDest.length !== secondDest.length) { + return false; + } + for (let i = 0, ii = firstDest.length; i < ii; i++) { + if (!isEntryEqual(firstDest[i], secondDest[i])) { + return false; } - if (!this.#isValidPage(pageNumber)) { - console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); + } + return true; +} + +;// ./web/annotation_editor_layer_builder.js + + +class AnnotationEditorLayerBuilder { + #annotationLayer = null; + #drawLayer = null; + #onAppend = null; + #structTreeLayer = null; + #textLayer = null; + #uiManager; + constructor(options) { + this.pdfPage = options.pdfPage; + this.accessibilityManager = options.accessibilityManager; + this.l10n = options.l10n; + this.l10n ||= new genericl10n_GenericL10n(); + this.annotationEditorLayer = null; + this.div = null; + this._cancelled = false; + this.#uiManager = options.uiManager; + this.#annotationLayer = options.annotationLayer || null; + this.#textLayer = options.textLayer || null; + this.#drawLayer = options.drawLayer || null; + this.#onAppend = options.onAppend || null; + this.#structTreeLayer = options.structTreeLayer || null; + } + async render(viewport, intent = "display") { + if (intent !== "display") { return; } - if (this._destination?.page === pageNumber) { + if (this._cancelled) { return; } - if (this._popStateInProgress) { + const clonedViewport = viewport.clone({ + dontFlip: true + }); + if (this.div) { + this.annotationEditorLayer.update({ + viewport: clonedViewport + }); + this.show(); return; } - this.#pushOrReplaceState({ - dest: null, - hash: `page=${pageNumber}`, - page: pageNumber, - rotation: this.linkService.rotation + const div = this.div = document.createElement("div"); + div.className = "annotationEditorLayer"; + div.hidden = true; + div.dir = this.#uiManager.direction; + this.#onAppend?.(div); + this.annotationEditorLayer = new AnnotationEditorLayer({ + uiManager: this.#uiManager, + div, + structTreeLayer: this.#structTreeLayer, + accessibilityManager: this.accessibilityManager, + pageIndex: this.pdfPage.pageNumber - 1, + l10n: this.l10n, + viewport: clonedViewport, + annotationLayer: this.#annotationLayer, + textLayer: this.#textLayer, + drawLayer: this.#drawLayer }); - if (!this._popStateInProgress) { - this._popStateInProgress = true; - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - } - pushCurrentPosition() { - if (!this._initialized || this._popStateInProgress) { - return; - } - this.#tryPushCurrentPosition(); - } - back() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid > 0) { - window.history.back(); - } - } - forward() { - if (!this._initialized || this._popStateInProgress) { - return; - } - const state = window.history.state; - if (this.#isValidState(state) && state.uid < this._maxUid) { - window.history.forward(); - } - } - get popStateInProgress() { - return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); - } - get initialBookmark() { - return this._initialized ? this._initialBookmark : null; - } - get initialRotation() { - return this._initialized ? this._initialRotation : null; - } - #pushOrReplaceState(destination, forceReplace = false) { - const shouldReplace = forceReplace || !this._destination; - const newState = { - fingerprint: this._fingerprint, - uid: shouldReplace ? this._uid : this._uid + 1, - destination + const parameters = { + viewport: clonedViewport, + div, + annotations: null, + intent }; - this.#updateInternalState(destination, newState.uid); - let newUrl; - if (this._updateUrl && destination?.hash) { - const baseUrl = document.location.href.split("#", 1)[0]; - if (!baseUrl.startsWith("file://")) { - newUrl = `${baseUrl}#${destination.hash}`; - } - } - if (shouldReplace) { - window.history.replaceState(newState, "", newUrl); - } else { - window.history.pushState(newState, "", newUrl); - } + this.annotationEditorLayer.render(parameters); + this.show(); } - #tryPushCurrentPosition(temporary = false) { - if (!this._position) { - return; - } - let position = this._position; - if (temporary) { - position = Object.assign(Object.create(null), this._position); - position.temporary = true; - } - if (!this._destination) { - this.#pushOrReplaceState(position); - return; - } - if (this._destination.temporary) { - this.#pushOrReplaceState(position, true); - return; - } - if (this._destination.hash === position.hash) { - return; - } - if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { + cancel() { + this._cancelled = true; + if (!this.div) { return; } - let forceReplace = false; - if (this._destination.page >= position.first && this._destination.page <= position.page) { - if (this._destination.dest !== undefined || !this._destination.first) { - return; - } - forceReplace = true; - } - this.#pushOrReplaceState(position, forceReplace); - } - #isValidPage(val) { - return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; - } - #isValidState(state, checkReload = false) { - if (!state) { - return false; - } - if (state.fingerprint !== this._fingerprint) { - if (checkReload) { - if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { - return false; - } - const [perfEntry] = performance.getEntriesByType("navigation"); - if (perfEntry?.type !== "reload") { - return false; - } - } else { - return false; - } - } - if (!Number.isInteger(state.uid) || state.uid < 0) { - return false; - } - if (state.destination === null || typeof state.destination !== "object") { - return false; - } - return true; - } - #updateInternalState(destination, uid, removeTemporary = false) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - if (removeTemporary && destination?.temporary) { - delete destination.temporary; - } - this._destination = destination; - this._uid = uid; - this._maxUid = Math.max(this._maxUid, uid); - this._numPositionUpdates = 0; - } - #parseCurrentHash(checkNameddest = false) { - const hash = unescape(getCurrentHash()).substring(1); - const params = parseQueryString(hash); - const nameddest = params.get("nameddest") || ""; - let page = params.get("page") | 0; - if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) { - page = null; - } - return { - hash, - page, - rotation: this.linkService.rotation - }; + this.annotationEditorLayer.destroy(); } - #updateViewarea({ - location - }) { - if (this._updateViewareaTimeout) { - clearTimeout(this._updateViewareaTimeout); - this._updateViewareaTimeout = null; - } - this._position = { - hash: location.pdfOpenParams.substring(1), - page: this.linkService.page, - first: location.pageNumber, - rotation: location.rotation - }; - if (this._popStateInProgress) { + hide() { + if (!this.div) { return; } - if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { - this._numPositionUpdates++; - } - if (UPDATE_VIEWAREA_TIMEOUT > 0) { - this._updateViewareaTimeout = setTimeout(() => { - if (!this._popStateInProgress) { - this.#tryPushCurrentPosition(true); - } - this._updateViewareaTimeout = null; - }, UPDATE_VIEWAREA_TIMEOUT); - } + this.annotationEditorLayer.pause(true); + this.div.hidden = true; } - #popState({ - state - }) { - const newHash = getCurrentHash(), - hashChanged = this._currentHash !== newHash; - this._currentHash = newHash; - if (!state) { - this._uid++; - const { - hash, - page, - rotation - } = this.#parseCurrentHash(); - this.#pushOrReplaceState({ - hash, - page, - rotation - }, true); + show() { + if (!this.div || this.annotationEditorLayer.isInvisible) { return; } - if (!this.#isValidState(state)) { - return; + this.div.hidden = false; + this.annotationEditorLayer.pause(false); + } +} + +;// ./web/app_options.js +{ + var compatParams = new Map(); + const userAgent = navigator.userAgent || ""; + const platform = navigator.platform || ""; + const maxTouchPoints = navigator.maxTouchPoints || 1; + const isAndroid = /Android/.test(userAgent); + const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; + (function () { + if (isIOS || isAndroid) { + compatParams.set("maxCanvasPixels", 5242880); } - this._popStateInProgress = true; - if (hashChanged) { - this._blockHashChange++; - waitOnEventOrTimeout({ - target: window, - name: "hashchange", - delay: HASH_CHANGE_TIMEOUT - }).then(() => { - this._blockHashChange--; - }); + })(); + (function () { + if (isAndroid) { + compatParams.set("useSystemFonts", false); } - const destination = state.destination; - this.#updateInternalState(destination, state.uid, true); - if (isValidRotation(destination.rotation)) { - this.linkService.rotation = destination.rotation; - } - if (destination.dest) { - this.linkService.goToDestination(destination.dest); - } else if (destination.hash) { - this.linkService.setHash(destination.hash); - } else if (destination.page) { - this.linkService.page = destination.page; - } - Promise.resolve().then(() => { - this._popStateInProgress = false; - }); - } - #pageHide() { - if (!this._destination || this._destination.temporary) { - this.#tryPushCurrentPosition(); - } - } - #bindEvents() { - if (this.#eventAbortController) { - return; - } - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), { - signal - }); - window.addEventListener("popstate", this.#popState.bind(this), { - signal - }); - window.addEventListener("pagehide", this.#pageHide.bind(this), { - signal - }); - } - #unbindEvents() { - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } -} -function isDestHashesEqual(destHash, pushHash) { - if (typeof destHash !== "string" || typeof pushHash !== "string") { - return false; - } - if (destHash === pushHash) { - return true; - } - const nameddest = parseQueryString(destHash).get("nameddest"); - if (nameddest === pushHash) { - return true; - } - return false; -} -function isDestArraysEqual(firstDest, secondDest) { - function isEntryEqual(first, second) { - if (typeof first !== typeof second) { - return false; - } - if (Array.isArray(first) || Array.isArray(second)) { - return false; - } - if (first !== null && typeof first === "object" && second !== null) { - if (Object.keys(first).length !== Object.keys(second).length) { - return false; - } - for (const key in first) { - if (!isEntryEqual(first[key], second[key])) { - return false; - } - } - return true; - } - return first === second || Number.isNaN(first) && Number.isNaN(second); - } - if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { - return false; - } - if (firstDest.length !== secondDest.length) { - return false; - } - for (let i = 0, ii = firstDest.length; i < ii; i++) { - if (!isEntryEqual(firstDest[i], secondDest[i])) { - return false; - } - } - return true; -} - -;// ./web/pdf_layer_viewer.js - -class PDFLayerViewer extends BaseTreeViewer { - constructor(options) { - super(options); - this.eventBus._on("optionalcontentconfigchanged", evt => { - this.#updateLayers(evt.promise); - }); - this.eventBus._on("resetlayers", () => { - this.#updateLayers(); - }); - this.eventBus._on("togglelayerstree", this._toggleAllTreeItems.bind(this)); - } - reset() { - super.reset(); - this._optionalContentConfig = null; - this._optionalContentVisibility?.clear(); - this._optionalContentVisibility = null; - } - _dispatchEvent(layersCount) { - this.eventBus.dispatch("layersloaded", { - source: this, - layersCount - }); - } - _bindLink(element, { - groupId, - input - }) { - const setVisibility = () => { - const visible = input.checked; - this._optionalContentConfig.setVisibility(groupId, visible); - const cached = this._optionalContentVisibility.get(groupId); - if (cached) { - cached.visible = visible; - } - this.eventBus.dispatch("optionalcontentconfig", { - source: this, - promise: Promise.resolve(this._optionalContentConfig) - }); - }; - element.onclick = evt => { - if (evt.target === input) { - setVisibility(); - return true; - } else if (evt.target !== element) { - return true; - } - input.checked = !input.checked; - setVisibility(); - return false; - }; - } - _setNestedName(element, { - name = null - }) { - if (typeof name === "string") { - element.textContent = this._normalizeTextContent(name); - return; - } - element.setAttribute("data-l10n-id", "pdfjs-additional-layers"); - element.style.fontStyle = "italic"; - this._l10n.translateOnce(element); - } - _addToggleButton(div, { - name = null - }) { - super._addToggleButton(div, name === null); - } - _toggleAllTreeItems() { - if (!this._optionalContentConfig) { - return; - } - super._toggleAllTreeItems(); - } - render({ - optionalContentConfig, - pdfDocument - }) { - if (this._optionalContentConfig) { - this.reset(); - } - this._optionalContentConfig = optionalContentConfig || null; - this._pdfDocument = pdfDocument || null; - const groups = optionalContentConfig?.getOrder(); - if (!groups) { - this._dispatchEvent(0); - return; - } - this._optionalContentVisibility = new Map(); - const fragment = document.createDocumentFragment(), - queue = [{ - parent: fragment, - groups - }]; - let layersCount = 0, - hasAnyNesting = false; - while (queue.length > 0) { - const levelData = queue.shift(); - for (const groupId of levelData.groups) { - const div = document.createElement("div"); - div.className = "treeItem"; - const element = document.createElement("a"); - div.append(element); - if (typeof groupId === "object") { - hasAnyNesting = true; - this._addToggleButton(div, groupId); - this._setNestedName(element, groupId); - const itemsDiv = document.createElement("div"); - itemsDiv.className = "treeItems"; - div.append(itemsDiv); - queue.push({ - parent: itemsDiv, - groups: groupId.order - }); - } else { - const group = optionalContentConfig.getGroup(groupId); - const input = document.createElement("input"); - this._bindLink(element, { - groupId, - input - }); - input.type = "checkbox"; - input.checked = group.visible; - this._optionalContentVisibility.set(groupId, { - input, - visible: input.checked - }); - const label = document.createElement("label"); - label.textContent = this._normalizeTextContent(group.name); - label.append(input); - element.append(label); - layersCount++; - } - levelData.parent.append(div); - } - } - this._finishRendering(fragment, layersCount, hasAnyNesting); - } - async #updateLayers(promise = null) { - if (!this._optionalContentConfig) { - return; - } - const pdfDocument = this._pdfDocument; - const optionalContentConfig = await (promise || pdfDocument.getOptionalContentConfig({ - intent: "display" - })); - if (pdfDocument !== this._pdfDocument) { - return; - } - if (promise) { - for (const [groupId, cached] of this._optionalContentVisibility) { - const group = optionalContentConfig.getGroup(groupId); - if (group && cached.visible !== group.visible) { - cached.input.checked = cached.visible = !cached.visible; - } - } - return; - } - this.eventBus.dispatch("optionalcontentconfig", { - source: this, - promise: Promise.resolve(optionalContentConfig) - }); - this.render({ - optionalContentConfig, - pdfDocument: this._pdfDocument - }); - } -} - -;// ./web/pdf_outline_viewer.js - - -class PDFOutlineViewer extends BaseTreeViewer { - constructor(options) { - super(options); - this.linkService = options.linkService; - this.downloadManager = options.downloadManager; - this.eventBus._on("toggleoutlinetree", this._toggleAllTreeItems.bind(this)); - this.eventBus._on("currentoutlineitem", this._currentOutlineItem.bind(this)); - this.eventBus._on("pagechanging", evt => { - this._currentPageNumber = evt.pageNumber; - }); - this.eventBus._on("pagesloaded", evt => { - this._isPagesLoaded = !!evt.pagesCount; - this._currentOutlineItemCapability?.resolve(this._isPagesLoaded); - }); - this.eventBus._on("sidebarviewchanged", evt => { - this._sidebarView = evt.view; - }); - } - reset() { - super.reset(); - this._outline = null; - this._pageNumberToDestHashCapability = null; - this._currentPageNumber = 1; - this._isPagesLoaded = null; - this._currentOutlineItemCapability?.resolve(false); - this._currentOutlineItemCapability = null; - } - _dispatchEvent(outlineCount) { - this._currentOutlineItemCapability = Promise.withResolvers(); - if (outlineCount === 0 || this._pdfDocument?.loadingParams.disableAutoFetch) { - this._currentOutlineItemCapability.resolve(false); - } else if (this._isPagesLoaded !== null) { - this._currentOutlineItemCapability.resolve(this._isPagesLoaded); - } - this.eventBus.dispatch("outlineloaded", { - source: this, - outlineCount, - currentOutlineItemPromise: this._currentOutlineItemCapability.promise - }); - } - _bindLink(element, { - url, - newWindow, - action, - attachment, - dest, - setOCGState - }) { - const { - linkService - } = this; - if (url) { - linkService.addLinkAttributes(element, url, newWindow); - return; - } - if (action) { - element.href = linkService.getAnchorUrl(""); - element.onclick = () => { - linkService.executeNamedAction(action); - return false; - }; - return; - } - if (attachment) { - element.href = linkService.getAnchorUrl(""); - element.onclick = () => { - this.downloadManager.openOrDownloadData(attachment.content, attachment.filename); - return false; - }; - return; - } - if (setOCGState) { - element.href = linkService.getAnchorUrl(""); - element.onclick = () => { - linkService.executeSetOCGState(setOCGState); - return false; - }; - return; - } - element.href = linkService.getDestinationHash(dest); - element.onclick = evt => { - this._updateCurrentTreeItem(evt.target.parentNode); - if (dest) { - linkService.goToDestination(dest); - } - return false; - }; - } - _setStyles(element, { - bold, - italic - }) { - if (bold) { - element.style.fontWeight = "bold"; - } - if (italic) { - element.style.fontStyle = "italic"; - } - } - _addToggleButton(div, { - count, - items - }) { - let hidden = false; - if (count < 0) { - let totalCount = items.length; - if (totalCount > 0) { - const queue = [...items]; - while (queue.length > 0) { - const { - count: nestedCount, - items: nestedItems - } = queue.shift(); - if (nestedCount > 0 && nestedItems.length > 0) { - totalCount += nestedItems.length; - queue.push(...nestedItems); - } - } - } - if (Math.abs(count) === totalCount) { - hidden = true; - } - } - super._addToggleButton(div, hidden); - } - _toggleAllTreeItems() { - if (!this._outline) { - return; - } - super._toggleAllTreeItems(); - } - render({ - outline, - pdfDocument - }) { - if (this._outline) { - this.reset(); - } - this._outline = outline || null; - this._pdfDocument = pdfDocument || null; - if (!outline) { - this._dispatchEvent(0); - return; - } - const fragment = document.createDocumentFragment(); - const queue = [{ - parent: fragment, - items: outline - }]; - let outlineCount = 0, - hasAnyNesting = false; - while (queue.length > 0) { - const levelData = queue.shift(); - for (const item of levelData.items) { - const div = document.createElement("div"); - div.className = "treeItem"; - const element = document.createElement("a"); - this._bindLink(element, item); - this._setStyles(element, item); - element.textContent = this._normalizeTextContent(item.title); - div.append(element); - if (item.items.length > 0) { - hasAnyNesting = true; - this._addToggleButton(div, item); - const itemsDiv = document.createElement("div"); - itemsDiv.className = "treeItems"; - div.append(itemsDiv); - queue.push({ - parent: itemsDiv, - items: item.items - }); - } - levelData.parent.append(div); - outlineCount++; - } - } - this._finishRendering(fragment, outlineCount, hasAnyNesting); - } - async _currentOutlineItem() { - if (!this._isPagesLoaded) { - throw new Error("_currentOutlineItem: All pages have not been loaded."); - } - if (!this._outline || !this._pdfDocument) { - return; - } - const pageNumberToDestHash = await this._getPageNumberToDestHash(this._pdfDocument); - if (!pageNumberToDestHash) { - return; - } - this._updateCurrentTreeItem(null); - if (this._sidebarView !== SidebarView.OUTLINE) { - return; - } - for (let i = this._currentPageNumber; i > 0; i--) { - const destHash = pageNumberToDestHash.get(i); - if (!destHash) { - continue; - } - const linkElement = this.container.querySelector(`a[href="${destHash}"]`); - if (!linkElement) { - continue; - } - this._scrollToCurrentTreeItem(linkElement.parentNode); - break; - } - } - async _getPageNumberToDestHash(pdfDocument) { - if (this._pageNumberToDestHashCapability) { - return this._pageNumberToDestHashCapability.promise; - } - this._pageNumberToDestHashCapability = Promise.withResolvers(); - const pageNumberToDestHash = new Map(), - pageNumberNesting = new Map(); - const queue = [{ - nesting: 0, - items: this._outline - }]; - while (queue.length > 0) { - const levelData = queue.shift(), - currentNesting = levelData.nesting; - for (const { - dest, - items - } of levelData.items) { - let explicitDest, pageNumber; - if (typeof dest === "string") { - explicitDest = await pdfDocument.getDestination(dest); - if (pdfDocument !== this._pdfDocument) { - return null; - } - } else { - explicitDest = dest; - } - if (Array.isArray(explicitDest)) { - const [destRef] = explicitDest; - if (destRef && typeof destRef === "object") { - pageNumber = pdfDocument.cachedPageNumber(destRef); - } else if (Number.isInteger(destRef)) { - pageNumber = destRef + 1; - } - if (Number.isInteger(pageNumber) && (!pageNumberToDestHash.has(pageNumber) || currentNesting > pageNumberNesting.get(pageNumber))) { - const destHash = this.linkService.getDestinationHash(dest); - pageNumberToDestHash.set(pageNumber, destHash); - pageNumberNesting.set(pageNumber, currentNesting); - } - } - if (items.length > 0) { - queue.push({ - nesting: currentNesting + 1, - items - }); - } - } - } - this._pageNumberToDestHashCapability.resolve(pageNumberToDestHash.size > 0 ? pageNumberToDestHash : null); - return this._pageNumberToDestHashCapability.promise; - } + })(); } - -;// ./web/pdf_presentation_mode.js - - -const DELAY_BEFORE_HIDING_CONTROLS = 3000; -const ACTIVE_SELECTOR = "pdfPresentationMode"; -const CONTROLS_SELECTOR = "pdfPresentationModeControls"; -const MOUSE_SCROLL_COOLDOWN_TIME = 50; -const PAGE_SWITCH_THRESHOLD = 0.1; -const SWIPE_MIN_DISTANCE_THRESHOLD = 50; -const SWIPE_ANGLE_THRESHOLD = Math.PI / 6; -class PDFPresentationMode { - #state = PresentationModeState.UNKNOWN; - #args = null; - #fullscreenChangeAbortController = null; - #windowAbortController = null; - constructor({ - container, - pdfViewer, - eventBus - }) { - this.container = container; - this.pdfViewer = pdfViewer; - this.eventBus = eventBus; - this.contextMenuOpen = false; - this.mouseScrollTimeStamp = 0; - this.mouseScrollDelta = 0; - this.touchSwipeState = null; - } - async request() { - const { - container, - pdfViewer - } = this; - if (this.active || !pdfViewer.pagesCount || !container.requestFullscreen) { - return false; - } - this.#addFullscreenChangeListeners(); - this.#notifyStateChange(PresentationModeState.CHANGING); - const promise = container.requestFullscreen(); - this.#args = { - pageNumber: pdfViewer.currentPageNumber, - scaleValue: pdfViewer.currentScaleValue, - scrollMode: pdfViewer.scrollMode, - spreadMode: null, - annotationEditorMode: null - }; - if (pdfViewer.spreadMode !== SpreadMode.NONE && !(pdfViewer.pageViewsReady && pdfViewer.hasEqualPageSizes)) { - console.warn("Ignoring Spread modes when entering PresentationMode, " + "since the document may contain varying page sizes."); - this.#args.spreadMode = pdfViewer.spreadMode; - } - if (pdfViewer.annotationEditorMode !== AnnotationEditorType.DISABLE) { - this.#args.annotationEditorMode = pdfViewer.annotationEditorMode; - } - try { - await promise; - pdfViewer.focus(); - return true; - } catch { - this.#removeFullscreenChangeListeners(); - this.#notifyStateChange(PresentationModeState.NORMAL); - } - return false; - } - get active() { - return this.#state === PresentationModeState.CHANGING || this.#state === PresentationModeState.FULLSCREEN; - } - #mouseWheel(evt) { - if (!this.active) { - return; - } - evt.preventDefault(); - const delta = normalizeWheelEventDelta(evt); - const currentTime = Date.now(); - const storedTime = this.mouseScrollTimeStamp; - if (currentTime > storedTime && currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) { - return; - } - if (this.mouseScrollDelta > 0 && delta < 0 || this.mouseScrollDelta < 0 && delta > 0) { - this.#resetMouseScrollState(); - } - this.mouseScrollDelta += delta; - if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) { - const totalDelta = this.mouseScrollDelta; - this.#resetMouseScrollState(); - const success = totalDelta > 0 ? this.pdfViewer.previousPage() : this.pdfViewer.nextPage(); - if (success) { - this.mouseScrollTimeStamp = currentTime; - } - } - } - #notifyStateChange(state) { - this.#state = state; - this.eventBus.dispatch("presentationmodechanged", { - source: this, - state - }); - } - #enter() { - this.#notifyStateChange(PresentationModeState.FULLSCREEN); - this.container.classList.add(ACTIVE_SELECTOR); - setTimeout(() => { - this.pdfViewer.scrollMode = ScrollMode.PAGE; - if (this.#args.spreadMode !== null) { - this.pdfViewer.spreadMode = SpreadMode.NONE; - } - this.pdfViewer.currentPageNumber = this.#args.pageNumber; - this.pdfViewer.currentScaleValue = "page-fit"; - if (this.#args.annotationEditorMode !== null) { - this.pdfViewer.annotationEditorMode = { - mode: AnnotationEditorType.NONE - }; - } - }, 0); - this.#addWindowListeners(); - this.#showControls(); - this.contextMenuOpen = false; - document.getSelection().empty(); - } - #exit() { - const pageNumber = this.pdfViewer.currentPageNumber; - this.container.classList.remove(ACTIVE_SELECTOR); - setTimeout(() => { - this.#removeFullscreenChangeListeners(); - this.#notifyStateChange(PresentationModeState.NORMAL); - this.pdfViewer.scrollMode = this.#args.scrollMode; - if (this.#args.spreadMode !== null) { - this.pdfViewer.spreadMode = this.#args.spreadMode; - } - this.pdfViewer.currentScaleValue = this.#args.scaleValue; - this.pdfViewer.currentPageNumber = pageNumber; - if (this.#args.annotationEditorMode !== null) { - this.pdfViewer.annotationEditorMode = { - mode: this.#args.annotationEditorMode - }; - } - this.#args = null; - }, 0); - this.#removeWindowListeners(); - this.#hideControls(); - this.#resetMouseScrollState(); - this.contextMenuOpen = false; - } - #mouseDown(evt) { - if (this.contextMenuOpen) { - this.contextMenuOpen = false; - evt.preventDefault(); - return; - } - if (evt.button !== 0) { - return; - } - if (evt.target.href && evt.target.parentNode?.hasAttribute("data-internal-link")) { - return; - } - evt.preventDefault(); - if (evt.shiftKey) { - this.pdfViewer.previousPage(); - } else { - this.pdfViewer.nextPage(); - } - } - #contextMenu() { - this.contextMenuOpen = true; - } - #showControls() { - if (this.controlsTimeout) { - clearTimeout(this.controlsTimeout); - } else { - this.container.classList.add(CONTROLS_SELECTOR); - } - this.controlsTimeout = setTimeout(() => { - this.container.classList.remove(CONTROLS_SELECTOR); - delete this.controlsTimeout; - }, DELAY_BEFORE_HIDING_CONTROLS); - } - #hideControls() { - if (!this.controlsTimeout) { - return; - } - clearTimeout(this.controlsTimeout); - this.container.classList.remove(CONTROLS_SELECTOR); - delete this.controlsTimeout; - } - #resetMouseScrollState() { - this.mouseScrollTimeStamp = 0; - this.mouseScrollDelta = 0; - } - #touchSwipe(evt) { - if (!this.active) { - return; - } - if (evt.touches.length > 1) { - this.touchSwipeState = null; - return; - } - switch (evt.type) { - case "touchstart": - this.touchSwipeState = { - startX: evt.touches[0].pageX, - startY: evt.touches[0].pageY, - endX: evt.touches[0].pageX, - endY: evt.touches[0].pageY - }; - break; - case "touchmove": - if (this.touchSwipeState === null) { - return; - } - this.touchSwipeState.endX = evt.touches[0].pageX; - this.touchSwipeState.endY = evt.touches[0].pageY; - evt.preventDefault(); - break; - case "touchend": - if (this.touchSwipeState === null) { - return; - } - let delta = 0; - const dx = this.touchSwipeState.endX - this.touchSwipeState.startX; - const dy = this.touchSwipeState.endY - this.touchSwipeState.startY; - const absAngle = Math.abs(Math.atan2(dy, dx)); - if (Math.abs(dx) > SWIPE_MIN_DISTANCE_THRESHOLD && (absAngle <= SWIPE_ANGLE_THRESHOLD || absAngle >= Math.PI - SWIPE_ANGLE_THRESHOLD)) { - delta = dx; - } else if (Math.abs(dy) > SWIPE_MIN_DISTANCE_THRESHOLD && Math.abs(absAngle - Math.PI / 2) <= SWIPE_ANGLE_THRESHOLD) { - delta = dy; - } - if (delta > 0) { - this.pdfViewer.previousPage(); - } else if (delta < 0) { - this.pdfViewer.nextPage(); - } - break; - } - } - #addWindowListeners() { - if (this.#windowAbortController) { - return; - } - this.#windowAbortController = new AbortController(); - const { - signal - } = this.#windowAbortController; - const touchSwipeBind = this.#touchSwipe.bind(this); - window.addEventListener("mousemove", this.#showControls.bind(this), { - signal - }); - window.addEventListener("mousedown", this.#mouseDown.bind(this), { - signal - }); - window.addEventListener("wheel", this.#mouseWheel.bind(this), { - passive: false, - signal - }); - window.addEventListener("keydown", this.#resetMouseScrollState.bind(this), { - signal - }); - window.addEventListener("contextmenu", this.#contextMenu.bind(this), { - signal - }); - window.addEventListener("touchstart", touchSwipeBind, { - signal - }); - window.addEventListener("touchmove", touchSwipeBind, { - signal - }); - window.addEventListener("touchend", touchSwipeBind, { - signal - }); - } - #removeWindowListeners() { - this.#windowAbortController?.abort(); - this.#windowAbortController = null; - } - #addFullscreenChangeListeners() { - if (this.#fullscreenChangeAbortController) { - return; - } - this.#fullscreenChangeAbortController = new AbortController(); - window.addEventListener("fullscreenchange", () => { - if (document.fullscreenElement) { - this.#enter(); - } else { - this.#exit(); - } - }, { - signal: this.#fullscreenChangeAbortController.signal - }); - } - #removeFullscreenChangeListeners() { - this.#fullscreenChangeAbortController?.abort(); - this.#fullscreenChangeAbortController = null; - } -} - -;// ./web/xfa_layer_builder.js - -class XfaLayerBuilder { - constructor({ - pdfPage, - annotationStorage = null, - linkService, - xfaHtml = null - }) { - this.pdfPage = pdfPage; - this.annotationStorage = annotationStorage; - this.linkService = linkService; - this.xfaHtml = xfaHtml; - this.div = null; - this._cancelled = false; - } - async render(viewport, intent = "display") { - if (intent === "print") { - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml: this.xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - const xfaHtml = await this.pdfPage.getXfa(); - if (this._cancelled || !xfaHtml) { - return { - textDivs: [] - }; - } - const parameters = { - viewport: viewport.clone({ - dontFlip: true - }), - div: this.div, - xfaHtml, - annotationStorage: this.annotationStorage, - linkService: this.linkService, - intent - }; - if (this.div) { - return XfaLayer.update(parameters); - } - this.div = document.createElement("div"); - parameters.div = this.div; - return XfaLayer.render(parameters); - } - cancel() { - this._cancelled = true; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } -} - -;// ./web/print_utils.js - - - -function getXfaHtmlForPrinting(printContainer, pdfDocument) { - const xfaHtml = pdfDocument.allXfaHtml; - const linkService = new SimpleLinkService(); - const scale = Math.round(PixelsPerInch.PDF_TO_CSS_UNITS * 100) / 100; - for (const xfaPage of xfaHtml.children) { - const page = document.createElement("div"); - page.className = "xfaPrintedPage"; - printContainer.append(page); - const builder = new XfaLayerBuilder({ - pdfPage: null, - annotationStorage: pdfDocument.annotationStorage, - linkService, - xfaHtml: xfaPage - }); - const viewport = getXfaPageViewport(xfaPage, { - scale - }); - builder.render(viewport, "print"); - page.append(builder.div); - } -} - -;// ./web/pdf_print_service.js - - -let activeService = null; -let dialog = null; -let overlayManager = null; -let viewerApp = { - initialized: false +const OptionKind = { + BROWSER: 0x01, + VIEWER: 0x02, + API: 0x04, + WORKER: 0x08, + EVENT_DISPATCH: 0x10, + PREFERENCE: 0x80 }; -function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size, printResolution, optionalContentConfigPromise, printAnnotationStoragePromise) { - const scratchCanvas = activeService.scratchCanvas; - const PRINT_UNITS = printResolution / PixelsPerInch.PDF; - scratchCanvas.width = Math.floor(size.width * PRINT_UNITS); - scratchCanvas.height = Math.floor(size.height * PRINT_UNITS); - const ctx = scratchCanvas.getContext("2d"); - ctx.save(); - ctx.fillStyle = "rgb(255, 255, 255)"; - ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height); - ctx.restore(); - return Promise.all([pdfDocument.getPage(pageNumber), printAnnotationStoragePromise]).then(function ([pdfPage, printAnnotationStorage]) { - const renderContext = { - canvasContext: ctx, - transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0], - viewport: pdfPage.getViewport({ - scale: 1, - rotation: size.rotation - }), - intent: "print", - annotationMode: AnnotationMode.ENABLE_STORAGE, - optionalContentConfigPromise, - printAnnotationStorage - }; - const renderTask = pdfPage.render(renderContext); - return renderTask.promise.catch(reason => { - if (!(reason instanceof RenderingCancelledException)) { - console.error(reason); - } - throw reason; - }); - }); -} -class PDFPrintService { - constructor({ - pdfDocument, - pagesOverview, - printContainer, - printResolution, - printAnnotationStoragePromise = null - }) { - this.pdfDocument = pdfDocument; - this.pagesOverview = pagesOverview; - this.printContainer = printContainer; - this._printResolution = printResolution || 150; - this._optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ - intent: "print" - }); - this._printAnnotationStoragePromise = printAnnotationStoragePromise || Promise.resolve(); - this.currentPage = -1; - this.scratchCanvas = document.createElement("canvas"); - } - layout() { - this.throwIfInactive(); - const body = document.querySelector("body"); - body.setAttribute("data-pdfjsprinting", true); - const { - width, - height - } = this.pagesOverview[0]; - const hasEqualPageSizes = this.pagesOverview.every(size => size.width === width && size.height === height); - if (!hasEqualPageSizes) { - console.warn("Not all pages have the same size. The printed result may be incorrect!"); - } - this.pageStyleSheet = document.createElement("style"); - this.pageStyleSheet.textContent = `@page { size: ${width}pt ${height}pt;}`; - body.append(this.pageStyleSheet); - } - destroy() { - if (activeService !== this) { - return; - } - this.printContainer.textContent = ""; - const body = document.querySelector("body"); - body.removeAttribute("data-pdfjsprinting"); - if (this.pageStyleSheet) { - this.pageStyleSheet.remove(); - this.pageStyleSheet = null; - } - this.scratchCanvas.width = this.scratchCanvas.height = 0; - this.scratchCanvas = null; - activeService = null; - ensureOverlay().then(function () { - if (overlayManager.active === dialog) { - overlayManager.close(dialog); - } - }); - } - renderPages() { - if (this.pdfDocument.isPureXfa) { - getXfaHtmlForPrinting(this.printContainer, this.pdfDocument); - return Promise.resolve(); - } - const pageCount = this.pagesOverview.length; - const renderNextPage = (resolve, reject) => { - this.throwIfInactive(); - if (++this.currentPage >= pageCount) { - renderProgress(pageCount, pageCount); - resolve(); - return; - } - const index = this.currentPage; - renderProgress(index, pageCount); - renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index], this._printResolution, this._optionalContentConfigPromise, this._printAnnotationStoragePromise).then(this.useRenderedPage.bind(this)).then(function () { - renderNextPage(resolve, reject); - }, reject); - }; - return new Promise(renderNextPage); - } - useRenderedPage() { - this.throwIfInactive(); - const img = document.createElement("img"); - this.scratchCanvas.toBlob(blob => { - img.src = URL.createObjectURL(blob); - }); - const wrapper = document.createElement("div"); - wrapper.className = "printedPage"; - wrapper.append(img); - this.printContainer.append(wrapper); - const { - promise, - resolve, - reject - } = Promise.withResolvers(); - img.onload = resolve; - img.onerror = reject; - promise.catch(() => {}).then(() => { - URL.revokeObjectURL(img.src); - }); - return promise; - } - performPrint() { - this.throwIfInactive(); - return new Promise(resolve => { - setTimeout(() => { - if (!this.active) { - resolve(); - return; - } - print.call(window); - setTimeout(resolve, 20); - }, 0); - }); - } - get active() { - return this === activeService; - } - throwIfInactive() { - if (!this.active) { - throw new Error("This print request was cancelled or completed."); - } - } -} -const print = window.print; -window.print = function () { - if (activeService) { - console.warn("Ignored window.print() because of a pending print job."); - return; - } - ensureOverlay().then(function () { - if (activeService) { - overlayManager.open(dialog); - } - }); - try { - dispatchEvent("beforeprint"); - } finally { - if (!activeService) { - console.error("Expected print service to be initialized."); - ensureOverlay().then(function () { - if (overlayManager.active === dialog) { - overlayManager.close(dialog); - } - }); - return; - } - const activeServiceOnEntry = activeService; - activeService.renderPages().then(function () { - return activeServiceOnEntry.performPrint(); - }).catch(function () {}).then(function () { - if (activeServiceOnEntry.active) { - abort(); - } - }); - } +const Type = { + BOOLEAN: 0x01, + NUMBER: 0x02, + OBJECT: 0x04, + STRING: 0x08, + UNDEFINED: 0x10 }; -function dispatchEvent(eventType) { - const event = new CustomEvent(eventType, { - bubbles: false, - cancelable: false, - detail: "custom" - }); - window.dispatchEvent(event); -} -function abort() { - if (activeService) { - activeService.destroy(); - dispatchEvent("afterprint"); - } -} -function renderProgress(index, total) { - dialog ||= document.getElementById("printServiceDialog"); - const progress = Math.round(100 * index / total); - const progressBar = dialog.querySelector("progress"); - const progressPerc = dialog.querySelector(".relative-progress"); - progressBar.value = progress; - progressPerc.setAttribute("data-l10n-args", JSON.stringify({ - progress - })); -} -window.addEventListener("keydown", function (event) { - if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) { - window.print(); - event.preventDefault(); - event.stopImmediatePropagation(); - } -}, true); -if ("onbeforeprint" in window) { - const stopPropagationIfNeeded = function (event) { - if (event.detail !== "custom") { - event.stopImmediatePropagation(); - } - }; - window.addEventListener("beforeprint", stopPropagationIfNeeded); - window.addEventListener("afterprint", stopPropagationIfNeeded); -} -let overlayPromise; -function ensureOverlay() { - if (!overlayPromise) { - overlayManager = viewerApp.overlayManager; - if (!overlayManager) { - throw new Error("The overlay manager has not yet been initialized."); - } - dialog ||= document.getElementById("printServiceDialog"); - overlayPromise = overlayManager.register(dialog, true); - document.getElementById("printCancel").onclick = abort; - dialog.addEventListener("close", abort); - } - return overlayPromise; -} -class PDFPrintServiceFactory { - static initGlobals(app) { - viewerApp = app; - } - static get supportsPrinting() { - return shadow(this, "supportsPrinting", true); - } - static createPrintService(params) { - if (activeService) { - throw new Error("The print service is created and active."); - } - return activeService = new PDFPrintService(params); - } -} - -;// ./web/pdf_rendering_queue.js - - -const CLEANUP_TIMEOUT = 30000; -class PDFRenderingQueue { - constructor() { - this.pdfViewer = null; - this.pdfThumbnailViewer = null; - this.onIdle = null; - this.highestPriorityPage = null; - this.idleTimeout = null; - this.printing = false; - this.isThumbnailViewEnabled = false; - Object.defineProperty(this, "hasViewer", { - value: () => !!this.pdfViewer - }); - } - setViewer(pdfViewer) { - this.pdfViewer = pdfViewer; - } - setThumbnailViewer(pdfThumbnailViewer) { - this.pdfThumbnailViewer = pdfThumbnailViewer; - } - isHighestPriority(view) { - return this.highestPriorityPage === view.renderingId; - } - renderHighestPriority(currentlyVisiblePages) { - if (this.idleTimeout) { - clearTimeout(this.idleTimeout); - this.idleTimeout = null; - } - if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { - return; - } - if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) { - return; - } - if (this.printing) { - return; - } - if (this.onIdle) { - this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); - } - } - getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { - const visibleViews = visible.views, - numVisible = visibleViews.length; - if (numVisible === 0) { - return null; - } - for (let i = 0; i < numVisible; i++) { - const view = visibleViews[i].view; - if (!this.isViewFinished(view)) { - return view; - } - } - const firstId = visible.first.id, - lastId = visible.last.id; - if (lastId - firstId + 1 > numVisible) { - const visibleIds = visible.ids; - for (let i = 1, ii = lastId - firstId; i < ii; i++) { - const holeId = scrolledDown ? firstId + i : lastId - i; - if (visibleIds.has(holeId)) { - continue; - } - const holeView = views[holeId - 1]; - if (!this.isViewFinished(holeView)) { - return holeView; - } - } - } - let preRenderIndex = scrolledDown ? lastId : firstId - 2; - let preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - if (preRenderExtra) { - preRenderIndex += scrolledDown ? 1 : -1; - preRenderView = views[preRenderIndex]; - if (preRenderView && !this.isViewFinished(preRenderView)) { - return preRenderView; - } - } - return null; - } - isViewFinished(view) { - return view.renderingState === RenderingStates.FINISHED; - } - renderView(view) { - switch (view.renderingState) { - case RenderingStates.FINISHED: - return false; - case RenderingStates.PAUSED: - this.highestPriorityPage = view.renderingId; - view.resume(); - break; - case RenderingStates.RUNNING: - this.highestPriorityPage = view.renderingId; - break; - case RenderingStates.INITIAL: - this.highestPriorityPage = view.renderingId; - view.draw().finally(() => { - this.renderHighestPriority(); - }).catch(reason => { - if (reason instanceof RenderingCancelledException) { - return; - } - console.error("renderView:", reason); - }); - break; - } - return true; - } -} - -;// ./web/pdf_scripting_manager.js - - -class PDFScriptingManager { - #closeCapability = null; - #destroyCapability = null; - #docProperties = null; - #eventAbortController = null; - #eventBus = null; - #externalServices = null; - #pdfDocument = null; - #pdfViewer = null; - #ready = false; - #scripting = null; - #willPrintCapability = null; - constructor({ - eventBus, - externalServices = null, - docProperties = null - }) { - this.#eventBus = eventBus; - this.#externalServices = externalServices; - this.#docProperties = docProperties; - } - setViewer(pdfViewer) { - this.#pdfViewer = pdfViewer; - } - async setDocument(pdfDocument) { - if (this.#pdfDocument) { - await this.#destroyScripting(); - } - this.#pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); - if (!objects && !docActions) { - await this.#destroyScripting(); - return; - } - if (pdfDocument !== this.#pdfDocument) { - return; - } - try { - this.#scripting = this.#initScripting(); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - const eventBus = this.#eventBus; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - eventBus._on("updatefromsandbox", event => { - if (event?.source === window) { - this.#updateFromSandbox(event.detail); - } - }, { - signal - }); - eventBus._on("dispatcheventinsandbox", event => { - this.#scripting?.dispatchEventInSandbox(event.detail); - }, { - signal - }); - eventBus._on("pagechanging", ({ - pageNumber, - previous - }) => { - if (pageNumber === previous) { - return; - } - this.#dispatchPageClose(previous); - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - if (!this._pageOpenPending.has(pageNumber)) { - return; - } - if (pageNumber !== this.#pdfViewer.currentPageNumber) { - return; - } - this.#dispatchPageOpen(pageNumber); - }, { - signal - }); - eventBus._on("pagesdestroy", async () => { - await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber); - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillClose" - }); - this.#closeCapability?.resolve(); - }, { - signal - }); - try { - const docProperties = await this.#docProperties(pdfDocument); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting.createSandbox({ - objects, - calculationOrder, - appInfo: { - platform: navigator.platform, - language: navigator.language - }, - docInfo: { - ...docProperties, - actions: docActions - } - }); - eventBus.dispatch("sandboxcreated", { - source: this - }); - } catch (error) { - console.error("setDocument:", error); - await this.#destroyScripting(); - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "Open" - }); - await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true); - Promise.resolve().then(() => { - if (pdfDocument === this.#pdfDocument) { - this.#ready = true; - } - }); - } - async dispatchWillSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "WillSave" - }); - } - async dispatchDidSave() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidSave" - }); - } - async dispatchWillPrint() { - if (!this.#scripting) { - return; - } - await this.#willPrintCapability?.promise; - this.#willPrintCapability = Promise.withResolvers(); - try { - await this.#scripting.dispatchEventInSandbox({ - id: "doc", - name: "WillPrint" - }); - } catch (ex) { - this.#willPrintCapability.resolve(); - this.#willPrintCapability = null; - throw ex; - } - await this.#willPrintCapability.promise; - } - async dispatchDidPrint() { - return this.#scripting?.dispatchEventInSandbox({ - id: "doc", - name: "DidPrint" - }); - } - get destroyPromise() { - return this.#destroyCapability?.promise || null; - } - get ready() { - return this.#ready; - } - get _pageOpenPending() { - return shadow(this, "_pageOpenPending", new Set()); - } - get _visitedPages() { - return shadow(this, "_visitedPages", new Map()); - } - async #updateFromSandbox(detail) { - const pdfViewer = this.#pdfViewer; - const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode; - const { - id, - siblings, - command, - value - } = detail; - if (!id) { - switch (command) { - case "clear": - console.clear(); - break; - case "error": - console.error(value); - break; - case "layout": - if (!isInPresentationMode) { - const modes = apiPageLayoutToViewerModes(value); - pdfViewer.spreadMode = modes.spreadMode; - } - break; - case "page-num": - pdfViewer.currentPageNumber = value + 1; - break; - case "print": - await pdfViewer.pagesPromise; - this.#eventBus.dispatch("print", { - source: this - }); - break; - case "println": - console.log(value); - break; - case "zoom": - if (!isInPresentationMode) { - pdfViewer.currentScaleValue = value; - } - break; - case "SaveAs": - this.#eventBus.dispatch("download", { - source: this - }); - break; - case "FirstPage": - pdfViewer.currentPageNumber = 1; - break; - case "LastPage": - pdfViewer.currentPageNumber = pdfViewer.pagesCount; - break; - case "NextPage": - pdfViewer.nextPage(); - break; - case "PrevPage": - pdfViewer.previousPage(); - break; - case "ZoomViewIn": - if (!isInPresentationMode) { - pdfViewer.increaseScale(); - } - break; - case "ZoomViewOut": - if (!isInPresentationMode) { - pdfViewer.decreaseScale(); - } - break; - case "WillPrintFinished": - this.#willPrintCapability?.resolve(); - this.#willPrintCapability = null; - break; - } - return; - } - if (isInPresentationMode && detail.focus) { - return; - } - delete detail.id; - delete detail.siblings; - const ids = siblings ? [id, ...siblings] : [id]; - for (const elementId of ids) { - const element = document.querySelector(`[data-element-id="${elementId}"]`); - if (element) { - element.dispatchEvent(new CustomEvent("updatefromsandbox", { - detail - })); - } else { - this.#pdfDocument?.annotationStorage.setValue(elementId, detail); - } - } - } - async #dispatchPageOpen(pageNumber, initialize = false) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (initialize) { - this.#closeCapability = Promise.withResolvers(); - } - if (!this.#closeCapability) { - return; - } - const pageView = this.#pdfViewer.getPageView(pageNumber - 1); - if (pageView?.renderingState !== RenderingStates.FINISHED) { - this._pageOpenPending.add(pageNumber); - return; - } - this._pageOpenPending.delete(pageNumber); - const actionsPromise = (async () => { - const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageOpen", - pageNumber, - actions - }); - })(); - visitedPages.set(pageNumber, actionsPromise); - } - async #dispatchPageClose(pageNumber) { - const pdfDocument = this.#pdfDocument, - visitedPages = this._visitedPages; - if (!this.#closeCapability) { - return; - } - if (this._pageOpenPending.has(pageNumber)) { - return; - } - const actionsPromise = visitedPages.get(pageNumber); - if (!actionsPromise) { - return; - } - visitedPages.set(pageNumber, null); - await actionsPromise; - if (pdfDocument !== this.#pdfDocument) { - return; - } - await this.#scripting?.dispatchEventInSandbox({ - id: "page", - name: "PageClose", - pageNumber - }); - } - #initScripting() { - this.#destroyCapability = Promise.withResolvers(); - if (this.#scripting) { - throw new Error("#initScripting: Scripting already exists."); - } - return this.#externalServices.createScripting(); - } - async #destroyScripting() { - if (!this.#scripting) { - this.#pdfDocument = null; - this.#destroyCapability?.resolve(); - return; - } - if (this.#closeCapability) { - await Promise.race([this.#closeCapability.promise, new Promise(resolve => { - setTimeout(resolve, 1000); - })]).catch(() => {}); - this.#closeCapability = null; - } - this.#pdfDocument = null; - try { - await this.#scripting.destroySandbox(); - } catch {} - this.#willPrintCapability?.reject(new Error("Scripting destroyed.")); - this.#willPrintCapability = null; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._pageOpenPending.clear(); - this._visitedPages.clear(); - this.#scripting = null; - this.#ready = false; - this.#destroyCapability?.resolve(); - } -} - -;// ./web/pdf_sidebar.js - -const SIDEBAR_WIDTH_VAR = "--sidebar-width"; -const SIDEBAR_MIN_WIDTH = 200; -const SIDEBAR_RESIZING_CLASS = "sidebarResizing"; -const UI_NOTIFICATION_CLASS = "pdfSidebarNotification"; -class PDFSidebar { - #isRTL = false; - #mouseAC = null; - #outerContainerWidth = null; - #width = null; - constructor({ - elements, - eventBus, - l10n - }) { - this.isOpen = false; - this.active = SidebarView.THUMBS; - this.isInitialViewSet = false; - this.isInitialEventDispatched = false; - this.onToggled = null; - this.onUpdateThumbnails = null; - this.outerContainer = elements.outerContainer; - this.sidebarContainer = elements.sidebarContainer; - this.toggleButton = elements.toggleButton; - this.resizer = elements.resizer; - this.thumbnailButton = elements.thumbnailButton; - this.outlineButton = elements.outlineButton; - this.attachmentsButton = elements.attachmentsButton; - this.layersButton = elements.layersButton; - this.thumbnailView = elements.thumbnailView; - this.outlineView = elements.outlineView; - this.attachmentsView = elements.attachmentsView; - this.layersView = elements.layersView; - this._currentOutlineItemButton = elements.currentOutlineItemButton; - this.eventBus = eventBus; - this.#isRTL = l10n.getDirection() === "rtl"; - this.#addEventListeners(); - } - reset() { - this.isInitialViewSet = false; - this.isInitialEventDispatched = false; - this.#hideUINotification(true); - this.switchView(SidebarView.THUMBS); - this.outlineButton.disabled = false; - this.attachmentsButton.disabled = false; - this.layersButton.disabled = false; - this._currentOutlineItemButton.disabled = true; - } - get visibleView() { - return this.isOpen ? this.active : SidebarView.NONE; - } - setInitialView(view = SidebarView.NONE) { - if (this.isInitialViewSet) { - return; - } - this.isInitialViewSet = true; - if (view === SidebarView.NONE || view === SidebarView.UNKNOWN) { - this.#dispatchEvent(); - return; - } - this.switchView(view, true); - if (!this.isInitialEventDispatched) { - this.#dispatchEvent(); - } - } - switchView(view, forceOpen = false) { - const isViewChanged = view !== this.active; - let forceRendering = false; - switch (view) { - case SidebarView.NONE: - if (this.isOpen) { - this.close(); - } - return; - case SidebarView.THUMBS: - if (this.isOpen && isViewChanged) { - forceRendering = true; - } - break; - case SidebarView.OUTLINE: - if (this.outlineButton.disabled) { - return; - } - break; - case SidebarView.ATTACHMENTS: - if (this.attachmentsButton.disabled) { - return; - } - break; - case SidebarView.LAYERS: - if (this.layersButton.disabled) { - return; - } - break; - default: - console.error(`PDFSidebar.switchView: "${view}" is not a valid view.`); - return; - } - this.active = view; - toggleCheckedBtn(this.thumbnailButton, view === SidebarView.THUMBS, this.thumbnailView); - toggleCheckedBtn(this.outlineButton, view === SidebarView.OUTLINE, this.outlineView); - toggleCheckedBtn(this.attachmentsButton, view === SidebarView.ATTACHMENTS, this.attachmentsView); - toggleCheckedBtn(this.layersButton, view === SidebarView.LAYERS, this.layersView); - if (forceOpen && !this.isOpen) { - this.open(); - return; - } - if (forceRendering) { - this.onUpdateThumbnails(); - this.onToggled(); - } - if (isViewChanged) { - this.#dispatchEvent(); - } - } - open() { - if (this.isOpen) { - return; - } - this.isOpen = true; - toggleExpandedBtn(this.toggleButton, true); - this.outerContainer.classList.add("sidebarMoving", "sidebarOpen"); - if (this.active === SidebarView.THUMBS) { - this.onUpdateThumbnails(); - } - this.onToggled(); - this.#dispatchEvent(); - this.#hideUINotification(); - } - close(evt = null) { - if (!this.isOpen) { - return; - } - this.isOpen = false; - toggleExpandedBtn(this.toggleButton, false); - this.outerContainer.classList.add("sidebarMoving"); - this.outerContainer.classList.remove("sidebarOpen"); - this.onToggled(); - this.#dispatchEvent(); - if (evt?.detail > 0) { - this.toggleButton.blur(); - } - } - toggle(evt = null) { - if (this.isOpen) { - this.close(evt); - } else { - this.open(); - } - } - #dispatchEvent() { - if (this.isInitialViewSet) { - this.isInitialEventDispatched ||= true; - } - this.eventBus.dispatch("sidebarviewchanged", { - source: this, - view: this.visibleView - }); - } - #showUINotification() { - this.toggleButton.setAttribute("data-l10n-id", "pdfjs-toggle-sidebar-notification-button"); - if (!this.isOpen) { - this.toggleButton.classList.add(UI_NOTIFICATION_CLASS); - } - } - #hideUINotification(reset = false) { - if (this.isOpen || reset) { - this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS); - } - if (reset) { - this.toggleButton.setAttribute("data-l10n-id", "pdfjs-toggle-sidebar-button"); - } - } - #addEventListeners() { - const { - eventBus, - outerContainer - } = this; - this.sidebarContainer.addEventListener("transitionend", evt => { - if (evt.target === this.sidebarContainer) { - outerContainer.classList.remove("sidebarMoving"); - eventBus.dispatch("resize", { - source: this - }); - } - }); - this.toggleButton.addEventListener("click", evt => { - this.toggle(evt); - }); - this.thumbnailButton.addEventListener("click", () => { - this.switchView(SidebarView.THUMBS); - }); - this.outlineButton.addEventListener("click", () => { - this.switchView(SidebarView.OUTLINE); - }); - this.outlineButton.addEventListener("dblclick", () => { - eventBus.dispatch("toggleoutlinetree", { - source: this - }); - }); - this.attachmentsButton.addEventListener("click", () => { - this.switchView(SidebarView.ATTACHMENTS); - }); - this.layersButton.addEventListener("click", () => { - this.switchView(SidebarView.LAYERS); - }); - this.layersButton.addEventListener("dblclick", () => { - eventBus.dispatch("resetlayers", { - source: this - }); - }); - this._currentOutlineItemButton.addEventListener("click", () => { - eventBus.dispatch("currentoutlineitem", { - source: this - }); - }); - const onTreeLoaded = (count, button, view) => { - button.disabled = !count; - if (count) { - this.#showUINotification(); - } else if (this.active === view) { - this.switchView(SidebarView.THUMBS); - } - }; - eventBus._on("outlineloaded", evt => { - onTreeLoaded(evt.outlineCount, this.outlineButton, SidebarView.OUTLINE); - evt.currentOutlineItemPromise.then(enabled => { - if (!this.isInitialViewSet) { - return; - } - this._currentOutlineItemButton.disabled = !enabled; - }); - }); - eventBus._on("attachmentsloaded", evt => { - onTreeLoaded(evt.attachmentsCount, this.attachmentsButton, SidebarView.ATTACHMENTS); - }); - eventBus._on("layersloaded", evt => { - onTreeLoaded(evt.layersCount, this.layersButton, SidebarView.LAYERS); - }); - eventBus._on("presentationmodechanged", evt => { - if (evt.state === PresentationModeState.NORMAL && this.visibleView === SidebarView.THUMBS) { - this.onUpdateThumbnails(); - } - }); - this.resizer.addEventListener("mousedown", evt => { - if (evt.button !== 0) { - return; - } - outerContainer.classList.add(SIDEBAR_RESIZING_CLASS); - this.#mouseAC = new AbortController(); - const opts = { - signal: this.#mouseAC.signal - }; - window.addEventListener("mousemove", this.#mouseMove.bind(this), opts); - window.addEventListener("mouseup", this.#mouseUp.bind(this), opts); - window.addEventListener("blur", this.#mouseUp.bind(this), opts); - }); - eventBus._on("resize", evt => { - if (evt.source !== window) { - return; - } - this.#outerContainerWidth = null; - if (!this.#width) { - return; - } - if (!this.isOpen) { - this.#updateWidth(this.#width); - return; - } - outerContainer.classList.add(SIDEBAR_RESIZING_CLASS); - const updated = this.#updateWidth(this.#width); - Promise.resolve().then(() => { - outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS); - if (updated) { - eventBus.dispatch("resize", { - source: this - }); - } - }); - }); - } - get outerContainerWidth() { - return this.#outerContainerWidth ||= this.outerContainer.clientWidth; - } - #updateWidth(width = 0) { - const maxWidth = Math.floor(this.outerContainerWidth / 2); - if (width > maxWidth) { - width = maxWidth; - } - if (width < SIDEBAR_MIN_WIDTH) { - width = SIDEBAR_MIN_WIDTH; - } - if (width === this.#width) { - return false; - } - this.#width = width; - docStyle.setProperty(SIDEBAR_WIDTH_VAR, `${width}px`); - return true; - } - #mouseMove(evt) { - let width = evt.clientX; - if (this.#isRTL) { - width = this.outerContainerWidth - width; - } - this.#updateWidth(width); - } - #mouseUp(evt) { - this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS); - this.eventBus.dispatch("resize", { - source: this - }); - this.#mouseAC?.abort(); - this.#mouseAC = null; - } -} - -;// ./web/pdf_thumbnail_view.js - - -const DRAW_UPSCALE_FACTOR = 2; -const MAX_NUM_SCALING_STEPS = 3; -const THUMBNAIL_WIDTH = 98; -class TempImageFactory { - static #tempCanvas = null; - static getCanvas(width, height) { - const tempCanvas = this.#tempCanvas ||= document.createElement("canvas"); - tempCanvas.width = width; - tempCanvas.height = height; - const ctx = tempCanvas.getContext("2d", { - alpha: false - }); - ctx.save(); - ctx.fillStyle = "rgb(255, 255, 255)"; - ctx.fillRect(0, 0, width, height); - ctx.restore(); - return [tempCanvas, tempCanvas.getContext("2d")]; - } - static destroyCanvas() { - const tempCanvas = this.#tempCanvas; - if (tempCanvas) { - tempCanvas.width = 0; - tempCanvas.height = 0; - } - this.#tempCanvas = null; - } -} -class PDFThumbnailView { - constructor({ - container, - eventBus, - id, - defaultViewport, - optionalContentConfigPromise, - linkService, - renderingQueue, - pageColors, - enableHWA - }) { - this.id = id; - this.renderingId = "thumbnail" + id; - this.pageLabel = null; - this.pdfPage = null; - this.rotation = 0; - this.viewport = defaultViewport; - this.pdfPageRotate = defaultViewport.rotation; - this._optionalContentConfigPromise = optionalContentConfigPromise || null; - this.pageColors = pageColors || null; - this.enableHWA = enableHWA || false; - this.eventBus = eventBus; - this.linkService = linkService; - this.renderingQueue = renderingQueue; - this.renderTask = null; - this.renderingState = RenderingStates.INITIAL; - this.resume = null; - const anchor = document.createElement("a"); - anchor.href = linkService.getAnchorUrl("#page=" + id); - anchor.setAttribute("data-l10n-id", "pdfjs-thumb-page-title"); - anchor.setAttribute("data-l10n-args", this.#pageL10nArgs); - anchor.onclick = function () { - linkService.goToPage(id); - return false; - }; - this.anchor = anchor; - const div = document.createElement("div"); - div.className = "thumbnail"; - div.setAttribute("data-page-number", this.id); - this.div = div; - this.#updateDims(); - const img = document.createElement("div"); - img.className = "thumbnailImage"; - this._placeholderImg = img; - div.append(img); - anchor.append(div); - container.append(anchor); - } - #updateDims() { - const { - width, - height - } = this.viewport; - const ratio = width / height; - this.canvasWidth = THUMBNAIL_WIDTH; - this.canvasHeight = this.canvasWidth / ratio | 0; - this.scale = this.canvasWidth / width; - const { - style - } = this.div; - style.setProperty("--thumbnail-width", `${this.canvasWidth}px`); - style.setProperty("--thumbnail-height", `${this.canvasHeight}px`); - } - setPdfPage(pdfPage) { - this.pdfPage = pdfPage; - this.pdfPageRotate = pdfPage.rotate; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = pdfPage.getViewport({ - scale: 1, - rotation: totalRotation - }); - this.reset(); - } - reset() { - this.cancelRendering(); - this.renderingState = RenderingStates.INITIAL; - this.div.removeAttribute("data-loaded"); - this.image?.replaceWith(this._placeholderImg); - this.#updateDims(); - if (this.image) { - this.image.removeAttribute("src"); - delete this.image; - } - } - update({ - rotation = null - }) { - if (typeof rotation === "number") { - this.rotation = rotation; - } - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = this.viewport.clone({ - scale: 1, - rotation: totalRotation - }); - this.reset(); - } - cancelRendering() { - if (this.renderTask) { - this.renderTask.cancel(); - this.renderTask = null; - } - this.resume = null; - } - #getPageDrawContext(upscaleFactor = 1, enableHWA = this.enableHWA) { - const canvas = document.createElement("canvas"); - const ctx = canvas.getContext("2d", { - alpha: false, - willReadFrequently: !enableHWA - }); - const outputScale = new OutputScale(); - canvas.width = upscaleFactor * this.canvasWidth * outputScale.sx | 0; - canvas.height = upscaleFactor * this.canvasHeight * outputScale.sy | 0; - const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; - return { - ctx, - canvas, - transform - }; - } - #convertCanvasToImage(canvas) { - if (this.renderingState !== RenderingStates.FINISHED) { - throw new Error("#convertCanvasToImage: Rendering has not finished."); - } - const reducedCanvas = this.#reduceImage(canvas); - const image = document.createElement("img"); - image.className = "thumbnailImage"; - image.setAttribute("data-l10n-id", "pdfjs-thumb-page-canvas"); - image.setAttribute("data-l10n-args", this.#pageL10nArgs); - image.src = reducedCanvas.toDataURL(); - this.image = image; - this.div.setAttribute("data-loaded", true); - this._placeholderImg.replaceWith(image); - reducedCanvas.width = 0; - reducedCanvas.height = 0; - } - async #finishRenderTask(renderTask, canvas, error = null) { - if (renderTask === this.renderTask) { - this.renderTask = null; - } - if (error instanceof RenderingCancelledException) { - return; - } - this.renderingState = RenderingStates.FINISHED; - this.#convertCanvasToImage(canvas); - if (error) { - throw error; - } - } - async draw() { - if (this.renderingState !== RenderingStates.INITIAL) { - console.error("Must be in new state before drawing"); - return undefined; - } - const { - pdfPage - } = this; - if (!pdfPage) { - this.renderingState = RenderingStates.FINISHED; - throw new Error("pdfPage is not loaded"); - } - this.renderingState = RenderingStates.RUNNING; - const { - ctx, - canvas, - transform - } = this.#getPageDrawContext(DRAW_UPSCALE_FACTOR); - const drawViewport = this.viewport.clone({ - scale: DRAW_UPSCALE_FACTOR * this.scale - }); - const renderContinueCallback = cont => { - if (!this.renderingQueue.isHighestPriority(this)) { - this.renderingState = RenderingStates.PAUSED; - this.resume = () => { - this.renderingState = RenderingStates.RUNNING; - cont(); - }; - return; - } - cont(); - }; - const renderContext = { - canvasContext: ctx, - transform, - viewport: drawViewport, - optionalContentConfigPromise: this._optionalContentConfigPromise, - pageColors: this.pageColors - }; - const renderTask = this.renderTask = pdfPage.render(renderContext); - renderTask.onContinue = renderContinueCallback; - const resultPromise = renderTask.promise.then(() => this.#finishRenderTask(renderTask, canvas), error => this.#finishRenderTask(renderTask, canvas, error)); - resultPromise.finally(() => { - canvas.width = 0; - canvas.height = 0; - this.eventBus.dispatch("thumbnailrendered", { - source: this, - pageNumber: this.id, - pdfPage: this.pdfPage - }); - }); - return resultPromise; - } - setImage(pageView) { - if (this.renderingState !== RenderingStates.INITIAL) { - return; - } - const { - thumbnailCanvas: canvas, - pdfPage, - scale - } = pageView; - if (!canvas) { - return; - } - if (!this.pdfPage) { - this.setPdfPage(pdfPage); - } - if (scale < this.scale) { - return; - } - this.renderingState = RenderingStates.FINISHED; - this.#convertCanvasToImage(canvas); - } - #reduceImage(img) { - const { - ctx, - canvas - } = this.#getPageDrawContext(1, true); - if (img.width <= 2 * canvas.width) { - ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height); - return canvas; - } - let reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS; - let reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS; - const [reducedImage, reducedImageCtx] = TempImageFactory.getCanvas(reducedWidth, reducedHeight); - while (reducedWidth > img.width || reducedHeight > img.height) { - reducedWidth >>= 1; - reducedHeight >>= 1; - } - reducedImageCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, reducedWidth, reducedHeight); - while (reducedWidth > 2 * canvas.width) { - reducedImageCtx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, reducedWidth >> 1, reducedHeight >> 1); - reducedWidth >>= 1; - reducedHeight >>= 1; - } - ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, canvas.width, canvas.height); - return canvas; - } - get #pageL10nArgs() { - return JSON.stringify({ - page: this.pageLabel ?? this.id - }); - } - setPageLabel(label) { - this.pageLabel = typeof label === "string" ? label : null; - this.anchor.setAttribute("data-l10n-args", this.#pageL10nArgs); - if (this.renderingState !== RenderingStates.FINISHED) { - return; - } - this.image?.setAttribute("data-l10n-args", this.#pageL10nArgs); - } -} - -;// ./web/pdf_thumbnail_viewer.js - - -const THUMBNAIL_SCROLL_MARGIN = -19; -const THUMBNAIL_SELECTED_CLASS = "selected"; -class PDFThumbnailViewer { - constructor({ - container, - eventBus, - linkService, - renderingQueue, - pageColors, - abortSignal, - enableHWA - }) { - this.container = container; - this.eventBus = eventBus; - this.linkService = linkService; - this.renderingQueue = renderingQueue; - this.pageColors = pageColors || null; - this.enableHWA = enableHWA || false; - this.scroll = watchScroll(this.container, this.#scrollUpdated.bind(this), abortSignal); - this.#resetView(); - } - #scrollUpdated() { - this.renderingQueue.renderHighestPriority(); - } - getThumbnail(index) { - return this._thumbnails[index]; - } - #getVisibleThumbs() { - return getVisibleElements({ - scrollEl: this.container, - views: this._thumbnails - }); - } - scrollThumbnailIntoView(pageNumber) { - if (!this.pdfDocument) { - return; - } - const thumbnailView = this._thumbnails[pageNumber - 1]; - if (!thumbnailView) { - console.error('scrollThumbnailIntoView: Invalid "pageNumber" parameter.'); - return; - } - if (pageNumber !== this._currentPageNumber) { - const prevThumbnailView = this._thumbnails[this._currentPageNumber - 1]; - prevThumbnailView.div.classList.remove(THUMBNAIL_SELECTED_CLASS); - thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS); - } - const { - first, - last, - views - } = this.#getVisibleThumbs(); - if (views.length > 0) { - let shouldScroll = false; - if (pageNumber <= first.id || pageNumber >= last.id) { - shouldScroll = true; - } else { - for (const { - id, - percent - } of views) { - if (id !== pageNumber) { - continue; - } - shouldScroll = percent < 100; - break; - } - } - if (shouldScroll) { - scrollIntoView(thumbnailView.div, { - top: THUMBNAIL_SCROLL_MARGIN - }); - } - } - this._currentPageNumber = pageNumber; - } - get pagesRotation() { - return this._pagesRotation; - } - set pagesRotation(rotation) { - if (!isValidRotation(rotation)) { - throw new Error("Invalid thumbnails rotation angle."); - } - if (!this.pdfDocument) { - return; - } - if (this._pagesRotation === rotation) { - return; - } - this._pagesRotation = rotation; - const updateArgs = { - rotation - }; - for (const thumbnail of this._thumbnails) { - thumbnail.update(updateArgs); - } - } - cleanup() { - for (const thumbnail of this._thumbnails) { - if (thumbnail.renderingState !== RenderingStates.FINISHED) { - thumbnail.reset(); - } - } - TempImageFactory.destroyCanvas(); - } - #resetView() { - this._thumbnails = []; - this._currentPageNumber = 1; - this._pageLabels = null; - this._pagesRotation = 0; - this.container.textContent = ""; - } - setDocument(pdfDocument) { - if (this.pdfDocument) { - this.#cancelRendering(); - this.#resetView(); - } - this.pdfDocument = pdfDocument; - if (!pdfDocument) { - return; - } - const firstPagePromise = pdfDocument.getPage(1); - const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ - intent: "display" - }); - firstPagePromise.then(firstPdfPage => { - const pagesCount = pdfDocument.numPages; - const viewport = firstPdfPage.getViewport({ - scale: 1 - }); - for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { - const thumbnail = new PDFThumbnailView({ - container: this.container, - eventBus: this.eventBus, - id: pageNum, - defaultViewport: viewport.clone(), - optionalContentConfigPromise, - linkService: this.linkService, - renderingQueue: this.renderingQueue, - pageColors: this.pageColors, - enableHWA: this.enableHWA - }); - this._thumbnails.push(thumbnail); - } - this._thumbnails[0]?.setPdfPage(firstPdfPage); - const thumbnailView = this._thumbnails[this._currentPageNumber - 1]; - thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS); - }).catch(reason => { - console.error("Unable to initialize thumbnail viewer", reason); - }); - } - #cancelRendering() { - for (const thumbnail of this._thumbnails) { - thumbnail.cancelRendering(); - } - } - setPageLabels(labels) { - if (!this.pdfDocument) { - return; - } - if (!labels) { - this._pageLabels = null; - } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { - this._pageLabels = null; - console.error("PDFThumbnailViewer_setPageLabels: Invalid page labels."); - } else { - this._pageLabels = labels; - } - for (let i = 0, ii = this._thumbnails.length; i < ii; i++) { - this._thumbnails[i].setPageLabel(this._pageLabels?.[i] ?? null); - } - } - async #ensurePdfPageLoaded(thumbView) { - if (thumbView.pdfPage) { - return thumbView.pdfPage; - } - try { - const pdfPage = await this.pdfDocument.getPage(thumbView.id); - if (!thumbView.pdfPage) { - thumbView.setPdfPage(pdfPage); - } - return pdfPage; - } catch (reason) { - console.error("Unable to get page for thumb view", reason); - return null; - } - } - #getScrollAhead(visible) { - if (visible.first?.id === 1) { - return true; - } else if (visible.last?.id === this._thumbnails.length) { - return false; - } - return this.scroll.down; - } - forceRendering() { - const visibleThumbs = this.#getVisibleThumbs(); - const scrollAhead = this.#getScrollAhead(visibleThumbs); - const thumbView = this.renderingQueue.getHighestPriority(visibleThumbs, this._thumbnails, scrollAhead); - if (thumbView) { - this.#ensurePdfPageLoaded(thumbView).then(() => { - this.renderingQueue.renderView(thumbView); - }); - return true; - } - return false; - } -} - -;// ./web/annotation_editor_layer_builder.js - - -class AnnotationEditorLayerBuilder { - #annotationLayer = null; - #drawLayer = null; - #onAppend = null; - #structTreeLayer = null; - #textLayer = null; - #uiManager; - constructor(options) { - this.pdfPage = options.pdfPage; - this.accessibilityManager = options.accessibilityManager; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.annotationEditorLayer = null; - this.div = null; - this._cancelled = false; - this.#uiManager = options.uiManager; - this.#annotationLayer = options.annotationLayer || null; - this.#textLayer = options.textLayer || null; - this.#drawLayer = options.drawLayer || null; - this.#onAppend = options.onAppend || null; - this.#structTreeLayer = options.structTreeLayer || null; - } - async render(viewport, intent = "display") { - if (intent !== "display") { - return; - } - if (this._cancelled) { - return; - } - const clonedViewport = viewport.clone({ - dontFlip: true - }); - if (this.div) { - this.annotationEditorLayer.update({ - viewport: clonedViewport - }); - this.show(); - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationEditorLayer"; - div.hidden = true; - div.dir = this.#uiManager.direction; - this.#onAppend?.(div); - this.annotationEditorLayer = new AnnotationEditorLayer({ - uiManager: this.#uiManager, - div, - structTreeLayer: this.#structTreeLayer, - accessibilityManager: this.accessibilityManager, - pageIndex: this.pdfPage.pageNumber - 1, - l10n: this.l10n, - viewport: clonedViewport, - annotationLayer: this.#annotationLayer, - textLayer: this.#textLayer, - drawLayer: this.#drawLayer - }); - const parameters = { - viewport: clonedViewport, - div, - annotations: null, - intent - }; - this.annotationEditorLayer.render(parameters); - this.show(); - } - cancel() { - this._cancelled = true; - if (!this.div) { - return; - } - this.annotationEditorLayer.destroy(); - } - hide() { - if (!this.div) { - return; - } - this.annotationEditorLayer.pause(true); - this.div.hidden = true; - } - show() { - if (!this.div || this.annotationEditorLayer.isInvisible) { - return; - } - this.div.hidden = false; - this.annotationEditorLayer.pause(false); - } -} - -;// ./web/annotation_layer_builder.js - - -class AnnotationLayerBuilder { - #onAppend = null; - #eventAbortController = null; - constructor({ - pdfPage, - linkService, - downloadManager, - annotationStorage = null, - imageResourcesPath = "", - renderForms = true, - enableScripting = false, - hasJSActionsPromise = null, - fieldObjectsPromise = null, - annotationCanvasMap = null, - accessibilityManager = null, - annotationEditorUIManager = null, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.linkService = linkService; - this.downloadManager = downloadManager; - this.imageResourcesPath = imageResourcesPath; - this.renderForms = renderForms; - this.annotationStorage = annotationStorage; - this.enableScripting = enableScripting; - this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false); - this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null); - this._annotationCanvasMap = annotationCanvasMap; - this._accessibilityManager = accessibilityManager; - this._annotationEditorUIManager = annotationEditorUIManager; - this.#onAppend = onAppend; - this.annotationLayer = null; - this.div = null; - this._cancelled = false; - this._eventBus = linkService.eventBus; - } - async render(viewport, options, intent = "display") { - if (this.div) { - if (this._cancelled || !this.annotationLayer) { - return; - } - this.annotationLayer.update({ - viewport: viewport.clone({ - dontFlip: true - }) - }); - return; - } - const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({ - intent - }), this._hasJSActionsPromise, this._fieldObjectsPromise]); - if (this._cancelled) { - return; - } - const div = this.div = document.createElement("div"); - div.className = "annotationLayer"; - this.#onAppend?.(div); - if (annotations.length === 0) { - this.hide(); - return; - } - this.annotationLayer = new AnnotationLayer({ - div, - accessibilityManager: this._accessibilityManager, - annotationCanvasMap: this._annotationCanvasMap, - annotationEditorUIManager: this._annotationEditorUIManager, - page: this.pdfPage, - viewport: viewport.clone({ - dontFlip: true - }), - structTreeLayer: options?.structTreeLayer || null - }); - await this.annotationLayer.render({ - annotations, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.renderForms, - linkService: this.linkService, - downloadManager: this.downloadManager, - annotationStorage: this.annotationStorage, - enableScripting: this.enableScripting, - hasJSActions, - fieldObjects - }); - if (this.linkService.isInPresentationMode) { - this.#updatePresentationModeState(PresentationModeState.FULLSCREEN); - } - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this._eventBus?._on("presentationmodechanged", evt => { - this.#updatePresentationModeState(evt.state); - }, { - signal: this.#eventAbortController.signal - }); - } - } - cancel() { - this._cancelled = true; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - } - hide() { - if (!this.div) { - return; - } - this.div.hidden = true; - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - #updatePresentationModeState(state) { - if (!this.div) { - return; - } - let disableFormElements = false; - switch (state) { - case PresentationModeState.FULLSCREEN: - disableFormElements = true; - break; - case PresentationModeState.NORMAL: - break; - default: - return; - } - for (const section of this.div.childNodes) { - if (section.hasAttribute("data-internal-link")) { - continue; - } - section.inert = disableFormElements; - } - } -} - -;// ./web/draw_layer_builder.js - -class DrawLayerBuilder { - #drawLayer = null; - constructor(options) { - this.pageIndex = options.pageIndex; - } - async render(intent = "display") { - if (intent !== "display" || this.#drawLayer || this._cancelled) { - return; - } - this.#drawLayer = new DrawLayer({ - pageIndex: this.pageIndex - }); - } - cancel() { - this._cancelled = true; - if (!this.#drawLayer) { - return; - } - this.#drawLayer.destroy(); - this.#drawLayer = null; - } - setParent(parent) { - this.#drawLayer?.setParent(parent); - } - getDrawLayer() { - return this.#drawLayer; - } -} - -;// ./web/struct_tree_layer_builder.js - -const PDF_ROLE_TO_HTML_ROLE = { - Document: null, - DocumentFragment: null, - Part: "group", - Sect: "group", - Div: "group", - Aside: "note", - NonStruct: "none", - P: null, - H: "heading", - Title: null, - FENote: "note", - Sub: "group", - Lbl: null, - Span: null, - Em: null, - Strong: null, - Link: "link", - Annot: "note", - Form: "form", - Ruby: null, - RB: null, - RT: null, - RP: null, - Warichu: null, - WT: null, - WP: null, - L: "list", - LI: "listitem", - LBody: null, - Table: "table", - TR: "row", - TH: "columnheader", - TD: "cell", - THead: "columnheader", - TBody: null, - TFoot: null, - Caption: null, - Figure: "figure", - Formula: null, - Artifact: null -}; -const HEADING_PATTERN = /^H(\d+)$/; -class StructTreeLayerBuilder { - #promise; - #treeDom = null; - #treePromise; - #elementAttributes = new Map(); - #rawDims; - #elementsToAddToTextLayer = null; - constructor(pdfPage, rawDims) { - this.#promise = pdfPage.getStructTree(); - this.#rawDims = rawDims; - } - async render() { - if (this.#treePromise) { - return this.#treePromise; - } - const { - promise, - resolve, - reject - } = Promise.withResolvers(); - this.#treePromise = promise; - try { - this.#treeDom = this.#walk(await this.#promise); - } catch (ex) { - reject(ex); - } - this.#promise = null; - this.#treeDom?.classList.add("structTree"); - resolve(this.#treeDom); - return promise; - } - async getAriaAttributes(annotationId) { - try { - await this.render(); - return this.#elementAttributes.get(annotationId); - } catch {} - return null; - } - hide() { - if (this.#treeDom && !this.#treeDom.hidden) { - this.#treeDom.hidden = true; - } - } - show() { - if (this.#treeDom?.hidden) { - this.#treeDom.hidden = false; - } - } - #setAttributes(structElement, htmlElement) { - const { - alt, - id, - lang - } = structElement; - if (alt !== undefined) { - let added = false; - const label = removeNullCharacters(alt); - for (const child of structElement.children) { - if (child.type === "annotation") { - let attrs = this.#elementAttributes.get(child.id); - if (!attrs) { - attrs = new Map(); - this.#elementAttributes.set(child.id, attrs); - } - attrs.set("aria-label", label); - added = true; - } - } - if (!added) { - htmlElement.setAttribute("aria-label", label); - } - } - if (id !== undefined) { - htmlElement.setAttribute("aria-owns", id); - } - if (lang !== undefined) { - htmlElement.setAttribute("lang", removeNullCharacters(lang, true)); - } - } - #addImageInTextLayer(node, element) { - const { - alt, - bbox, - children - } = node; - const child = children?.[0]; - if (!this.#rawDims || !alt || !bbox || child?.type !== "content") { - return false; - } - const { - id - } = child; - if (!id) { - return false; - } - element.setAttribute("aria-owns", id); - const img = document.createElement("span"); - (this.#elementsToAddToTextLayer ||= new Map()).set(id, img); - img.setAttribute("role", "img"); - img.setAttribute("aria-label", removeNullCharacters(alt)); - const { - pageHeight, - pageX, - pageY - } = this.#rawDims; - const calc = "calc(var(--scale-factor)*"; - const { - style - } = img; - style.width = `${calc}${bbox[2] - bbox[0]}px)`; - style.height = `${calc}${bbox[3] - bbox[1]}px)`; - style.left = `${calc}${bbox[0] - pageX}px)`; - style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`; - return true; - } - addElementsToTextLayer() { - if (!this.#elementsToAddToTextLayer) { - return; - } - for (const [id, img] of this.#elementsToAddToTextLayer) { - document.getElementById(id)?.append(img); - } - this.#elementsToAddToTextLayer.clear(); - this.#elementsToAddToTextLayer = null; - } - #walk(node) { - if (!node) { - return null; - } - const element = document.createElement("span"); - if ("role" in node) { - const { - role - } = node; - const match = role.match(HEADING_PATTERN); - if (match) { - element.setAttribute("role", "heading"); - element.setAttribute("aria-level", match[1]); - } else if (PDF_ROLE_TO_HTML_ROLE[role]) { - element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); - } - if (role === "Figure" && this.#addImageInTextLayer(node, element)) { - return element; - } - } - this.#setAttributes(node, element); - if (node.children) { - if (node.children.length === 1 && "id" in node.children[0]) { - this.#setAttributes(node.children[0], element); - } else { - for (const kid of node.children) { - element.append(this.#walk(kid)); - } - } - } - return element; - } -} - -;// ./web/text_accessibility.js - -class TextAccessibilityManager { - #enabled = false; - #textChildren = null; - #textNodes = new Map(); - #waitingElements = new Map(); - setTextMapping(textDivs) { - this.#textChildren = textDivs; - } - static #compareElementPositions(e1, e2) { - const rect1 = e1.getBoundingClientRect(); - const rect2 = e2.getBoundingClientRect(); - if (rect1.width === 0 && rect1.height === 0) { - return +1; - } - if (rect2.width === 0 && rect2.height === 0) { - return -1; - } - const top1 = rect1.y; - const bot1 = rect1.y + rect1.height; - const mid1 = rect1.y + rect1.height / 2; - const top2 = rect2.y; - const bot2 = rect2.y + rect2.height; - const mid2 = rect2.y + rect2.height / 2; - if (mid1 <= top2 && mid2 >= bot1) { - return -1; - } - if (mid2 <= top1 && mid1 >= bot2) { - return +1; - } - const centerX1 = rect1.x + rect1.width / 2; - const centerX2 = rect2.x + rect2.width / 2; - return centerX1 - centerX2; - } - enable() { - if (this.#enabled) { - throw new Error("TextAccessibilityManager is already enabled."); - } - if (!this.#textChildren) { - throw new Error("Text divs and strings have not been set."); - } - this.#enabled = true; - this.#textChildren = this.#textChildren.slice(); - this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions); - if (this.#textNodes.size > 0) { - const textChildren = this.#textChildren; - for (const [id, nodeIndex] of this.#textNodes) { - const element = document.getElementById(id); - if (!element) { - this.#textNodes.delete(id); - continue; - } - this.#addIdToAriaOwns(id, textChildren[nodeIndex]); - } - } - for (const [element, isRemovable] of this.#waitingElements) { - this.addPointerInTextLayer(element, isRemovable); - } - this.#waitingElements.clear(); - } - disable() { - if (!this.#enabled) { - return; - } - this.#waitingElements.clear(); - this.#textChildren = null; - this.#enabled = false; - } - removePointerInTextLayer(element) { - if (!this.#enabled) { - this.#waitingElements.delete(element); - return; - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return; - } - const { - id - } = element; - const nodeIndex = this.#textNodes.get(id); - if (nodeIndex === undefined) { - return; - } - const node = children[nodeIndex]; - this.#textNodes.delete(id); - let owns = node.getAttribute("aria-owns"); - if (owns?.includes(id)) { - owns = owns.split(" ").filter(x => x !== id).join(" "); - if (owns) { - node.setAttribute("aria-owns", owns); - } else { - node.removeAttribute("aria-owns"); - node.setAttribute("role", "presentation"); - } - } - } - #addIdToAriaOwns(id, node) { - const owns = node.getAttribute("aria-owns"); - if (!owns?.includes(id)) { - node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id); - } - node.removeAttribute("role"); - } - addPointerInTextLayer(element, isRemovable) { - const { - id - } = element; - if (!id) { - return null; - } - if (!this.#enabled) { - this.#waitingElements.set(element, isRemovable); - return null; - } - if (isRemovable) { - this.removePointerInTextLayer(element); - } - const children = this.#textChildren; - if (!children || children.length === 0) { - return null; - } - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0); - const nodeIndex = Math.max(0, index - 1); - const child = children[nodeIndex]; - this.#addIdToAriaOwns(id, child); - this.#textNodes.set(id, nodeIndex); - const parent = child.parentNode; - return parent?.classList.contains("markedContent") ? parent.id : null; - } - moveElementInDOM(container, element, contentElement, isRemovable) { - const id = this.addPointerInTextLayer(contentElement, isRemovable); - if (!container.hasChildNodes()) { - container.append(element); - return id; - } - const children = Array.from(container.childNodes).filter(node => node !== element); - if (children.length === 0) { - return id; - } - const elementToCompare = contentElement || element; - const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0); - if (index === 0) { - children[0].before(element); - } else { - children[index - 1].after(element); - } - return id; - } -} - -;// ./web/text_highlighter.js -class TextHighlighter { - #eventAbortController = null; - constructor({ - findController, - eventBus, - pageIndex - }) { - this.findController = findController; - this.matches = []; - this.eventBus = eventBus; - this.pageIdx = pageIndex; - this.textDivs = null; - this.textContentItemsStr = null; - this.enabled = false; - } - setTextMapping(divs, texts) { - this.textDivs = divs; - this.textContentItemsStr = texts; - } - enable() { - if (!this.textDivs || !this.textContentItemsStr) { - throw new Error("Text divs and strings have not been set."); - } - if (this.enabled) { - throw new Error("TextHighlighter is already enabled."); - } - this.enabled = true; - if (!this.#eventAbortController) { - this.#eventAbortController = new AbortController(); - this.eventBus._on("updatetextlayermatches", evt => { - if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) { - this._updateMatches(); - } - }, { - signal: this.#eventAbortController.signal - }); - } - this._updateMatches(); - } - disable() { - if (!this.enabled) { - return; - } - this.enabled = false; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this._updateMatches(true); - } - _convertMatches(matches, matchesLength) { - if (!matches) { - return []; - } - const { - textContentItemsStr - } = this; - let i = 0, - iIndex = 0; - const end = textContentItemsStr.length - 1; - const result = []; - for (let m = 0, mm = matches.length; m < mm; m++) { - let matchIdx = matches[m]; - while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - if (i === textContentItemsStr.length) { - console.error("Could not find a matching mapping"); - } - const match = { - begin: { - divIdx: i, - offset: matchIdx - iIndex - } - }; - matchIdx += matchesLength[m]; - while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { - iIndex += textContentItemsStr[i].length; - i++; - } - match.end = { - divIdx: i, - offset: matchIdx - iIndex - }; - result.push(match); - } - return result; - } - _renderMatches(matches) { - if (matches.length === 0) { - return; - } - const { - findController, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - const isSelectedPage = pageIdx === findController.selected.pageIdx; - const selectedMatchIdx = findController.selected.matchIdx; - const highlightAll = findController.state.highlightAll; - let prevEnd = null; - const infinity = { - divIdx: -1, - offset: undefined - }; - function beginText(begin, className) { - const divIdx = begin.divIdx; - textDivs[divIdx].textContent = ""; - return appendTextToDiv(divIdx, 0, begin.offset, className); - } - function appendTextToDiv(divIdx, fromOffset, toOffset, className) { - let div = textDivs[divIdx]; - if (div.nodeType === Node.TEXT_NODE) { - const span = document.createElement("span"); - div.before(span); - span.append(div); - textDivs[divIdx] = span; - div = span; - } - const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset); - const node = document.createTextNode(content); - if (className) { - const span = document.createElement("span"); - span.className = `${className} appended`; - span.append(node); - div.append(span); - if (className.includes("selected")) { - const { - left - } = span.getClientRects()[0]; - const parentLeft = div.getBoundingClientRect().left; - return left - parentLeft; - } - return 0; - } - div.append(node); - return 0; - } - let i0 = selectedMatchIdx, - i1 = i0 + 1; - if (highlightAll) { - i0 = 0; - i1 = matches.length; - } else if (!isSelectedPage) { - return; - } - let lastDivIdx = -1; - let lastOffset = -1; - for (let i = i0; i < i1; i++) { - const match = matches[i]; - const begin = match.begin; - if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) { - continue; - } - lastDivIdx = begin.divIdx; - lastOffset = begin.offset; - const end = match.end; - const isSelected = isSelectedPage && i === selectedMatchIdx; - const highlightSuffix = isSelected ? " selected" : ""; - let selectedLeft = 0; - if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { - if (prevEnd !== null) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - beginText(begin); - } else { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); - } - if (begin.divIdx === end.divIdx) { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); - } else { - selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); - for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { - textDivs[n0].className = "highlight middle" + highlightSuffix; - } - beginText(end, "highlight end" + highlightSuffix); - } - prevEnd = end; - if (isSelected) { - findController.scrollMatchIntoView({ - element: textDivs[begin.divIdx], - selectedLeft, - pageIndex: pageIdx, - matchIndex: selectedMatchIdx - }); - } - } - if (prevEnd) { - appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); - } - } - _updateMatches(reset = false) { - if (!this.enabled && !reset) { - return; - } - const { - findController, - matches, - pageIdx - } = this; - const { - textContentItemsStr, - textDivs - } = this; - let clearedUntilDivIdx = -1; - for (const match of matches) { - const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); - for (let n = begin, end = match.end.divIdx; n <= end; n++) { - const div = textDivs[n]; - div.textContent = textContentItemsStr[n]; - div.className = ""; - } - clearedUntilDivIdx = match.end.divIdx + 1; - } - if (!findController?.highlightMatches || reset) { - return; - } - const pageMatches = findController.pageMatches[pageIdx] || null; - const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null; - this.matches = this._convertMatches(pageMatches, pageMatchesLength); - this._renderMatches(this.matches); +const defaultOptions = { + allowedGlobalEvents: { + value: null, + kind: OptionKind.BROWSER + }, + canvasMaxAreaInBytes: { + value: -1, + kind: OptionKind.BROWSER + OptionKind.API + }, + isInAutomation: { + value: false, + kind: OptionKind.BROWSER + }, + localeProperties: { + value: { + lang: navigator.language || "en-US" + }, + kind: OptionKind.BROWSER + }, + nimbusDataStr: { + value: "", + kind: OptionKind.BROWSER + }, + supportsCaretBrowsingMode: { + value: false, + kind: OptionKind.BROWSER + }, + supportsDocumentFonts: { + value: true, + kind: OptionKind.BROWSER + }, + supportsIntegratedFind: { + value: false, + kind: OptionKind.BROWSER + }, + supportsMouseWheelZoomCtrlKey: { + value: true, + kind: OptionKind.BROWSER + }, + supportsMouseWheelZoomMetaKey: { + value: true, + kind: OptionKind.BROWSER + }, + supportsPinchToZoom: { + value: true, + kind: OptionKind.BROWSER + }, + toolbarDensity: { + value: 0, + kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH + }, + altTextLearnMoreUrl: { + value: "", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + annotationEditorMode: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + annotationMode: { + value: 2, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + cursorToolOnLoad: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + debuggerSrc: { + value: "./debugger.mjs", + kind: OptionKind.VIEWER + }, + defaultZoomDelay: { + value: 400, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + defaultZoomValue: { + value: "", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + disableHistory: { + value: false, + kind: OptionKind.VIEWER + }, + disablePageLabels: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableAltText: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableAltTextModelDownload: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH + }, + enableGuessAltText: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH + }, + enableHighlightFloatingButton: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableNewAltTextWhenAddingImage: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enablePermissions: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enablePrintAutoRotate: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableScripting: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableUpdatedAddImage: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + externalLinkRel: { + value: "noopener noreferrer nofollow", + kind: OptionKind.VIEWER + }, + externalLinkTarget: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + highlightEditorColors: { + value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + historyUpdateUrl: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + ignoreDestinationZoom: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + imageResourcesPath: { + value: "./images/", + kind: OptionKind.VIEWER + }, + maxCanvasPixels: { + value: 2 ** 25, + kind: OptionKind.VIEWER + }, + forcePageColors: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + pageColorsBackground: { + value: "Canvas", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + pageColorsForeground: { + value: "CanvasText", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + pdfBugEnabled: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + printResolution: { + value: 150, + kind: OptionKind.VIEWER + }, + sidebarViewOnLoad: { + value: -1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + scrollModeOnLoad: { + value: -1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + spreadModeOnLoad: { + value: -1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + textLayerMode: { + value: 1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + viewOnLoad: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + cMapPacked: { + value: true, + kind: OptionKind.API + }, + cMapUrl: { + value: "../web/cmaps/", + kind: OptionKind.API + }, + disableAutoFetch: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + disableFontFace: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + disableRange: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + disableStream: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + docBaseUrl: { + value: "", + kind: OptionKind.API + }, + enableHWA: { + value: true, + kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableXfa: { + value: true, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + fontExtraProperties: { + value: false, + kind: OptionKind.API + }, + isEvalSupported: { + value: true, + kind: OptionKind.API + }, + isOffscreenCanvasSupported: { + value: true, + kind: OptionKind.API + }, + maxImageSize: { + value: -1, + kind: OptionKind.API + }, + pdfBug: { + value: false, + kind: OptionKind.API + }, + standardFontDataUrl: { + value: "../web/standard_fonts/", + kind: OptionKind.API + }, + useSystemFonts: { + value: undefined, + kind: OptionKind.API, + type: Type.BOOLEAN + Type.UNDEFINED + }, + verbosity: { + value: 1, + kind: OptionKind.API + }, + workerPort: { + value: null, + kind: OptionKind.WORKER + }, + workerSrc: { + value: "../build/pdf.worker.mjs", + kind: OptionKind.WORKER } +}; +{ + defaultOptions.defaultUrl = { + value: "compressed.tracemonkey-pldi-09.pdf", + kind: OptionKind.VIEWER + }; + defaultOptions.sandboxBundleSrc = { + value: "../build/pdf.sandbox.mjs", + kind: OptionKind.VIEWER + }; + defaultOptions.viewerCssTheme = { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }; + defaultOptions.enableFakeMLManager = { + value: true, + kind: OptionKind.VIEWER + }; } - -;// ./web/text_layer_builder.js - - -class TextLayerBuilder { - #enablePermissions = false; - #onAppend = null; - #renderingDone = false; - #textLayer = null; - static #textLayers = new Map(); - static #selectionChangeAbortController = null; - constructor({ - pdfPage, - highlighter = null, - accessibilityManager = null, - enablePermissions = false, - onAppend = null - }) { - this.pdfPage = pdfPage; - this.highlighter = highlighter; - this.accessibilityManager = accessibilityManager; - this.#enablePermissions = enablePermissions === true; - this.#onAppend = onAppend; - this.div = document.createElement("div"); - this.div.tabIndex = 0; - this.div.className = "textLayer"; - } - async render(viewport, textContentParams = null) { - if (this.#renderingDone && this.#textLayer) { - this.#textLayer.update({ - viewport, - onBefore: this.hide.bind(this) - }); - this.show(); - return; - } - this.cancel(); - this.#textLayer = new TextLayer({ - textContentSource: this.pdfPage.streamTextContent(textContentParams || { - includeMarkedContent: true, - disableNormalization: true - }), - container: this.div, - viewport - }); - const { - textDivs, - textContentItemsStr - } = this.#textLayer; - this.highlighter?.setTextMapping(textDivs, textContentItemsStr); - this.accessibilityManager?.setTextMapping(textDivs); - await this.#textLayer.render(); - this.#renderingDone = true; - const endOfContent = document.createElement("div"); - endOfContent.className = "endOfContent"; - this.div.append(endOfContent); - this.#bindMouse(endOfContent); - this.#onAppend?.(this.div); - this.highlighter?.enable(); - this.accessibilityManager?.enable(); - } - hide() { - if (!this.div.hidden && this.#renderingDone) { - this.highlighter?.disable(); - this.div.hidden = true; - } - } - show() { - if (this.div.hidden && this.#renderingDone) { - this.div.hidden = false; - this.highlighter?.enable(); +{ + defaultOptions.disablePreferences = { + value: false, + kind: OptionKind.VIEWER + }; +} +class AppOptions { + static eventBus; + static #opts = new Map(); + static { + for (const name in defaultOptions) { + this.#opts.set(name, defaultOptions[name].value); + } + for (const [name, value] of compatParams) { + this.#opts.set(name, value); } + this._hasInvokedSet = false; + this._checkDisablePreferences = () => { + if (this.get("disablePreferences")) { + return true; + } + if (this._hasInvokedSet) { + console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.'); + } + return false; + }; } - cancel() { - this.#textLayer?.cancel(); - this.#textLayer = null; - this.highlighter?.disable(); - this.accessibilityManager?.disable(); - TextLayerBuilder.#removeGlobalSelectionListener(this.div); + static get(name) { + return this.#opts.get(name); } - #bindMouse(end) { - const { - div - } = this; - div.addEventListener("mousedown", () => { - div.classList.add("selecting"); - }); - div.addEventListener("copy", event => { - if (!this.#enablePermissions) { - const selection = document.getSelection(); - event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString()))); + static getAll(kind = null, defaultOnly = false) { + const options = Object.create(null); + for (const name in defaultOptions) { + const defaultOpt = defaultOptions[name]; + if (kind && !(kind & defaultOpt.kind)) { + continue; } - stopEvent(event); - }); - TextLayerBuilder.#textLayers.set(div, end); - TextLayerBuilder.#enableGlobalSelectionListener(); - } - static #removeGlobalSelectionListener(textLayerDiv) { - this.#textLayers.delete(textLayerDiv); - if (this.#textLayers.size === 0) { - this.#selectionChangeAbortController?.abort(); - this.#selectionChangeAbortController = null; + options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value; } + return options; } - static #enableGlobalSelectionListener() { - if (this.#selectionChangeAbortController) { - return; - } - this.#selectionChangeAbortController = new AbortController(); - const { - signal - } = this.#selectionChangeAbortController; - const reset = (end, textLayer) => { - textLayer.append(end); - end.style.width = ""; - end.style.height = ""; - textLayer.classList.remove("selecting"); - }; - let isPointerDown = false; - document.addEventListener("pointerdown", () => { - isPointerDown = true; - }, { - signal - }); - document.addEventListener("pointerup", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - window.addEventListener("blur", () => { - isPointerDown = false; - this.#textLayers.forEach(reset); - }, { - signal - }); - document.addEventListener("keyup", () => { - if (!isPointerDown) { - this.#textLayers.forEach(reset); - } - }, { - signal - }); - var isFirefox, prevRange; - document.addEventListener("selectionchange", () => { - const selection = document.getSelection(); - if (selection.rangeCount === 0) { - this.#textLayers.forEach(reset); - return; - } - const activeTextLayers = new Set(); - for (let i = 0; i < selection.rangeCount; i++) { - const range = selection.getRangeAt(i); - for (const textLayerDiv of this.#textLayers.keys()) { - if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) { - activeTextLayers.add(textLayerDiv); - } - } - } - for (const [textLayerDiv, endDiv] of this.#textLayers) { - if (activeTextLayers.has(textLayerDiv)) { - textLayerDiv.classList.add("selecting"); - } else { - reset(endDiv, textLayerDiv); - } - } - isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none"; - if (isFirefox) { - return; - } - const range = selection.getRangeAt(0); - const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0); - let anchor = modifyStart ? range.startContainer : range.endContainer; - if (anchor.nodeType === Node.TEXT_NODE) { - anchor = anchor.parentNode; - } - const parentTextLayer = anchor.parentElement?.closest(".textLayer"); - const endDiv = this.#textLayers.get(parentTextLayer); - if (endDiv) { - endDiv.style.width = parentTextLayer.style.width; - endDiv.style.height = parentTextLayer.style.height; - anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling); - } - prevRange = range.cloneRange(); - }, { - signal + static set(name, value) { + this.setAll({ + [name]: value }); } -} - -;// ./web/pdf_page_view.js - - - - - - - - - - - - - -const DEFAULT_LAYER_PROPERTIES = null; -const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]); -class PDFPageView { - #annotationMode = AnnotationMode.ENABLE_FORMS; - #canvasWrapper = null; - #enableHWA = false; - #hasRestrictedScaling = false; - #isEditing = false; - #layerProperties = null; - #loadingId = null; - #originalViewport = null; - #previousRotation = null; - #scaleRoundX = 1; - #scaleRoundY = 1; - #renderError = null; - #renderingState = RenderingStates.INITIAL; - #textLayerMode = TextLayerMode.ENABLE; - #useThumbnailCanvas = { - directDrawing: true, - initialOptionalContent: true, - regularAnnotations: true - }; - #layers = [null, null, null, null]; - constructor(options) { - const container = options.container; - const defaultViewport = options.defaultViewport; - this.id = options.id; - this.renderingId = "page" + this.id; - this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES; - this.pdfPage = null; - this.pageLabel = null; - this.rotation = 0; - this.scale = options.scale || DEFAULT_SCALE; - this.viewport = defaultViewport; - this.pdfPageRotate = defaultViewport.rotation; - this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; - this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; - this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.imageResourcesPath = options.imageResourcesPath || ""; - this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels"); - this.pageColors = options.pageColors || null; - this.#enableHWA = options.enableHWA || false; - this.eventBus = options.eventBus; - this.renderingQueue = options.renderingQueue; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.renderTask = null; - this.resume = null; - this._isStandalone = !this.renderingQueue?.hasViewer(); - this._container = container; - this._annotationCanvasMap = null; - this.annotationLayer = null; - this.annotationEditorLayer = null; - this.textLayer = null; - this.xfaLayer = null; - this.structTreeLayer = null; - this.drawLayer = null; - const div = document.createElement("div"); - div.className = "page"; - div.setAttribute("data-page-number", this.id); - div.setAttribute("role", "region"); - div.setAttribute("data-l10n-id", "pdfjs-page-landmark"); - div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.id - })); - this.div = div; - this.#setDimensions(); - container?.append(div); - if (this._isStandalone) { - container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS); - if (this.pageColors?.background) { - container?.style.setProperty("--page-bg-color", this.pageColors.background); + static setAll(options, prefs = false) { + this._hasInvokedSet ||= true; + let events; + for (const name in options) { + const defaultOpt = defaultOptions[name], + userOpt = options[name]; + if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) { + continue; } const { - optionalContentConfigPromise - } = options; - if (optionalContentConfigPromise) { - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; - } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; - }); + kind + } = defaultOpt; + if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) { + continue; } - if (!options.l10n) { - this.l10n.translate(this.div); + if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) { + (events ||= new Map()).set(name, userOpt); + } + this.#opts.set(name, userOpt); + } + if (events) { + for (const [name, value] of events) { + this.eventBus.dispatch(name.toLowerCase(), { + source: this, + value + }); } } } - #addLayer(div, name) { - const pos = LAYERS_ORDER.get(name); - const oldDiv = this.#layers[pos]; - this.#layers[pos] = div; - if (oldDiv) { - oldDiv.replaceWith(div); +} + +;// ./web/draw_layer_builder.js + +class DrawLayerBuilder { + #drawLayer = null; + constructor(options) { + this.pageIndex = options.pageIndex; + } + async render(intent = "display") { + if (intent !== "display" || this.#drawLayer || this._cancelled) { return; } - for (let i = pos - 1; i >= 0; i--) { - const layer = this.#layers[i]; - if (layer) { - layer.after(div); - return; - } + this.#drawLayer = new DrawLayer({ + pageIndex: this.pageIndex + }); + } + cancel() { + this._cancelled = true; + if (!this.#drawLayer) { + return; } - this.div.prepend(div); + this.#drawLayer.destroy(); + this.#drawLayer = null; } - get renderingState() { - return this.#renderingState; + setParent(parent) { + this.#drawLayer?.setParent(parent); } - set renderingState(state) { - if (state === this.#renderingState) { - return; + getDrawLayer() { + return this.#drawLayer; + } +} + +;// ./web/struct_tree_layer_builder.js + +const PDF_ROLE_TO_HTML_ROLE = { + Document: null, + DocumentFragment: null, + Part: "group", + Sect: "group", + Div: "group", + Aside: "note", + NonStruct: "none", + P: null, + H: "heading", + Title: null, + FENote: "note", + Sub: "group", + Lbl: null, + Span: null, + Em: null, + Strong: null, + Link: "link", + Annot: "note", + Form: "form", + Ruby: null, + RB: null, + RT: null, + RP: null, + Warichu: null, + WT: null, + WP: null, + L: "list", + LI: "listitem", + LBody: null, + Table: "table", + TR: "row", + TH: "columnheader", + TD: "cell", + THead: "columnheader", + TBody: null, + TFoot: null, + Caption: null, + Figure: "figure", + Formula: null, + Artifact: null +}; +const HEADING_PATTERN = /^H(\d+)$/; +class StructTreeLayerBuilder { + #promise; + #treeDom = null; + #treePromise; + #elementAttributes = new Map(); + #rawDims; + #elementsToAddToTextLayer = null; + constructor(pdfPage, rawDims) { + this.#promise = pdfPage.getStructTree(); + this.#rawDims = rawDims; + } + async render() { + if (this.#treePromise) { + return this.#treePromise; } - this.#renderingState = state; - if (this.#loadingId) { - clearTimeout(this.#loadingId); - this.#loadingId = null; + const { + promise, + resolve, + reject + } = Promise.withResolvers(); + this.#treePromise = promise; + try { + this.#treeDom = this.#walk(await this.#promise); + } catch (ex) { + reject(ex); } - switch (state) { - case RenderingStates.PAUSED: - this.div.classList.remove("loading"); - break; - case RenderingStates.RUNNING: - this.div.classList.add("loadingIcon"); - this.#loadingId = setTimeout(() => { - this.div.classList.add("loading"); - this.#loadingId = null; - }, 0); - break; - case RenderingStates.INITIAL: - case RenderingStates.FINISHED: - this.div.classList.remove("loadingIcon", "loading"); - break; + this.#promise = null; + this.#treeDom?.classList.add("structTree"); + resolve(this.#treeDom); + return promise; + } + async getAriaAttributes(annotationId) { + try { + await this.render(); + return this.#elementAttributes.get(annotationId); + } catch {} + return null; + } + hide() { + if (this.#treeDom && !this.#treeDom.hidden) { + this.#treeDom.hidden = true; } } - #setDimensions() { + show() { + if (this.#treeDom?.hidden) { + this.#treeDom.hidden = false; + } + } + #setAttributes(structElement, htmlElement) { const { - viewport - } = this; - if (this.pdfPage) { - if (this.#previousRotation === viewport.rotation) { - return; + alt, + id, + lang + } = structElement; + if (alt !== undefined) { + let added = false; + const label = removeNullCharacters(alt); + for (const child of structElement.children) { + if (child.type === "annotation") { + let attrs = this.#elementAttributes.get(child.id); + if (!attrs) { + attrs = new Map(); + this.#elementAttributes.set(child.id, attrs); + } + attrs.set("aria-label", label); + added = true; + } + } + if (!added) { + htmlElement.setAttribute("aria-label", label); } - this.#previousRotation = viewport.rotation; } - setLayerDimensions(this.div, viewport, true, false); - } - setPdfPage(pdfPage) { - if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) { - this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight")); + if (id !== undefined) { + htmlElement.setAttribute("aria-owns", id); + } + if (lang !== undefined) { + htmlElement.setAttribute("lang", removeNullCharacters(lang, true)); } - this.pdfPage = pdfPage; - this.pdfPageRotate = pdfPage.rotate; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = pdfPage.getViewport({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - this.reset(); - } - destroy() { - this.reset(); - this.pdfPage?.cleanup(); - } - hasEditableAnnotations() { - return !!this.annotationLayer?.hasEditableAnnotations(); - } - get _textHighlighter() { - return shadow(this, "_textHighlighter", new TextHighlighter({ - pageIndex: this.id - 1, - eventBus: this.eventBus, - findController: this.#layerProperties.findController - })); } - #dispatchLayerRendered(name, error) { - this.eventBus.dispatch(name, { - source: this, - pageNumber: this.id, - error - }); + #addImageInTextLayer(node, element) { + const { + alt, + bbox, + children + } = node; + const child = children?.[0]; + if (!this.#rawDims || !alt || !bbox || child?.type !== "content") { + return false; + } + const { + id + } = child; + if (!id) { + return false; + } + element.setAttribute("aria-owns", id); + const img = document.createElement("span"); + (this.#elementsToAddToTextLayer ||= new Map()).set(id, img); + img.setAttribute("role", "img"); + img.setAttribute("aria-label", removeNullCharacters(alt)); + const { + pageHeight, + pageX, + pageY + } = this.#rawDims; + const calc = "calc(var(--scale-factor)*"; + const { + style + } = img; + style.width = `${calc}${bbox[2] - bbox[0]}px)`; + style.height = `${calc}${bbox[3] - bbox[1]}px)`; + style.left = `${calc}${bbox[0] - pageX}px)`; + style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`; + return true; } - async #renderAnnotationLayer() { - let error = null; - try { - await this.annotationLayer.render(this.viewport, { - structTreeLayer: this.structTreeLayer - }, "display"); - } catch (ex) { - console.error("#renderAnnotationLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationlayerrendered", error); + addElementsToTextLayer() { + if (!this.#elementsToAddToTextLayer) { + return; } - } - async #renderAnnotationEditorLayer() { - let error = null; - try { - await this.annotationEditorLayer.render(this.viewport, "display"); - } catch (ex) { - console.error("#renderAnnotationEditorLayer:", ex); - error = ex; - } finally { - this.#dispatchLayerRendered("annotationeditorlayerrendered", error); + for (const [id, img] of this.#elementsToAddToTextLayer) { + document.getElementById(id)?.append(img); } + this.#elementsToAddToTextLayer.clear(); + this.#elementsToAddToTextLayer = null; } - async #renderDrawLayer() { - try { - await this.drawLayer.render("display"); - } catch (ex) { - console.error("#renderDrawLayer:", ex); + #walk(node) { + if (!node) { + return null; } - } - async #renderXfaLayer() { - let error = null; - try { - const result = await this.xfaLayer.render(this.viewport, "display"); - if (result?.textDivs && this._textHighlighter) { - this.#buildXfaTextContentItems(result.textDivs); + const element = document.createElement("span"); + if ("role" in node) { + const { + role + } = node; + const match = role.match(HEADING_PATTERN); + if (match) { + element.setAttribute("role", "heading"); + element.setAttribute("aria-level", match[1]); + } else if (PDF_ROLE_TO_HTML_ROLE[role]) { + element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); } - } catch (ex) { - console.error("#renderXfaLayer:", ex); - error = ex; - } finally { - if (this.xfaLayer?.div) { - this.l10n.pause(); - this.#addLayer(this.xfaLayer.div, "xfaLayer"); - this.l10n.resume(); + if (role === "Figure" && this.#addImageInTextLayer(node, element)) { + return element; + } + } + this.#setAttributes(node, element); + if (node.children) { + if (node.children.length === 1 && "id" in node.children[0]) { + this.#setAttributes(node.children[0], element); + } else { + for (const kid of node.children) { + element.append(this.#walk(kid)); + } } - this.#dispatchLayerRendered("xfalayerrendered", error); } + return element; } - async #renderTextLayer() { - if (!this.textLayer) { - return; +} + +;// ./web/text_accessibility.js + +class TextAccessibilityManager { + #enabled = false; + #textChildren = null; + #textNodes = new Map(); + #waitingElements = new Map(); + setTextMapping(textDivs) { + this.#textChildren = textDivs; + } + static #compareElementPositions(e1, e2) { + const rect1 = e1.getBoundingClientRect(); + const rect2 = e2.getBoundingClientRect(); + if (rect1.width === 0 && rect1.height === 0) { + return +1; } - let error = null; - try { - await this.textLayer.render(this.viewport); - } catch (ex) { - if (ex instanceof AbortException) { - return; - } - console.error("#renderTextLayer:", ex); - error = ex; + if (rect2.width === 0 && rect2.height === 0) { + return -1; } - this.#dispatchLayerRendered("textlayerrendered", error); - this.#renderStructTreeLayer(); + const top1 = rect1.y; + const bot1 = rect1.y + rect1.height; + const mid1 = rect1.y + rect1.height / 2; + const top2 = rect2.y; + const bot2 = rect2.y + rect2.height; + const mid2 = rect2.y + rect2.height / 2; + if (mid1 <= top2 && mid2 >= bot1) { + return -1; + } + if (mid2 <= top1 && mid1 >= bot2) { + return +1; + } + const centerX1 = rect1.x + rect1.width / 2; + const centerX2 = rect2.x + rect2.width / 2; + return centerX1 - centerX2; } - async #renderStructTreeLayer() { - if (!this.textLayer) { - return; + enable() { + if (this.#enabled) { + throw new Error("TextAccessibilityManager is already enabled."); } - const treeDom = await this.structTreeLayer?.render(); - if (treeDom) { - this.l10n.pause(); - this.structTreeLayer?.addElementsToTextLayer(); - if (this.canvas && treeDom.parentNode !== this.canvas) { - this.canvas.append(treeDom); + if (!this.#textChildren) { + throw new Error("Text divs and strings have not been set."); + } + this.#enabled = true; + this.#textChildren = this.#textChildren.slice(); + this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions); + if (this.#textNodes.size > 0) { + const textChildren = this.#textChildren; + for (const [id, nodeIndex] of this.#textNodes) { + const element = document.getElementById(id); + if (!element) { + this.#textNodes.delete(id); + continue; + } + this.#addIdToAriaOwns(id, textChildren[nodeIndex]); } - this.l10n.resume(); } - this.structTreeLayer?.show(); + for (const [element, isRemovable] of this.#waitingElements) { + this.addPointerInTextLayer(element, isRemovable); + } + this.#waitingElements.clear(); } - async #buildXfaTextContentItems(textDivs) { - const text = await this.pdfPage.getTextContent(); - const items = []; - for (const item of text.items) { - items.push(item.str); + disable() { + if (!this.#enabled) { + return; } - this._textHighlighter.setTextMapping(textDivs, items); - this._textHighlighter.enable(); + this.#waitingElements.clear(); + this.#textChildren = null; + this.#enabled = false; } - #resetCanvas() { + removePointerInTextLayer(element) { + if (!this.#enabled) { + this.#waitingElements.delete(element); + return; + } + const children = this.#textChildren; + if (!children || children.length === 0) { + return; + } const { - canvas - } = this; - if (!canvas) { + id + } = element; + const nodeIndex = this.#textNodes.get(id); + if (nodeIndex === undefined) { return; } - canvas.remove(); - canvas.width = canvas.height = 0; - this.canvas = null; - this.#originalViewport = null; - } - reset({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - keepCanvasWrapper = false - } = {}) { - this.cancelRendering({ - keepAnnotationLayer, - keepAnnotationEditorLayer, - keepXfaLayer, - keepTextLayer - }); - this.renderingState = RenderingStates.INITIAL; - const div = this.div; - const childNodes = div.childNodes, - annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, - annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null, - xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null, - textLayerNode = keepTextLayer && this.textLayer?.div || null, - canvasWrapperNode = keepCanvasWrapper && this.#canvasWrapper || null; - for (let i = childNodes.length - 1; i >= 0; i--) { - const node = childNodes[i]; - switch (node) { - case annotationLayerNode: - case annotationEditorLayerNode: - case xfaLayerNode: - case textLayerNode: - case canvasWrapperNode: - continue; - } - node.remove(); - const layerIndex = this.#layers.indexOf(node); - if (layerIndex >= 0) { - this.#layers[layerIndex] = null; + const node = children[nodeIndex]; + this.#textNodes.delete(id); + let owns = node.getAttribute("aria-owns"); + if (owns?.includes(id)) { + owns = owns.split(" ").filter(x => x !== id).join(" "); + if (owns) { + node.setAttribute("aria-owns", owns); + } else { + node.removeAttribute("aria-owns"); + node.setAttribute("role", "presentation"); } } - div.removeAttribute("data-loaded"); - if (annotationLayerNode) { - this.annotationLayer.hide(); + } + #addIdToAriaOwns(id, node) { + const owns = node.getAttribute("aria-owns"); + if (!owns?.includes(id)) { + node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id); } - if (annotationEditorLayerNode) { - this.annotationEditorLayer.hide(); + node.removeAttribute("role"); + } + addPointerInTextLayer(element, isRemovable) { + const { + id + } = element; + if (!id) { + return null; } - if (xfaLayerNode) { - this.xfaLayer.hide(); + if (!this.#enabled) { + this.#waitingElements.set(element, isRemovable); + return null; } - if (textLayerNode) { - this.textLayer.hide(); + if (isRemovable) { + this.removePointerInTextLayer(element); } - this.structTreeLayer?.hide(); - if (!keepCanvasWrapper && this.#canvasWrapper) { - this.#canvasWrapper = null; - this.#resetCanvas(); + const children = this.#textChildren; + if (!children || children.length === 0) { + return null; } + const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0); + const nodeIndex = Math.max(0, index - 1); + const child = children[nodeIndex]; + this.#addIdToAriaOwns(id, child); + this.#textNodes.set(id, nodeIndex); + const parent = child.parentNode; + return parent?.classList.contains("markedContent") ? parent.id : null; } - toggleEditingMode(isEditing) { - if (!this.hasEditableAnnotations()) { - return; + moveElementInDOM(container, element, contentElement, isRemovable) { + const id = this.addPointerInTextLayer(contentElement, isRemovable); + if (!container.hasChildNodes()) { + container.append(element); + return id; } - this.#isEditing = isEditing; - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); + const children = Array.from(container.childNodes).filter(node => node !== element); + if (children.length === 0) { + return id; + } + const elementToCompare = contentElement || element; + const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0); + if (index === 0) { + children[0].before(element); + } else { + children[index - 1].after(element); + } + return id; } - update({ - scale = 0, - rotation = null, - optionalContentConfigPromise = null, - drawingDelay = -1 +} + +;// ./web/text_highlighter.js +class TextHighlighter { + #eventAbortController = null; + constructor({ + findController, + eventBus, + pageIndex }) { - this.scale = scale || this.scale; - if (typeof rotation === "number") { - this.rotation = rotation; + this.findController = findController; + this.matches = []; + this.eventBus = eventBus; + this.pageIdx = pageIndex; + this.textDivs = null; + this.textContentItemsStr = null; + this.enabled = false; + } + setTextMapping(divs, texts) { + this.textDivs = divs; + this.textContentItemsStr = texts; + } + enable() { + if (!this.textDivs || !this.textContentItemsStr) { + throw new Error("Text divs and strings have not been set."); } - if (optionalContentConfigPromise instanceof Promise) { - this._optionalContentConfigPromise = optionalContentConfigPromise; - optionalContentConfigPromise.then(optionalContentConfig => { - if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { - return; + if (this.enabled) { + throw new Error("TextHighlighter is already enabled."); + } + this.enabled = true; + if (!this.#eventAbortController) { + this.#eventAbortController = new AbortController(); + this.eventBus._on("updatetextlayermatches", evt => { + if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) { + this._updateMatches(); } - this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; + }, { + signal: this.#eventAbortController.signal }); } - this.#useThumbnailCanvas.directDrawing = true; - const totalRotation = (this.rotation + this.pdfPageRotate) % 360; - this.viewport = this.viewport.clone({ - scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, - rotation: totalRotation - }); - this.#setDimensions(); - if (this._isStandalone) { - this._container?.style.setProperty("--scale-factor", this.viewport.scale); + this._updateMatches(); + } + disable() { + if (!this.enabled) { + return; } - if (this.canvas) { - let onlyCssZoom = false; - if (this.#hasRestrictedScaling) { - if (this.maxCanvasPixels === 0) { - onlyCssZoom = true; - } else if (this.maxCanvasPixels > 0) { - const { - width, - height - } = this.viewport; - const { - sx, - sy - } = this.outputScale; - onlyCssZoom = (Math.floor(width) * sx | 0) * (Math.floor(height) * sy | 0) > this.maxCanvasPixels; - } + this.enabled = false; + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + this._updateMatches(true); + } + _convertMatches(matches, matchesLength) { + if (!matches) { + return []; + } + const { + textContentItemsStr + } = this; + let i = 0, + iIndex = 0; + const end = textContentItemsStr.length - 1; + const result = []; + for (let m = 0, mm = matches.length; m < mm; m++) { + let matchIdx = matches[m]; + while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) { + iIndex += textContentItemsStr[i].length; + i++; } - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - if (postponeDrawing || onlyCssZoom) { - if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) { - this.cancelRendering({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - cancelExtraDelay: drawingDelay - }); - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.directDrawing = false; - } - this.cssTransform({ - redrawAnnotationLayer: true, - redrawAnnotationEditorLayer: true, - redrawXfaLayer: true, - redrawTextLayer: !postponeDrawing, - hideTextLayer: postponeDrawing - }); - if (postponeDrawing) { - return; + if (i === textContentItemsStr.length) { + console.error("Could not find a matching mapping"); + } + const match = { + begin: { + divIdx: i, + offset: matchIdx - iIndex } - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: true, - timestamp: performance.now(), - error: this.#renderError - }); - return; + }; + matchIdx += matchesLength[m]; + while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { + iIndex += textContentItemsStr[i].length; + i++; } + match.end = { + divIdx: i, + offset: matchIdx - iIndex + }; + result.push(match); } - this.cssTransform({}); - this.reset({ - keepAnnotationLayer: true, - keepAnnotationEditorLayer: true, - keepXfaLayer: true, - keepTextLayer: true, - keepCanvasWrapper: true - }); + return result; } - cancelRendering({ - keepAnnotationLayer = false, - keepAnnotationEditorLayer = false, - keepXfaLayer = false, - keepTextLayer = false, - cancelExtraDelay = 0 - } = {}) { - if (this.renderTask) { - this.renderTask.cancel(cancelExtraDelay); - this.renderTask = null; - } - this.resume = null; - if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) { - this.textLayer.cancel(); - this.textLayer = null; - } - if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { - this.annotationLayer.cancel(); - this.annotationLayer = null; - this._annotationCanvasMap = null; - } - if (this.structTreeLayer && !this.textLayer) { - this.structTreeLayer = null; - } - if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) { - if (this.drawLayer) { - this.drawLayer.cancel(); - this.drawLayer = null; - } - this.annotationEditorLayer.cancel(); - this.annotationEditorLayer = null; - } - if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { - this.xfaLayer.cancel(); - this.xfaLayer = null; - this._textHighlighter?.disable(); + _renderMatches(matches) { + if (matches.length === 0) { + return; } - } - cssTransform({ - redrawAnnotationLayer = false, - redrawAnnotationEditorLayer = false, - redrawXfaLayer = false, - redrawTextLayer = false, - hideTextLayer = false - }) { const { - canvas + findController, + pageIdx + } = this; + const { + textContentItemsStr, + textDivs } = this; - if (!canvas) { - return; + const isSelectedPage = pageIdx === findController.selected.pageIdx; + const selectedMatchIdx = findController.selected.matchIdx; + const highlightAll = findController.state.highlightAll; + let prevEnd = null; + const infinity = { + divIdx: -1, + offset: undefined + }; + function beginText(begin, className) { + const divIdx = begin.divIdx; + textDivs[divIdx].textContent = ""; + return appendTextToDiv(divIdx, 0, begin.offset, className); } - const originalViewport = this.#originalViewport; - if (this.viewport !== originalViewport) { - const relativeRotation = (360 + this.viewport.rotation - originalViewport.rotation) % 360; - if (relativeRotation === 90 || relativeRotation === 270) { - const { - width, - height - } = this.viewport; - const scaleX = height / width; - const scaleY = width / height; - canvas.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX},${scaleY})`; - } else { - canvas.style.transform = relativeRotation === 0 ? "" : `rotate(${relativeRotation}deg)`; + function appendTextToDiv(divIdx, fromOffset, toOffset, className) { + let div = textDivs[divIdx]; + if (div.nodeType === Node.TEXT_NODE) { + const span = document.createElement("span"); + div.before(span); + span.append(div); + textDivs[divIdx] = span; + div = span; } - } - if (redrawAnnotationLayer && this.annotationLayer) { - this.#renderAnnotationLayer(); - } - if (redrawAnnotationEditorLayer && this.annotationEditorLayer) { - if (this.drawLayer) { - this.#renderDrawLayer(); + const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset); + const node = document.createTextNode(content); + if (className) { + const span = document.createElement("span"); + span.className = `${className} appended`; + span.append(node); + div.append(span); + if (className.includes("selected")) { + const { + left + } = span.getClientRects()[0]; + const parentLeft = div.getBoundingClientRect().left; + return left - parentLeft; + } + return 0; } - this.#renderAnnotationEditorLayer(); + div.append(node); + return 0; } - if (redrawXfaLayer && this.xfaLayer) { - this.#renderXfaLayer(); + let i0 = selectedMatchIdx, + i1 = i0 + 1; + if (highlightAll) { + i0 = 0; + i1 = matches.length; + } else if (!isSelectedPage) { + return; } - if (this.textLayer) { - if (hideTextLayer) { - this.textLayer.hide(); - this.structTreeLayer?.hide(); - } else if (redrawTextLayer) { - this.#renderTextLayer(); + let lastDivIdx = -1; + let lastOffset = -1; + for (let i = i0; i < i1; i++) { + const match = matches[i]; + const begin = match.begin; + if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) { + continue; + } + lastDivIdx = begin.divIdx; + lastOffset = begin.offset; + const end = match.end; + const isSelected = isSelectedPage && i === selectedMatchIdx; + const highlightSuffix = isSelected ? " selected" : ""; + let selectedLeft = 0; + if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { + if (prevEnd !== null) { + appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); + } + beginText(begin); + } else { + appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); + } + if (begin.divIdx === end.divIdx) { + selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); + } else { + selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); + for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { + textDivs[n0].className = "highlight middle" + highlightSuffix; + } + beginText(end, "highlight end" + highlightSuffix); + } + prevEnd = end; + if (isSelected) { + findController.scrollMatchIntoView({ + element: textDivs[begin.divIdx], + selectedLeft, + pageIndex: pageIdx, + matchIndex: selectedMatchIdx + }); } } - } - get width() { - return this.viewport.width; - } - get height() { - return this.viewport.height; - } - getPagePoint(x, y) { - return this.viewport.convertToPdfPoint(x, y); - } - async #finishRenderTask(renderTask, error = null) { - if (renderTask === this.renderTask) { - this.renderTask = null; - } - if (error instanceof RenderingCancelledException) { - this.#renderError = null; - return; - } - this.#renderError = error; - this.renderingState = RenderingStates.FINISHED; - this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots; - this.eventBus.dispatch("pagerendered", { - source: this, - pageNumber: this.id, - cssTransform: false, - timestamp: performance.now(), - error: this.#renderError - }); - if (error) { - throw error; + if (prevEnd) { + appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); } } - async draw() { - if (this.renderingState !== RenderingStates.INITIAL) { - console.error("Must be in new state before drawing"); - this.reset(); + _updateMatches(reset = false) { + if (!this.enabled && !reset) { + return; } const { - div, - l10n, - pageColors, - pdfPage, - viewport + findController, + matches, + pageIdx } = this; - if (!pdfPage) { - this.renderingState = RenderingStates.FINISHED; - throw new Error("pdfPage is not loaded"); - } - this.renderingState = RenderingStates.RUNNING; - let canvasWrapper = this.#canvasWrapper; - if (!canvasWrapper) { - canvasWrapper = this.#canvasWrapper = document.createElement("div"); - canvasWrapper.classList.add("canvasWrapper"); - this.#addLayer(canvasWrapper, "canvasWrapper"); + const { + textContentItemsStr, + textDivs + } = this; + let clearedUntilDivIdx = -1; + for (const match of matches) { + const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); + for (let n = begin, end = match.end.divIdx; n <= end; n++) { + const div = textDivs[n]; + div.textContent = textContentItemsStr[n]; + div.className = ""; + } + clearedUntilDivIdx = match.end.divIdx + 1; } - if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) { - this._accessibilityManager ||= new TextAccessibilityManager(); - this.textLayer = new TextLayerBuilder({ - pdfPage, - highlighter: this._textHighlighter, - accessibilityManager: this._accessibilityManager, - enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS, - onAppend: textLayerDiv => { - this.l10n.pause(); - this.#addLayer(textLayerDiv, "textLayer"); - this.l10n.resume(); - } - }); + if (!findController?.highlightMatches || reset) { + return; } - if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) { - const { - annotationStorage, - annotationEditorUIManager, - downloadManager, - enableScripting, - fieldObjectsPromise, - hasJSActionsPromise, - linkService - } = this.#layerProperties; - this._annotationCanvasMap ||= new Map(); - this.annotationLayer = new AnnotationLayerBuilder({ - pdfPage, - annotationStorage, - imageResourcesPath: this.imageResourcesPath, - renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS, - linkService, - downloadManager, - enableScripting, - hasJSActionsPromise, - fieldObjectsPromise, - annotationCanvasMap: this._annotationCanvasMap, - accessibilityManager: this._accessibilityManager, - annotationEditorUIManager, - onAppend: annotationLayerDiv => { - this.#addLayer(annotationLayerDiv, "annotationLayer"); - } + const pageMatches = findController.pageMatches[pageIdx] || null; + const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null; + this.matches = this._convertMatches(pageMatches, pageMatchesLength); + this._renderMatches(this.matches); + } +} + +;// ./web/text_layer_builder.js + + +class TextLayerBuilder { + #enablePermissions = false; + #onAppend = null; + #renderingDone = false; + #textLayer = null; + static #textLayers = new Map(); + static #selectionChangeAbortController = null; + constructor({ + pdfPage, + highlighter = null, + accessibilityManager = null, + enablePermissions = false, + onAppend = null + }) { + this.pdfPage = pdfPage; + this.highlighter = highlighter; + this.accessibilityManager = accessibilityManager; + this.#enablePermissions = enablePermissions === true; + this.#onAppend = onAppend; + this.div = document.createElement("div"); + this.div.tabIndex = 0; + this.div.className = "textLayer"; + } + async render(viewport, textContentParams = null) { + if (this.#renderingDone && this.#textLayer) { + this.#textLayer.update({ + viewport, + onBefore: this.hide.bind(this) }); + this.show(); + return; } - const renderContinueCallback = cont => { - showCanvas?.(false); - if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) { - this.renderingState = RenderingStates.PAUSED; - this.resume = () => { - this.renderingState = RenderingStates.RUNNING; - cont(); - }; - return; - } - cont(); - }; + this.cancel(); + this.#textLayer = new TextLayer({ + textContentSource: this.pdfPage.streamTextContent(textContentParams || { + includeMarkedContent: true, + disableNormalization: true + }), + container: this.div, + viewport + }); const { - width, - height - } = viewport; - const canvas = document.createElement("canvas"); - canvas.setAttribute("role", "presentation"); - const hasHCM = !!(pageColors?.background && pageColors?.foreground); - const prevCanvas = this.canvas; - const updateOnFirstShow = !prevCanvas && !hasHCM; - this.canvas = canvas; - this.#originalViewport = viewport; - let showCanvas = isLastShow => { - if (updateOnFirstShow) { - canvasWrapper.prepend(canvas); - showCanvas = null; - return; - } - if (!isLastShow) { - return; - } - if (prevCanvas) { - prevCanvas.replaceWith(canvas); - prevCanvas.width = prevCanvas.height = 0; - } else { - canvasWrapper.prepend(canvas); - } - showCanvas = null; - }; - const ctx = canvas.getContext("2d", { - alpha: false, - willReadFrequently: !this.#enableHWA + textDivs, + textContentItemsStr + } = this.#textLayer; + this.highlighter?.setTextMapping(textDivs, textContentItemsStr); + this.accessibilityManager?.setTextMapping(textDivs); + await this.#textLayer.render(); + this.#renderingDone = true; + const endOfContent = document.createElement("div"); + endOfContent.className = "endOfContent"; + this.div.append(endOfContent); + this.#bindMouse(endOfContent); + this.#onAppend?.(this.div); + this.highlighter?.enable(); + this.accessibilityManager?.enable(); + } + hide() { + if (!this.div.hidden && this.#renderingDone) { + this.highlighter?.disable(); + this.div.hidden = true; + } + } + show() { + if (this.div.hidden && this.#renderingDone) { + this.div.hidden = false; + this.highlighter?.enable(); + } + } + cancel() { + this.#textLayer?.cancel(); + this.#textLayer = null; + this.highlighter?.disable(); + this.accessibilityManager?.disable(); + TextLayerBuilder.#removeGlobalSelectionListener(this.div); + } + #bindMouse(end) { + const { + div + } = this; + div.addEventListener("mousedown", () => { + div.classList.add("selecting"); }); - const outputScale = this.outputScale = new OutputScale(); - if (this.maxCanvasPixels === 0) { - const invScale = 1 / this.scale; - outputScale.sx *= invScale; - outputScale.sy *= invScale; - this.#hasRestrictedScaling = true; - } else if (this.maxCanvasPixels > 0) { - const pixelsInViewport = width * height; - const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); - if (outputScale.sx > maxScale || outputScale.sy > maxScale) { - outputScale.sx = maxScale; - outputScale.sy = maxScale; - this.#hasRestrictedScaling = true; - } else { - this.#hasRestrictedScaling = false; + div.addEventListener("copy", event => { + if (!this.#enablePermissions) { + const selection = document.getSelection(); + event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString()))); } + stopEvent(event); + }); + TextLayerBuilder.#textLayers.set(div, end); + TextLayerBuilder.#enableGlobalSelectionListener(); + } + static #removeGlobalSelectionListener(textLayerDiv) { + this.#textLayers.delete(textLayerDiv); + if (this.#textLayers.size === 0) { + this.#selectionChangeAbortController?.abort(); + this.#selectionChangeAbortController = null; } - const sfx = approximateFraction(outputScale.sx); - const sfy = approximateFraction(outputScale.sy); - const canvasWidth = canvas.width = floorToDivide(calcRound(width * outputScale.sx), sfx[0]); - const canvasHeight = canvas.height = floorToDivide(calcRound(height * outputScale.sy), sfy[0]); - const pageWidth = floorToDivide(calcRound(width), sfx[1]); - const pageHeight = floorToDivide(calcRound(height), sfy[1]); - outputScale.sx = canvasWidth / pageWidth; - outputScale.sy = canvasHeight / pageHeight; - if (this.#scaleRoundX !== sfx[1]) { - div.style.setProperty("--scale-round-x", `${sfx[1]}px`); - this.#scaleRoundX = sfx[1]; - } - if (this.#scaleRoundY !== sfy[1]) { - div.style.setProperty("--scale-round-y", `${sfy[1]}px`); - this.#scaleRoundY = sfy[1]; + } + static #enableGlobalSelectionListener() { + if (this.#selectionChangeAbortController) { + return; } - const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; - const renderContext = { - canvasContext: ctx, - transform, - viewport, - annotationMode: this.#annotationMode, - optionalContentConfigPromise: this._optionalContentConfigPromise, - annotationCanvasMap: this._annotationCanvasMap, - pageColors, - isEditing: this.#isEditing + this.#selectionChangeAbortController = new AbortController(); + const { + signal + } = this.#selectionChangeAbortController; + const reset = (end, textLayer) => { + textLayer.append(end); + end.style.width = ""; + end.style.height = ""; + textLayer.classList.remove("selecting"); }; - const renderTask = this.renderTask = pdfPage.render(renderContext); - renderTask.onContinue = renderContinueCallback; - const resultPromise = renderTask.promise.then(async () => { - showCanvas?.(true); - await this.#finishRenderTask(renderTask); - this.structTreeLayer ||= new StructTreeLayerBuilder(pdfPage, viewport.rawDims); - this.#renderTextLayer(); - if (this.annotationLayer) { - await this.#renderAnnotationLayer(); + let isPointerDown = false; + document.addEventListener("pointerdown", () => { + isPointerDown = true; + }, { + signal + }); + document.addEventListener("pointerup", () => { + isPointerDown = false; + this.#textLayers.forEach(reset); + }, { + signal + }); + window.addEventListener("blur", () => { + isPointerDown = false; + this.#textLayers.forEach(reset); + }, { + signal + }); + document.addEventListener("keyup", () => { + if (!isPointerDown) { + this.#textLayers.forEach(reset); } - const { - annotationEditorUIManager - } = this.#layerProperties; - if (!annotationEditorUIManager) { + }, { + signal + }); + var isFirefox, prevRange; + document.addEventListener("selectionchange", () => { + const selection = document.getSelection(); + if (selection.rangeCount === 0) { + this.#textLayers.forEach(reset); return; } - this.drawLayer ||= new DrawLayerBuilder({ - pageIndex: this.id - }); - await this.#renderDrawLayer(); - this.drawLayer.setParent(canvasWrapper); - this.annotationEditorLayer ||= new AnnotationEditorLayerBuilder({ - uiManager: annotationEditorUIManager, - pdfPage, - l10n, - structTreeLayer: this.structTreeLayer, - accessibilityManager: this._accessibilityManager, - annotationLayer: this.annotationLayer?.annotationLayer, - textLayer: this.textLayer, - drawLayer: this.drawLayer.getDrawLayer(), - onAppend: annotationEditorLayerDiv => { - this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer"); + const activeTextLayers = new Set(); + for (let i = 0; i < selection.rangeCount; i++) { + const range = selection.getRangeAt(i); + for (const textLayerDiv of this.#textLayers.keys()) { + if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) { + activeTextLayers.add(textLayerDiv); + } } - }); - this.#renderAnnotationEditorLayer(); - }, error => { - if (!(error instanceof RenderingCancelledException)) { - showCanvas?.(true); - } else { - prevCanvas?.remove(); - this.#resetCanvas(); } - return this.#finishRenderTask(renderTask, error); - }); - if (pdfPage.isPureXfa) { - if (!this.xfaLayer) { - const { - annotationStorage, - linkService - } = this.#layerProperties; - this.xfaLayer = new XfaLayerBuilder({ - pdfPage, - annotationStorage, - linkService - }); + for (const [textLayerDiv, endDiv] of this.#textLayers) { + if (activeTextLayers.has(textLayerDiv)) { + textLayerDiv.classList.add("selecting"); + } else { + reset(endDiv, textLayerDiv); + } + } + isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none"; + if (isFirefox) { + return; + } + const range = selection.getRangeAt(0); + const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0); + let anchor = modifyStart ? range.startContainer : range.endContainer; + if (anchor.nodeType === Node.TEXT_NODE) { + anchor = anchor.parentNode; } - this.#renderXfaLayer(); - } - div.setAttribute("data-loaded", true); - this.eventBus.dispatch("pagerender", { - source: this, - pageNumber: this.id + const parentTextLayer = anchor.parentElement?.closest(".textLayer"); + const endDiv = this.#textLayers.get(parentTextLayer); + if (endDiv) { + endDiv.style.width = parentTextLayer.style.width; + endDiv.style.height = parentTextLayer.style.height; + anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling); + } + prevRange = range.cloneRange(); + }, { + signal }); - return resultPromise; } - setPageLabel(label) { - this.pageLabel = typeof label === "string" ? label : null; - this.div.setAttribute("data-l10n-args", JSON.stringify({ - page: this.pageLabel ?? this.id - })); - if (this.pageLabel !== null) { - this.div.setAttribute("data-page-label", this.pageLabel); - } else { - this.div.removeAttribute("data-page-label"); +} + +;// ./web/xfa_layer_builder.js + +class XfaLayerBuilder { + constructor({ + pdfPage, + annotationStorage = null, + linkService, + xfaHtml = null + }) { + this.pdfPage = pdfPage; + this.annotationStorage = annotationStorage; + this.linkService = linkService; + this.xfaHtml = xfaHtml; + this.div = null; + this._cancelled = false; + } + async render(viewport, intent = "display") { + if (intent === "print") { + const parameters = { + viewport: viewport.clone({ + dontFlip: true + }), + div: this.div, + xfaHtml: this.xfaHtml, + annotationStorage: this.annotationStorage, + linkService: this.linkService, + intent + }; + this.div = document.createElement("div"); + parameters.div = this.div; + return XfaLayer.render(parameters); + } + const xfaHtml = await this.pdfPage.getXfa(); + if (this._cancelled || !xfaHtml) { + return { + textDivs: [] + }; + } + const parameters = { + viewport: viewport.clone({ + dontFlip: true + }), + div: this.div, + xfaHtml, + annotationStorage: this.annotationStorage, + linkService: this.linkService, + intent + }; + if (this.div) { + return XfaLayer.update(parameters); } + this.div = document.createElement("div"); + parameters.div = this.div; + return XfaLayer.render(parameters); } - get thumbnailCanvas() { - const { - directDrawing, - initialOptionalContent, - regularAnnotations - } = this.#useThumbnailCanvas; - return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null; + cancel() { + this._cancelled = true; + } + hide() { + if (!this.div) { + return; + } + this.div.hidden = true; } } -;// ./web/pdf_viewer.js +;// ./web/pdf_page_view.js -const DEFAULT_CACHE_SIZE = 10; -const PagesCountLimit = { - FORCE_SCROLL_MODE_PAGE: 10000, - FORCE_LAZY_PAGE_INIT: 5000, - PAUSE_EAGER_PAGE_INIT: 250 -}; -function isValidAnnotationEditorMode(mode) { - return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE; -} -class PDFPageViewBuffer { - #buf = new Set(); - #size = 0; - constructor(size) { - this.#size = size; - } - push(view) { - const buf = this.#buf; - if (buf.has(view)) { - buf.delete(view); - } - buf.add(view); - if (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - resize(newSize, idsToKeep = null) { - this.#size = newSize; - const buf = this.#buf; - if (idsToKeep) { - const ii = buf.size; - let i = 1; - for (const view of buf) { - if (idsToKeep.has(view.id)) { - buf.delete(view); - buf.add(view); - } - if (++i > ii) { - break; - } - } - } - while (buf.size > this.#size) { - this.#destroyFirstView(); - } - } - has(view) { - return this.#buf.has(view); - } - [Symbol.iterator]() { - return this.#buf.keys(); - } - #destroyFirstView() { - const firstView = this.#buf.keys().next().value; - firstView?.destroy(); - this.#buf.delete(firstView); + + + + + + + +const DEFAULT_LAYER_PROPERTIES = { + annotationEditorUIManager: null, + annotationStorage: null, + downloadManager: null, + enableScripting: false, + fieldObjectsPromise: null, + findController: null, + hasJSActionsPromise: null, + get linkService() { + return new SimpleLinkService(); } -} -class PDFViewer { - #buffer = null; - #altTextManager = null; - #annotationEditorHighlightColors = null; - #annotationEditorMode = AnnotationEditorType.NONE; - #annotationEditorUIManager = null; +}; +const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]); +class PDFPageView { #annotationMode = AnnotationMode.ENABLE_FORMS; - #containerTopLeft = null; - #editorUndoBar = null; + #canvasWrapper = null; #enableHWA = false; - #enableHighlightFloatingButton = false; - #enablePermissions = false; - #enableUpdatedAddImage = false; - #enableNewAltTextWhenAddingImage = false; - #eventAbortController = null; - #mlManager = null; - #switchAnnotationEditorModeAC = null; - #switchAnnotationEditorModeTimeoutId = null; - #getAllTextInProgress = false; - #hiddenCopyElement = null; - #interruptCopyCondition = false; - #previousContainerHeight = 0; - #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); - #scrollModePageState = null; - #scaleTimeoutId = null; - #supportsPinchToZoom = true; + #hasRestrictedScaling = false; + #isEditing = false; + #layerProperties = null; + #loadingId = null; + #originalViewport = null; + #previousRotation = null; + #scaleRoundX = 1; + #scaleRoundY = 1; + #renderError = null; + #renderingState = RenderingStates.INITIAL; #textLayerMode = TextLayerMode.ENABLE; + #useThumbnailCanvas = { + directDrawing: true, + initialOptionalContent: true, + regularAnnotations: true + }; + #layers = [null, null, null, null]; constructor(options) { - const viewerVersion = "4.10.38"; - if (version !== viewerVersion) { - throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`); - } - this.container = options.container; - this.viewer = options.viewer || options.container.firstElementChild; - if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") { - throw new Error("Invalid `container` and/or `viewer` option."); - } - if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { - throw new Error("The `container` must be absolutely positioned."); - } - this.#resizeObserver.observe(this.container); - this.eventBus = options.eventBus; - this.linkService = options.linkService || new SimpleLinkService(); - this.downloadManager = options.downloadManager || null; - this.findController = options.findController || null; - this.#altTextManager = options.altTextManager || null; - this.#editorUndoBar = options.editorUndoBar || null; - if (this.findController) { - this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber); - } - this._scriptingManager = options.scriptingManager || null; + const container = options.container; + const defaultViewport = options.defaultViewport; + this.id = options.id; + this.renderingId = "page" + this.id; + this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES; + this.pdfPage = null; + this.pageLabel = null; + this.rotation = 0; + this.scale = options.scale || DEFAULT_SCALE; + this.viewport = defaultViewport; + this.pdfPageRotate = defaultViewport.rotation; + this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; - this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE; - this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null; - this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true; - this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true; - this.#enableNewAltTextWhenAddingImage = options.enableNewAltTextWhenAddingImage === true; this.imageResourcesPath = options.imageResourcesPath || ""; - this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; - this.removePageBorders = options.removePageBorders || false; - this.maxCanvasPixels = options.maxCanvasPixels; - this.l10n = options.l10n; - this.l10n ||= new genericl10n_GenericL10n(); - this.#enablePermissions = options.enablePermissions || false; + this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels"); this.pageColors = options.pageColors || null; - this.#mlManager = options.mlManager || null; this.#enableHWA = options.enableHWA || false; - this.#supportsPinchToZoom = options.supportsPinchToZoom !== false; - this.defaultRenderingQueue = !options.renderingQueue; - if (this.defaultRenderingQueue) { - this.renderingQueue = new PDFRenderingQueue(); - this.renderingQueue.setViewer(this); - } else { - this.renderingQueue = options.renderingQueue; - } - const { - abortSignal - } = options; - abortSignal?.addEventListener("abort", () => { - this.#resizeObserver.disconnect(); - this.#resizeObserver = null; - }, { - once: true - }); - this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal); - this.presentationModeState = PresentationModeState.UNKNOWN; - this._resetView(); - if (this.removePageBorders) { - this.viewer.classList.add("removePageBorders"); - } - this.#updateContainerHeightCss(); - this.eventBus._on("thumbnailrendered", ({ - pageNumber, - pdfPage - }) => { - const pageView = this._pages[pageNumber - 1]; - if (!this.#buffer.has(pageView)) { - pdfPage?.cleanup(); + this.eventBus = options.eventBus; + this.renderingQueue = options.renderingQueue; + this.l10n = options.l10n; + this.l10n ||= new genericl10n_GenericL10n(); + this.renderTask = null; + this.resume = null; + this._isStandalone = !this.renderingQueue?.hasViewer(); + this._container = container; + this._annotationCanvasMap = null; + this.annotationLayer = null; + this.annotationEditorLayer = null; + this.textLayer = null; + this.xfaLayer = null; + this.structTreeLayer = null; + this.drawLayer = null; + const div = document.createElement("div"); + div.className = "page"; + div.setAttribute("data-page-number", this.id); + div.setAttribute("role", "region"); + div.setAttribute("data-l10n-id", "pdfjs-page-landmark"); + div.setAttribute("data-l10n-args", JSON.stringify({ + page: this.id + })); + this.div = div; + this.#setDimensions(); + container?.append(div); + if (this._isStandalone) { + container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS); + if (this.pageColors?.background) { + container?.style.setProperty("--page-bg-color", this.pageColors.background); + } + const { + optionalContentConfigPromise + } = options; + if (optionalContentConfigPromise) { + optionalContentConfigPromise.then(optionalContentConfig => { + if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { + return; + } + this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; + }); + } + if (!options.l10n) { + this.l10n.translate(this.div); } - }); - if (!options.l10n) { - this.l10n.translate(this.container); } } - get pagesCount() { - return this._pages.length; - } - getPageView(index) { - return this._pages[index]; - } - getCachedPageViews() { - return new Set(this.#buffer); - } - get pageViewsReady() { - return this._pages.every(pageView => pageView?.pdfPage); - } - get renderForms() { - return this.#annotationMode === AnnotationMode.ENABLE_FORMS; - } - get enableScripting() { - return !!this._scriptingManager; - } - get currentPageNumber() { - return this._currentPageNumber; - } - set currentPageNumber(val) { - if (!Number.isInteger(val)) { - throw new Error("Invalid page number."); - } - if (!this.pdfDocument) { + #addLayer(div, name) { + const pos = LAYERS_ORDER.get(name); + const oldDiv = this.#layers[pos]; + this.#layers[pos] = div; + if (oldDiv) { + oldDiv.replaceWith(div); return; } - if (!this._setCurrentPageNumber(val, true)) { - console.error(`currentPageNumber: "${val}" is not a valid page.`); - } - } - _setCurrentPageNumber(val, resetCurrentPageView = false) { - if (this._currentPageNumber === val) { - if (resetCurrentPageView) { - this.#resetCurrentPageView(); + for (let i = pos - 1; i >= 0; i--) { + const layer = this.#layers[i]; + if (layer) { + layer.after(div); + return; } - return true; - } - if (!(0 < val && val <= this.pagesCount)) { - return false; - } - const previous = this._currentPageNumber; - this._currentPageNumber = val; - this.eventBus.dispatch("pagechanging", { - source: this, - pageNumber: val, - pageLabel: this._pageLabels?.[val - 1] ?? null, - previous - }); - if (resetCurrentPageView) { - this.#resetCurrentPageView(); } - return true; + this.div.prepend(div); } - get currentPageLabel() { - return this._pageLabels?.[this._currentPageNumber - 1] ?? null; + get renderingState() { + return this.#renderingState; } - set currentPageLabel(val) { - if (!this.pdfDocument) { + set renderingState(state) { + if (state === this.#renderingState) { return; } - let page = val | 0; - if (this._pageLabels) { - const i = this._pageLabels.indexOf(val); - if (i >= 0) { - page = i + 1; - } - } - if (!this._setCurrentPageNumber(page, true)) { - console.error(`currentPageLabel: "${val}" is not a valid page.`); - } - } - get currentScale() { - return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; - } - set currentScale(val) { - if (isNaN(val)) { - throw new Error("Invalid numeric scale."); + this.#renderingState = state; + if (this.#loadingId) { + clearTimeout(this.#loadingId); + this.#loadingId = null; } - if (!this.pdfDocument) { - return; + switch (state) { + case RenderingStates.PAUSED: + this.div.classList.remove("loading"); + break; + case RenderingStates.RUNNING: + this.div.classList.add("loadingIcon"); + this.#loadingId = setTimeout(() => { + this.div.classList.add("loading"); + this.#loadingId = null; + }, 0); + break; + case RenderingStates.INITIAL: + case RenderingStates.FINISHED: + this.div.classList.remove("loadingIcon", "loading"); + break; } - this.#setScale(val, { - noScroll: false - }); - } - get currentScaleValue() { - return this._currentScaleValue; } - set currentScaleValue(val) { - if (!this.pdfDocument) { - return; + #setDimensions() { + const { + viewport + } = this; + if (this.pdfPage) { + if (this.#previousRotation === viewport.rotation) { + return; + } + this.#previousRotation = viewport.rotation; } - this.#setScale(val, { - noScroll: false - }); - } - get pagesRotation() { - return this._pagesRotation; + setLayerDimensions(this.div, viewport, true, false); } - set pagesRotation(rotation) { - if (!isValidRotation(rotation)) { - throw new Error("Invalid pages rotation angle."); - } - if (!this.pdfDocument) { - return; - } - rotation %= 360; - if (rotation < 0) { - rotation += 360; - } - if (this._pagesRotation === rotation) { - return; - } - this._pagesRotation = rotation; - const pageNumber = this._currentPageNumber; - this.refresh(true, { - rotation - }); - if (this._currentScaleValue) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); + setPdfPage(pdfPage) { + if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) { + this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); + this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight")); } - this.eventBus.dispatch("rotationchanging", { - source: this, - pagesRotation: rotation, - pageNumber + this.pdfPage = pdfPage; + this.pdfPageRotate = pdfPage.rotate; + const totalRotation = (this.rotation + this.pdfPageRotate) % 360; + this.viewport = pdfPage.getViewport({ + scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, + rotation: totalRotation }); - if (this.defaultRenderingQueue) { - this.update(); - } + this.#setDimensions(); + this.reset(); } - get firstPagePromise() { - return this.pdfDocument ? this._firstPageCapability.promise : null; + destroy() { + this.reset(); + this.pdfPage?.cleanup(); } - get onePageRendered() { - return this.pdfDocument ? this._onePageRenderedCapability.promise : null; + hasEditableAnnotations() { + return !!this.annotationLayer?.hasEditableAnnotations(); } - get pagesPromise() { - return this.pdfDocument ? this._pagesCapability.promise : null; + get _textHighlighter() { + return shadow(this, "_textHighlighter", new TextHighlighter({ + pageIndex: this.id - 1, + eventBus: this.eventBus, + findController: this.#layerProperties.findController + })); } - get _layerProperties() { - const self = this; - return shadow(this, "_layerProperties", { - get annotationEditorUIManager() { - return self.#annotationEditorUIManager; - }, - get annotationStorage() { - return self.pdfDocument?.annotationStorage; - }, - get downloadManager() { - return self.downloadManager; - }, - get enableScripting() { - return !!self._scriptingManager; - }, - get fieldObjectsPromise() { - return self.pdfDocument?.getFieldObjects(); - }, - get findController() { - return self.findController; - }, - get hasJSActionsPromise() { - return self.pdfDocument?.hasJSActions(); - }, - get linkService() { - return self.linkService; - } + #dispatchLayerRendered(name, error) { + this.eventBus.dispatch(name, { + source: this, + pageNumber: this.id, + error }); } - #initializePermissions(permissions) { - const params = { - annotationEditorMode: this.#annotationEditorMode, - annotationMode: this.#annotationMode, - textLayerMode: this.#textLayerMode - }; - if (!permissions) { - return params; + async #renderAnnotationLayer() { + let error = null; + try { + await this.annotationLayer.render(this.viewport, { + structTreeLayer: this.structTreeLayer + }, "display"); + } catch (ex) { + console.error("#renderAnnotationLayer:", ex); + error = ex; + } finally { + this.#dispatchLayerRendered("annotationlayerrendered", error); } - if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) { - params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS; + } + async #renderAnnotationEditorLayer() { + let error = null; + try { + await this.annotationEditorLayer.render(this.viewport, "display"); + } catch (ex) { + console.error("#renderAnnotationEditorLayer:", ex); + error = ex; + } finally { + this.#dispatchLayerRendered("annotationeditorlayerrendered", error); } - if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) { - params.annotationEditorMode = AnnotationEditorType.DISABLE; + } + async #renderDrawLayer() { + try { + await this.drawLayer.render("display"); + } catch (ex) { + console.error("#renderDrawLayer:", ex); } - if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) { - params.annotationMode = AnnotationMode.ENABLE; + } + async #renderXfaLayer() { + let error = null; + try { + const result = await this.xfaLayer.render(this.viewport, "display"); + if (result?.textDivs && this._textHighlighter) { + this.#buildXfaTextContentItems(result.textDivs); + } + } catch (ex) { + console.error("#renderXfaLayer:", ex); + error = ex; + } finally { + if (this.xfaLayer?.div) { + this.l10n.pause(); + this.#addLayer(this.xfaLayer.div, "xfaLayer"); + this.l10n.resume(); + } + this.#dispatchLayerRendered("xfalayerrendered", error); } - return params; } - async #onePageRenderedOrForceFetch(signal) { - if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) { + async #renderTextLayer() { + if (!this.textLayer) { return; } - const hiddenCapability = Promise.withResolvers(), - ac = new AbortController(); - document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "hidden") { - hiddenCapability.resolve(); + let error = null; + try { + await this.textLayer.render(this.viewport); + } catch (ex) { + if (ex instanceof AbortException) { + return; } - }, { - signal: typeof AbortSignal.any === "function" ? AbortSignal.any([signal, ac.signal]) : signal - }); - await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]); - ac.abort(); + console.error("#renderTextLayer:", ex); + error = ex; + } + this.#dispatchLayerRendered("textlayerrendered", error); + this.#renderStructTreeLayer(); } - async getAllText() { - const texts = []; - const buffer = []; - for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) { - if (this.#interruptCopyCondition) { - return null; - } - buffer.length = 0; - const page = await this.pdfDocument.getPage(pageNum); - const { - items - } = await page.getTextContent(); - for (const item of items) { - if (item.str) { - buffer.push(item.str); - } - if (item.hasEOL) { - buffer.push("\n"); - } + async #renderStructTreeLayer() { + if (!this.textLayer) { + return; + } + const treeDom = await this.structTreeLayer?.render(); + if (treeDom) { + this.l10n.pause(); + this.structTreeLayer?.addElementsToTextLayer(); + if (this.canvas && treeDom.parentNode !== this.canvas) { + this.canvas.append(treeDom); } - texts.push(removeNullCharacters(buffer.join(""))); + this.l10n.resume(); } - return texts.join("\n"); + this.structTreeLayer?.show(); } - #copyCallback(textLayerMode, event) { - const selection = document.getSelection(); + async #buildXfaTextContentItems(textDivs) { + const text = await this.pdfPage.getTextContent(); + const items = []; + for (const item of text.items) { + items.push(item.str); + } + this._textHighlighter.setTextMapping(textDivs, items); + this._textHighlighter.enable(); + } + #resetCanvas() { const { - focusNode, - anchorNode - } = selection; - if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) { - if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) { - stopEvent(event); - return; - } - this.#getAllTextInProgress = true; - const { - classList - } = this.viewer; - classList.add("copyAll"); - const ac = new AbortController(); - window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", { - signal: ac.signal - }); - this.getAllText().then(async text => { - if (text !== null) { - await navigator.clipboard.writeText(text); - } - }).catch(reason => { - console.warn(`Something goes wrong when extracting the text: ${reason.message}`); - }).finally(() => { - this.#getAllTextInProgress = false; - this.#interruptCopyCondition = false; - ac.abort(); - classList.remove("copyAll"); - }); - stopEvent(event); + canvas + } = this; + if (!canvas) { + return; + } + canvas.remove(); + canvas.width = canvas.height = 0; + this.canvas = null; + this.#originalViewport = null; + } + reset({ + keepAnnotationLayer = false, + keepAnnotationEditorLayer = false, + keepXfaLayer = false, + keepTextLayer = false, + keepCanvasWrapper = false + } = {}) { + this.cancelRendering({ + keepAnnotationLayer, + keepAnnotationEditorLayer, + keepXfaLayer, + keepTextLayer + }); + this.renderingState = RenderingStates.INITIAL; + const div = this.div; + const childNodes = div.childNodes, + annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, + annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null, + xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null, + textLayerNode = keepTextLayer && this.textLayer?.div || null, + canvasWrapperNode = keepCanvasWrapper && this.#canvasWrapper || null; + for (let i = childNodes.length - 1; i >= 0; i--) { + const node = childNodes[i]; + switch (node) { + case annotationLayerNode: + case annotationEditorLayerNode: + case xfaLayerNode: + case textLayerNode: + case canvasWrapperNode: + continue; + } + node.remove(); + const layerIndex = this.#layers.indexOf(node); + if (layerIndex >= 0) { + this.#layers[layerIndex] = null; + } } - } - setDocument(pdfDocument) { - if (this.pdfDocument) { - this.eventBus.dispatch("pagesdestroy", { - source: this - }); - this._cancelRendering(); - this._resetView(); - this.findController?.setDocument(null); - this._scriptingManager?.setDocument(null); - this.#annotationEditorUIManager?.destroy(); - this.#annotationEditorUIManager = null; + div.removeAttribute("data-loaded"); + if (annotationLayerNode) { + this.annotationLayer.hide(); } - this.pdfDocument = pdfDocument; - if (!pdfDocument) { + if (annotationEditorLayerNode) { + this.annotationEditorLayer.hide(); + } + if (xfaLayerNode) { + this.xfaLayer.hide(); + } + if (textLayerNode) { + this.textLayer.hide(); + } + this.structTreeLayer?.hide(); + if (!keepCanvasWrapper && this.#canvasWrapper) { + this.#canvasWrapper = null; + this.#resetCanvas(); + } + } + toggleEditingMode(isEditing) { + if (!this.hasEditableAnnotations()) { return; } - const pagesCount = pdfDocument.numPages; - const firstPagePromise = pdfDocument.getPage(1); - const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ - intent: "display" + this.#isEditing = isEditing; + this.reset({ + keepAnnotationLayer: true, + keepAnnotationEditorLayer: true, + keepXfaLayer: true, + keepTextLayer: true, + keepCanvasWrapper: true }); - const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve(); - const { - eventBus, - pageColors, - viewer - } = this; - this.#eventAbortController = new AbortController(); - const { - signal - } = this.#eventAbortController; - if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { - console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document."); - const mode = this._scrollMode = ScrollMode.PAGE; - eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); + } + update({ + scale = 0, + rotation = null, + optionalContentConfigPromise = null, + drawingDelay = -1 + }) { + this.scale = scale || this.scale; + if (typeof rotation === "number") { + this.rotation = rotation; } - this._pagesCapability.promise.then(() => { - eventBus.dispatch("pagesloaded", { - source: this, - pagesCount - }); - }, () => {}); - const onBeforeDraw = evt => { - const pageView = this._pages[evt.pageNumber - 1]; - if (!pageView) { - return; - } - this.#buffer.push(pageView); - }; - eventBus._on("pagerender", onBeforeDraw, { - signal - }); - const onAfterDraw = evt => { - if (evt.cssTransform) { - return; - } - this._onePageRenderedCapability.resolve({ - timestamp: evt.timestamp - }); - eventBus._off("pagerendered", onAfterDraw); - }; - eventBus._on("pagerendered", onAfterDraw, { - signal - }); - Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this._firstPageCapability.resolve(firstPdfPage); + if (optionalContentConfigPromise instanceof Promise) { this._optionalContentConfigPromise = optionalContentConfigPromise; - const { - annotationEditorMode, - annotationMode, - textLayerMode - } = this.#initializePermissions(permissions); - if (textLayerMode !== TextLayerMode.DISABLE) { - const element = this.#hiddenCopyElement = document.createElement("div"); - element.id = "hiddenCopyElement"; - viewer.before(element); - } - if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { - const mode = annotationEditorMode; - if (pdfDocument.isPureXfa) { - console.warn("Warning: XFA-editing is not implemented."); - } else if (isValidAnnotationEditorMode(mode)) { - this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#enableNewAltTextWhenAddingImage, this.#mlManager, this.#editorUndoBar, this.#supportsPinchToZoom); - eventBus.dispatch("annotationeditoruimanager", { - source: this, - uiManager: this.#annotationEditorUIManager - }); - if (mode !== AnnotationEditorType.NONE) { - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - this.#annotationEditorUIManager.updateMode(mode); - } - } else { - console.error(`Invalid AnnotationEditor mode: ${mode}`); - } - } - const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer; - const scale = this.currentScale; - const viewport = firstPdfPage.getViewport({ - scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS - }); - viewer.style.setProperty("--scale-factor", viewport.scale); - if (pageColors?.background) { - viewer.style.setProperty("--page-bg-color", pageColors.background); - } - if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") { - viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); - viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText")); - } - for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { - const pageView = new PDFPageView({ - container: viewerElement, - eventBus, - id: pageNum, - scale, - defaultViewport: viewport.clone(), - optionalContentConfigPromise, - renderingQueue: this.renderingQueue, - textLayerMode, - annotationMode, - imageResourcesPath: this.imageResourcesPath, - maxCanvasPixels: this.maxCanvasPixels, - pageColors, - l10n: this.l10n, - layerProperties: this._layerProperties, - enableHWA: this.#enableHWA - }); - this._pages.push(pageView); - } - this._pages[0]?.setPdfPage(firstPdfPage); - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._spreadMode !== SpreadMode.NONE) { - this._updateSpreadMode(); - } - this.#onePageRenderedOrForceFetch(signal).then(async () => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this.findController?.setDocument(pdfDocument); - this._scriptingManager?.setDocument(pdfDocument); - if (this.#hiddenCopyElement) { - document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), { - signal - }); - } - if (this.#annotationEditorUIManager) { - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode: this.#annotationEditorMode - }); - } - if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) { - this._pagesCapability.resolve(); + optionalContentConfigPromise.then(optionalContentConfig => { + if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { return; } - let getPagesLeft = pagesCount - 1; - if (getPagesLeft <= 0) { - this._pagesCapability.resolve(); - return; + this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; + }); + } + this.#useThumbnailCanvas.directDrawing = true; + const totalRotation = (this.rotation + this.pdfPageRotate) % 360; + this.viewport = this.viewport.clone({ + scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, + rotation: totalRotation + }); + this.#setDimensions(); + if (this._isStandalone) { + this._container?.style.setProperty("--scale-factor", this.viewport.scale); + } + if (this.canvas) { + let onlyCssZoom = false; + if (this.#hasRestrictedScaling) { + if (this.maxCanvasPixels === 0) { + onlyCssZoom = true; + } else if (this.maxCanvasPixels > 0) { + const { + width, + height + } = this.viewport; + const { + sx, + sy + } = this.outputScale; + onlyCssZoom = (Math.floor(width) * sx | 0) * (Math.floor(height) * sy | 0) > this.maxCanvasPixels; } - for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { - const promise = pdfDocument.getPage(pageNum).then(pdfPage => { - const pageView = this._pages[pageNum - 1]; - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } - }, reason => { - console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); - if (--getPagesLeft === 0) { - this._pagesCapability.resolve(); - } + } + const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; + if (postponeDrawing || onlyCssZoom) { + if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) { + this.cancelRendering({ + keepAnnotationLayer: true, + keepAnnotationEditorLayer: true, + keepXfaLayer: true, + keepTextLayer: true, + cancelExtraDelay: drawingDelay }); - if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) { - await promise; - } + this.renderingState = RenderingStates.FINISHED; + this.#useThumbnailCanvas.directDrawing = false; } - }); - eventBus.dispatch("pagesinit", { - source: this - }); - pdfDocument.getMetadata().then(({ - info - }) => { - if (pdfDocument !== this.pdfDocument) { + this.cssTransform({ + redrawAnnotationLayer: true, + redrawAnnotationEditorLayer: true, + redrawXfaLayer: true, + redrawTextLayer: !postponeDrawing, + hideTextLayer: postponeDrawing + }); + if (postponeDrawing) { return; } - if (info.Language) { - viewer.lang = info.Language; - } - }); - if (this.defaultRenderingQueue) { - this.update(); + this.eventBus.dispatch("pagerendered", { + source: this, + pageNumber: this.id, + cssTransform: true, + timestamp: performance.now(), + error: this.#renderError + }); + return; } - }).catch(reason => { - console.error("Unable to initialize viewer", reason); - this._pagesCapability.reject(reason); + } + this.cssTransform({}); + this.reset({ + keepAnnotationLayer: true, + keepAnnotationEditorLayer: true, + keepXfaLayer: true, + keepTextLayer: true, + keepCanvasWrapper: true }); } - setPageLabels(labels) { - if (!this.pdfDocument) { - return; + cancelRendering({ + keepAnnotationLayer = false, + keepAnnotationEditorLayer = false, + keepXfaLayer = false, + keepTextLayer = false, + cancelExtraDelay = 0 + } = {}) { + if (this.renderTask) { + this.renderTask.cancel(cancelExtraDelay); + this.renderTask = null; } - if (!labels) { - this._pageLabels = null; - } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { - this._pageLabels = null; - console.error(`setPageLabels: Invalid page labels.`); - } else { - this._pageLabels = labels; + this.resume = null; + if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) { + this.textLayer.cancel(); + this.textLayer = null; } - for (let i = 0, ii = this._pages.length; i < ii; i++) { - this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); + if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { + this.annotationLayer.cancel(); + this.annotationLayer = null; + this._annotationCanvasMap = null; + } + if (this.structTreeLayer && !this.textLayer) { + this.structTreeLayer = null; + } + if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) { + if (this.drawLayer) { + this.drawLayer.cancel(); + this.drawLayer = null; + } + this.annotationEditorLayer.cancel(); + this.annotationEditorLayer = null; + } + if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { + this.xfaLayer.cancel(); + this.xfaLayer = null; + this._textHighlighter?.disable(); } } - _resetView() { - this._pages = []; - this._currentPageNumber = 1; - this._currentScale = UNKNOWN_SCALE; - this._currentScaleValue = null; - this._pageLabels = null; - this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); - this._location = null; - this._pagesRotation = 0; - this._optionalContentConfigPromise = null; - this._firstPageCapability = Promise.withResolvers(); - this._onePageRenderedCapability = Promise.withResolvers(); - this._pagesCapability = Promise.withResolvers(); - this._scrollMode = ScrollMode.VERTICAL; - this._previousScrollMode = ScrollMode.UNKNOWN; - this._spreadMode = SpreadMode.NONE; - this.#scrollModePageState = { - previousPageNumber: 1, - scrollDown: true, - pages: [] - }; - this.#eventAbortController?.abort(); - this.#eventAbortController = null; - this.viewer.textContent = ""; - this._updateScrollMode(); - this.viewer.removeAttribute("lang"); - this.#hiddenCopyElement?.remove(); - this.#hiddenCopyElement = null; - this.#cleanupSwitchAnnotationEditorMode(); - } - #ensurePageViewVisible() { - if (this._scrollMode !== ScrollMode.PAGE) { - throw new Error("#ensurePageViewVisible: Invalid scrollMode value."); + cssTransform({ + redrawAnnotationLayer = false, + redrawAnnotationEditorLayer = false, + redrawXfaLayer = false, + redrawTextLayer = false, + hideTextLayer = false + }) { + const { + canvas + } = this; + if (!canvas) { + return; } - const pageNumber = this._currentPageNumber, - state = this.#scrollModePageState, - viewer = this.viewer; - viewer.textContent = ""; - state.pages.length = 0; - if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) { - const pageView = this._pages[pageNumber - 1]; - viewer.append(pageView.div); - state.pages.push(pageView); - } else { - const pageIndexSet = new Set(), - parity = this._spreadMode - 1; - if (parity === -1) { - pageIndexSet.add(pageNumber - 1); - } else if (pageNumber % 2 !== parity) { - pageIndexSet.add(pageNumber - 1); - pageIndexSet.add(pageNumber); + const originalViewport = this.#originalViewport; + if (this.viewport !== originalViewport) { + const relativeRotation = (360 + this.viewport.rotation - originalViewport.rotation) % 360; + if (relativeRotation === 90 || relativeRotation === 270) { + const { + width, + height + } = this.viewport; + const scaleX = height / width; + const scaleY = width / height; + canvas.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX},${scaleY})`; } else { - pageIndexSet.add(pageNumber - 2); - pageIndexSet.add(pageNumber - 1); + canvas.style.transform = relativeRotation === 0 ? "" : `rotate(${relativeRotation}deg)`; } - const spread = document.createElement("div"); - spread.className = "spread"; - if (this.isInPresentationMode) { - const dummyPage = document.createElement("div"); - dummyPage.className = "dummyPage"; - spread.append(dummyPage); + } + if (redrawAnnotationLayer && this.annotationLayer) { + this.#renderAnnotationLayer(); + } + if (redrawAnnotationEditorLayer && this.annotationEditorLayer) { + if (this.drawLayer) { + this.#renderDrawLayer(); } - for (const i of pageIndexSet) { - const pageView = this._pages[i]; - if (!pageView) { - continue; - } - spread.append(pageView.div); - state.pages.push(pageView); + this.#renderAnnotationEditorLayer(); + } + if (redrawXfaLayer && this.xfaLayer) { + this.#renderXfaLayer(); + } + if (this.textLayer) { + if (hideTextLayer) { + this.textLayer.hide(); + this.structTreeLayer?.hide(); + } else if (redrawTextLayer) { + this.#renderTextLayer(); } - viewer.append(spread); } - state.scrollDown = pageNumber >= state.previousPageNumber; - state.previousPageNumber = pageNumber; } - _scrollUpdate() { - if (this.pagesCount === 0) { + get width() { + return this.viewport.width; + } + get height() { + return this.viewport.height; + } + getPagePoint(x, y) { + return this.viewport.convertToPdfPoint(x, y); + } + async #finishRenderTask(renderTask, error = null) { + if (renderTask === this.renderTask) { + this.renderTask = null; + } + if (error instanceof RenderingCancelledException) { + this.#renderError = null; return; } - this.update(); + this.#renderError = error; + this.renderingState = RenderingStates.FINISHED; + this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots; + this.eventBus.dispatch("pagerendered", { + source: this, + pageNumber: this.id, + cssTransform: false, + timestamp: performance.now(), + error: this.#renderError + }); + if (error) { + throw error; + } } - #scrollIntoView(pageView, pageSpot = null) { + async draw() { + if (this.renderingState !== RenderingStates.INITIAL) { + console.error("Must be in new state before drawing"); + this.reset(); + } const { div, - id - } = pageView; - if (this._currentPageNumber !== id) { - this._setCurrentPageNumber(id); + l10n, + pageColors, + pdfPage, + viewport + } = this; + if (!pdfPage) { + this.renderingState = RenderingStates.FINISHED; + throw new Error("pdfPage is not loaded"); } - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - this.update(); + this.renderingState = RenderingStates.RUNNING; + let canvasWrapper = this.#canvasWrapper; + if (!canvasWrapper) { + canvasWrapper = this.#canvasWrapper = document.createElement("div"); + canvasWrapper.classList.add("canvasWrapper"); + this.#addLayer(canvasWrapper, "canvasWrapper"); } - if (!pageSpot && !this.isInPresentationMode) { - const left = div.offsetLeft + div.clientLeft, - right = left + div.clientWidth; + if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) { + this._accessibilityManager ||= new TextAccessibilityManager(); + this.textLayer = new TextLayerBuilder({ + pdfPage, + highlighter: this._textHighlighter, + accessibilityManager: this._accessibilityManager, + enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS, + onAppend: textLayerDiv => { + this.l10n.pause(); + this.#addLayer(textLayerDiv, "textLayer"); + this.l10n.resume(); + } + }); + } + if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) { const { - scrollLeft, - clientWidth - } = this.container; - if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) { - pageSpot = { - left: 0, - top: 0 + annotationStorage, + annotationEditorUIManager, + downloadManager, + enableScripting, + fieldObjectsPromise, + hasJSActionsPromise, + linkService + } = this.#layerProperties; + this._annotationCanvasMap ||= new Map(); + this.annotationLayer = new AnnotationLayerBuilder({ + pdfPage, + annotationStorage, + imageResourcesPath: this.imageResourcesPath, + renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS, + linkService, + downloadManager, + enableScripting, + hasJSActionsPromise, + fieldObjectsPromise, + annotationCanvasMap: this._annotationCanvasMap, + accessibilityManager: this._accessibilityManager, + annotationEditorUIManager, + onAppend: annotationLayerDiv => { + this.#addLayer(annotationLayerDiv, "annotationLayer"); + } + }); + } + const renderContinueCallback = cont => { + showCanvas?.(false); + if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) { + this.renderingState = RenderingStates.PAUSED; + this.resume = () => { + this.renderingState = RenderingStates.RUNNING; + cont(); }; + return; } - } - scrollIntoView(div, pageSpot); - if (!this._currentScaleValue && this._location) { - this._location = null; - } - } - #isSameScale(newScale) { - return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15; - } - #setScaleUpdatePages(newScale, newValue, { - noScroll = false, - preset = false, - drawingDelay = -1, - origin = null - }) { - this._currentScaleValue = newValue.toString(); - if (this.#isSameScale(newScale)) { - if (preset) { - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: newValue - }); + cont(); + }; + const { + width, + height + } = viewport; + const canvas = document.createElement("canvas"); + canvas.setAttribute("role", "presentation"); + const hasHCM = !!(pageColors?.background && pageColors?.foreground); + const prevCanvas = this.canvas; + const updateOnFirstShow = !prevCanvas && !hasHCM; + this.canvas = canvas; + this.#originalViewport = viewport; + let showCanvas = isLastShow => { + if (updateOnFirstShow) { + canvasWrapper.prepend(canvas); + showCanvas = null; + return; } - return; - } - this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS); - const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; - this.refresh(true, { - scale: newScale, - drawingDelay: postponeDrawing ? drawingDelay : -1 - }); - if (postponeDrawing) { - this.#scaleTimeoutId = setTimeout(() => { - this.#scaleTimeoutId = null; - this.refresh(); - }, drawingDelay); - } - const previousScale = this._currentScale; - this._currentScale = newScale; - if (!noScroll) { - let page = this._currentPageNumber, - dest; - if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { - page = this._location.pageNumber; - dest = [null, { - name: "XYZ" - }, this._location.left, this._location.top, null]; + if (!isLastShow) { + return; } - this.scrollPageIntoView({ - pageNumber: page, - destArray: dest, - allowNegativeOffset: true - }); - if (Array.isArray(origin)) { - const scaleDiff = newScale / previousScale - 1; - const [top, left] = this.containerTopLeft; - this.container.scrollLeft += (origin[0] - left) * scaleDiff; - this.container.scrollTop += (origin[1] - top) * scaleDiff; + if (prevCanvas) { + prevCanvas.replaceWith(canvas); + prevCanvas.width = prevCanvas.height = 0; + } else { + canvasWrapper.prepend(canvas); } - } - this.eventBus.dispatch("scalechanging", { - source: this, - scale: newScale, - presetValue: preset ? newValue : undefined + showCanvas = null; + }; + const ctx = canvas.getContext("2d", { + alpha: false, + willReadFrequently: !this.#enableHWA }); - if (this.defaultRenderingQueue) { - this.update(); + const outputScale = this.outputScale = new OutputScale(); + if (this.maxCanvasPixels === 0) { + const invScale = 1 / this.scale; + outputScale.sx *= invScale; + outputScale.sy *= invScale; + this.#hasRestrictedScaling = true; + } else if (this.maxCanvasPixels > 0) { + const pixelsInViewport = width * height; + const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); + if (outputScale.sx > maxScale || outputScale.sy > maxScale) { + outputScale.sx = maxScale; + outputScale.sy = maxScale; + this.#hasRestrictedScaling = true; + } else { + this.#hasRestrictedScaling = false; + } } - } - get #pageWidthScaleFactor() { - if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) { - return 2; + const sfx = approximateFraction(outputScale.sx); + const sfy = approximateFraction(outputScale.sy); + const canvasWidth = canvas.width = floorToDivide(calcRound(width * outputScale.sx), sfx[0]); + const canvasHeight = canvas.height = floorToDivide(calcRound(height * outputScale.sy), sfy[0]); + const pageWidth = floorToDivide(calcRound(width), sfx[1]); + const pageHeight = floorToDivide(calcRound(height), sfy[1]); + outputScale.sx = canvasWidth / pageWidth; + outputScale.sy = canvasHeight / pageHeight; + if (this.#scaleRoundX !== sfx[1]) { + div.style.setProperty("--scale-round-x", `${sfx[1]}px`); + this.#scaleRoundX = sfx[1]; } - return 1; - } - #setScale(value, options) { - let scale = parseFloat(value); - if (scale > 0) { - options.preset = false; - this.#setScaleUpdatePages(scale, value, options); - } else { - const currentPage = this._pages[this._currentPageNumber - 1]; - if (!currentPage) { + if (this.#scaleRoundY !== sfy[1]) { + div.style.setProperty("--scale-round-y", `${sfy[1]}px`); + this.#scaleRoundY = sfy[1]; + } + const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; + const renderContext = { + canvasContext: ctx, + transform, + viewport, + annotationMode: this.#annotationMode, + optionalContentConfigPromise: this._optionalContentConfigPromise, + annotationCanvasMap: this._annotationCanvasMap, + pageColors, + isEditing: this.#isEditing + }; + const renderTask = this.renderTask = pdfPage.render(renderContext); + renderTask.onContinue = renderContinueCallback; + const resultPromise = renderTask.promise.then(async () => { + showCanvas?.(true); + await this.#finishRenderTask(renderTask); + this.structTreeLayer ||= new StructTreeLayerBuilder(pdfPage, viewport.rawDims); + this.#renderTextLayer(); + if (this.annotationLayer) { + await this.#renderAnnotationLayer(); + } + const { + annotationEditorUIManager + } = this.#layerProperties; + if (!annotationEditorUIManager) { return; } - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.isInPresentationMode) { - hPadding = vPadding = 4; - if (this._spreadMode !== SpreadMode.NONE) { - hPadding *= 2; + this.drawLayer ||= new DrawLayerBuilder({ + pageIndex: this.id + }); + await this.#renderDrawLayer(); + this.drawLayer.setParent(canvasWrapper); + this.annotationEditorLayer ||= new AnnotationEditorLayerBuilder({ + uiManager: annotationEditorUIManager, + pdfPage, + l10n, + structTreeLayer: this.structTreeLayer, + accessibilityManager: this._accessibilityManager, + annotationLayer: this.annotationLayer?.annotationLayer, + textLayer: this.textLayer, + drawLayer: this.drawLayer.getDrawLayer(), + onAppend: annotationEditorLayerDiv => { + this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer"); } - } else if (this.removePageBorders) { - hPadding = vPadding = 0; - } else if (this._scrollMode === ScrollMode.HORIZONTAL) { - [hPadding, vPadding] = [vPadding, hPadding]; + }); + this.#renderAnnotationEditorLayer(); + }, error => { + if (!(error instanceof RenderingCancelledException)) { + showCanvas?.(true); + } else { + prevCanvas?.remove(); + this.#resetCanvas(); } - const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor; - const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; - switch (value) { - case "page-actual": - scale = 1; - break; - case "page-width": - scale = pageWidthScale; - break; - case "page-height": - scale = pageHeightScale; - break; - case "page-fit": - scale = Math.min(pageWidthScale, pageHeightScale); - break; - case "auto": - const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); - scale = Math.min(MAX_AUTO_SCALE, horizontalScale); - break; - default: - console.error(`#setScale: "${value}" is an unknown zoom value.`); - return; + return this.#finishRenderTask(renderTask, error); + }); + if (pdfPage.isPureXfa) { + if (!this.xfaLayer) { + const { + annotationStorage, + linkService + } = this.#layerProperties; + this.xfaLayer = new XfaLayerBuilder({ + pdfPage, + annotationStorage, + linkService + }); } - options.preset = true; - this.#setScaleUpdatePages(scale, value, options); + this.#renderXfaLayer(); } + div.setAttribute("data-loaded", true); + this.eventBus.dispatch("pagerender", { + source: this, + pageNumber: this.id + }); + return resultPromise; } - #resetCurrentPageView() { - const pageView = this._pages[this._currentPageNumber - 1]; - if (this.isInPresentationMode) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); + setPageLabel(label) { + this.pageLabel = typeof label === "string" ? label : null; + this.div.setAttribute("data-l10n-args", JSON.stringify({ + page: this.pageLabel ?? this.id + })); + if (this.pageLabel !== null) { + this.div.setAttribute("data-page-label", this.pageLabel); + } else { + this.div.removeAttribute("data-page-label"); } - this.#scrollIntoView(pageView); } - pageLabelToPageNumber(label) { - if (!this._pageLabels) { - return null; - } - const i = this._pageLabels.indexOf(label); - if (i < 0) { - return null; - } - return i + 1; + get thumbnailCanvas() { + const { + directDrawing, + initialOptionalContent, + regularAnnotations + } = this.#useThumbnailCanvas; + return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null; } - scrollPageIntoView({ - pageNumber, - destArray = null, - allowNegativeOffset = false, - ignoreDestinationZoom = false +} + +;// ./web/generic_scripting.js + +async function docProperties(pdfDocument) { + const url = "", + baseUrl = url.split("#", 1)[0]; + let { + info, + metadata, + contentDispositionFilename, + contentLength + } = await pdfDocument.getMetadata(); + if (!contentLength) { + const { + length + } = await pdfDocument.getDownloadInfo(); + contentLength = length; + } + return { + ...info, + baseURL: baseUrl, + filesize: contentLength, + filename: contentDispositionFilename || getPdfFilenameFromUrl(url), + metadata: metadata?.getRaw(), + authors: metadata?.get("dc:creator"), + numPages: pdfDocument.numPages, + URL: url + }; +} +class GenericScripting { + constructor(sandboxBundleSrc) { + this._ready = new Promise((resolve, reject) => { + const sandbox = import(/*webpackIgnore: true*/sandboxBundleSrc); + sandbox.then(pdfjsSandbox => { + resolve(pdfjsSandbox.QuickJSSandbox()); + }).catch(reject); + }); + } + async createSandbox(data) { + const sandbox = await this._ready; + sandbox.create(data); + } + async dispatchEventInSandbox(event) { + const sandbox = await this._ready; + setTimeout(() => sandbox.dispatchEvent(event), 0); + } + async destroySandbox() { + const sandbox = await this._ready; + sandbox.nukeSandbox(); + } +} + +;// ./web/pdf_scripting_manager.js + + +class PDFScriptingManager { + #closeCapability = null; + #destroyCapability = null; + #docProperties = null; + #eventAbortController = null; + #eventBus = null; + #externalServices = null; + #pdfDocument = null; + #pdfViewer = null; + #ready = false; + #scripting = null; + #willPrintCapability = null; + constructor({ + eventBus, + externalServices = null, + docProperties = null }) { - if (!this.pdfDocument) { - return; - } - const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; - if (!pageView) { - console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); - return; + this.#eventBus = eventBus; + this.#externalServices = externalServices; + this.#docProperties = docProperties; + } + setViewer(pdfViewer) { + this.#pdfViewer = pdfViewer; + } + async setDocument(pdfDocument) { + if (this.#pdfDocument) { + await this.#destroyScripting(); } - if (this.isInPresentationMode || !destArray) { - this._setCurrentPageNumber(pageNumber, true); + this.#pdfDocument = pdfDocument; + if (!pdfDocument) { return; } - let x = 0, - y = 0; - let width = 0, - height = 0, - widthScale, - heightScale; - const changeOrientation = pageView.rotation % 180 !== 0; - const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; - let scale = 0; - switch (destArray[1].name) { - case "XYZ": - x = destArray[2]; - y = destArray[3]; - scale = destArray[4]; - x = x !== null ? x : 0; - y = y !== null ? y : pageHeight; - break; - case "Fit": - case "FitB": - scale = "page-fit"; - break; - case "FitH": - case "FitBH": - y = destArray[2]; - scale = "page-width"; - if (y === null && this._location) { - x = this._location.left; - y = this._location.top; - } else if (typeof y !== "number" || y < 0) { - y = pageHeight; - } - break; - case "FitV": - case "FitBV": - x = destArray[2]; - width = pageWidth; - height = pageHeight; - scale = "page-height"; - break; - case "FitR": - x = destArray[2]; - y = destArray[3]; - width = destArray[4] - x; - height = destArray[5] - y; - let hPadding = SCROLLBAR_PADDING, - vPadding = VERTICAL_PADDING; - if (this.removePageBorders) { - hPadding = vPadding = 0; - } - widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS; - heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS; - scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); - break; - default: - console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); - return; - } - if (!ignoreDestinationZoom) { - if (scale && scale !== this._currentScale) { - this.currentScaleValue = scale; - } else if (this._currentScale === UNKNOWN_SCALE) { - this.currentScaleValue = DEFAULT_SCALE_VALUE; - } + const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); + if (!objects && !docActions) { + await this.#destroyScripting(); + return; } - if (scale === "page-fit" && !destArray[4]) { - this.#scrollIntoView(pageView); + if (pdfDocument !== this.#pdfDocument) { return; } - const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; - let left = Math.min(boundingRect[0][0], boundingRect[1][0]); - let top = Math.min(boundingRect[0][1], boundingRect[1][1]); - if (!allowNegativeOffset) { - left = Math.max(left, 0); - top = Math.max(top, 0); + try { + this.#scripting = this.#initScripting(); + } catch (error) { + console.error("setDocument:", error); + await this.#destroyScripting(); + return; } - this.#scrollIntoView(pageView, { - left, - top + const eventBus = this.#eventBus; + this.#eventAbortController = new AbortController(); + const { + signal + } = this.#eventAbortController; + eventBus._on("updatefromsandbox", event => { + if (event?.source === window) { + this.#updateFromSandbox(event.detail); + } + }, { + signal }); - } - _updateLocation(firstPage) { - const currentScale = this._currentScale; - const currentScaleValue = this._currentScaleValue; - const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; - const pageNumber = firstPage.id; - const currentPageView = this._pages[pageNumber - 1]; - const container = this.container; - const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); - const intLeft = Math.round(topLeft[0]); - const intTop = Math.round(topLeft[1]); - let pdfOpenParams = `#page=${pageNumber}`; - if (!this.isInPresentationMode) { - pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`; - } - this._location = { + eventBus._on("dispatcheventinsandbox", event => { + this.#scripting?.dispatchEventInSandbox(event.detail); + }, { + signal + }); + eventBus._on("pagechanging", ({ pageNumber, - scale: normalizedScaleValue, - top: intTop, - left: intLeft, - rotation: this._pagesRotation, - pdfOpenParams - }; - } - update() { - const visible = this._getVisiblePages(); - const visiblePages = visible.views, - numVisiblePages = visiblePages.length; - if (numVisiblePages === 0) { + previous + }) => { + if (pageNumber === previous) { + return; + } + this.#dispatchPageClose(previous); + this.#dispatchPageOpen(pageNumber); + }, { + signal + }); + eventBus._on("pagerendered", ({ + pageNumber + }) => { + if (!this._pageOpenPending.has(pageNumber)) { + return; + } + if (pageNumber !== this.#pdfViewer.currentPageNumber) { + return; + } + this.#dispatchPageOpen(pageNumber); + }, { + signal + }); + eventBus._on("pagesdestroy", async () => { + await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber); + await this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "WillClose" + }); + this.#closeCapability?.resolve(); + }, { + signal + }); + try { + const docProperties = await this.#docProperties(pdfDocument); + if (pdfDocument !== this.#pdfDocument) { + return; + } + await this.#scripting.createSandbox({ + objects, + calculationOrder, + appInfo: { + platform: navigator.platform, + language: navigator.language + }, + docInfo: { + ...docProperties, + actions: docActions + } + }); + eventBus.dispatch("sandboxcreated", { + source: this + }); + } catch (error) { + console.error("setDocument:", error); + await this.#destroyScripting(); return; } - const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); - this.#buffer.resize(newCacheSize, visible.ids); - this.renderingQueue.renderHighestPriority(visible); - const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL); - const currentId = this._currentPageNumber; - let stillFullyVisible = false; - for (const page of visiblePages) { - if (page.percent < 100) { - break; - } - if (page.id === currentId && isSimpleLayout) { - stillFullyVisible = true; - break; + await this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "Open" + }); + await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true); + Promise.resolve().then(() => { + if (pdfDocument === this.#pdfDocument) { + this.#ready = true; } + }); + } + async dispatchWillSave() { + return this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "WillSave" + }); + } + async dispatchDidSave() { + return this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "DidSave" + }); + } + async dispatchWillPrint() { + if (!this.#scripting) { + return; } - this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id); - this._updateLocation(visible.first); - this.eventBus.dispatch("updateviewarea", { - source: this, - location: this._location + await this.#willPrintCapability?.promise; + this.#willPrintCapability = Promise.withResolvers(); + try { + await this.#scripting.dispatchEventInSandbox({ + id: "doc", + name: "WillPrint" + }); + } catch (ex) { + this.#willPrintCapability.resolve(); + this.#willPrintCapability = null; + throw ex; + } + await this.#willPrintCapability.promise; + } + async dispatchDidPrint() { + return this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "DidPrint" }); } - #switchToEditAnnotationMode() { - const visible = this._getVisiblePages(); - const pagesToRefresh = []; + get destroyPromise() { + return this.#destroyCapability?.promise || null; + } + get ready() { + return this.#ready; + } + get _pageOpenPending() { + return shadow(this, "_pageOpenPending", new Set()); + } + get _visitedPages() { + return shadow(this, "_visitedPages", new Map()); + } + async #updateFromSandbox(detail) { + const pdfViewer = this.#pdfViewer; + const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode; const { - ids, - views - } = visible; - for (const page of views) { - const { - view - } = page; - if (!view.hasEditableAnnotations()) { - ids.delete(view.id); - continue; + id, + siblings, + command, + value + } = detail; + if (!id) { + switch (command) { + case "clear": + console.clear(); + break; + case "error": + console.error(value); + break; + case "layout": + if (!isInPresentationMode) { + const modes = apiPageLayoutToViewerModes(value); + pdfViewer.spreadMode = modes.spreadMode; + } + break; + case "page-num": + pdfViewer.currentPageNumber = value + 1; + break; + case "print": + await pdfViewer.pagesPromise; + this.#eventBus.dispatch("print", { + source: this + }); + break; + case "println": + console.log(value); + break; + case "zoom": + if (!isInPresentationMode) { + pdfViewer.currentScaleValue = value; + } + break; + case "SaveAs": + this.#eventBus.dispatch("download", { + source: this + }); + break; + case "FirstPage": + pdfViewer.currentPageNumber = 1; + break; + case "LastPage": + pdfViewer.currentPageNumber = pdfViewer.pagesCount; + break; + case "NextPage": + pdfViewer.nextPage(); + break; + case "PrevPage": + pdfViewer.previousPage(); + break; + case "ZoomViewIn": + if (!isInPresentationMode) { + pdfViewer.increaseScale(); + } + break; + case "ZoomViewOut": + if (!isInPresentationMode) { + pdfViewer.decreaseScale(); + } + break; + case "WillPrintFinished": + this.#willPrintCapability?.resolve(); + this.#willPrintCapability = null; + break; } - pagesToRefresh.push(page); + return; } - if (pagesToRefresh.length === 0) { - return null; + if (isInPresentationMode && detail.focus) { + return; } - this.renderingQueue.renderHighestPriority({ - first: pagesToRefresh[0], - last: pagesToRefresh.at(-1), - views: pagesToRefresh, - ids - }); - return ids; - } - containsElement(element) { - return this.container.contains(element); - } - focus() { - this.container.focus(); - } - get _isContainerRtl() { - return getComputedStyle(this.container).direction === "rtl"; - } - get isInPresentationMode() { - return this.presentationModeState === PresentationModeState.FULLSCREEN; - } - get isChangingPresentationMode() { - return this.presentationModeState === PresentationModeState.CHANGING; - } - get isHorizontalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; - } - get isVerticalScrollbarEnabled() { - return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; - } - _getVisiblePages() { - const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages, - horizontal = this._scrollMode === ScrollMode.HORIZONTAL, - rtl = horizontal && this._isContainerRtl; - return getVisibleElements({ - scrollEl: this.container, - views, - sortByVisibility: true, - horizontal, - rtl - }); - } - cleanup() { - for (const pageView of this._pages) { - if (pageView.renderingState !== RenderingStates.FINISHED) { - pageView.reset(); + delete detail.id; + delete detail.siblings; + const ids = siblings ? [id, ...siblings] : [id]; + for (const elementId of ids) { + const element = document.querySelector(`[data-element-id="${elementId}"]`); + if (element) { + element.dispatchEvent(new CustomEvent("updatefromsandbox", { + detail + })); + } else { + this.#pdfDocument?.annotationStorage.setValue(elementId, detail); } } } - _cancelRendering() { - for (const pageView of this._pages) { - pageView.cancelRendering(); + async #dispatchPageOpen(pageNumber, initialize = false) { + const pdfDocument = this.#pdfDocument, + visitedPages = this._visitedPages; + if (initialize) { + this.#closeCapability = Promise.withResolvers(); } - } - async #ensurePdfPageLoaded(pageView) { - if (pageView.pdfPage) { - return pageView.pdfPage; + if (!this.#closeCapability) { + return; } - try { - const pdfPage = await this.pdfDocument.getPage(pageView.id); - if (!pageView.pdfPage) { - pageView.setPdfPage(pdfPage); - } - return pdfPage; - } catch (reason) { - console.error("Unable to get page for page view", reason); - return null; + const pageView = this.#pdfViewer.getPageView(pageNumber - 1); + if (pageView?.renderingState !== RenderingStates.FINISHED) { + this._pageOpenPending.add(pageNumber); + return; } + this._pageOpenPending.delete(pageNumber); + const actionsPromise = (async () => { + const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); + if (pdfDocument !== this.#pdfDocument) { + return; + } + await this.#scripting?.dispatchEventInSandbox({ + id: "page", + name: "PageOpen", + pageNumber, + actions + }); + })(); + visitedPages.set(pageNumber, actionsPromise); } - #getScrollAhead(visible) { - if (visible.first?.id === 1) { - return true; - } else if (visible.last?.id === this.pagesCount) { - return false; + async #dispatchPageClose(pageNumber) { + const pdfDocument = this.#pdfDocument, + visitedPages = this._visitedPages; + if (!this.#closeCapability) { + return; } - switch (this._scrollMode) { - case ScrollMode.PAGE: - return this.#scrollModePageState.scrollDown; - case ScrollMode.HORIZONTAL: - return this.scroll.right; + if (this._pageOpenPending.has(pageNumber)) { + return; } - return this.scroll.down; - } - forceRendering(currentlyVisiblePages) { - const visiblePages = currentlyVisiblePages || this._getVisiblePages(); - const scrollAhead = this.#getScrollAhead(visiblePages); - const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL; - const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); - if (pageView) { - this.#ensurePdfPageLoaded(pageView).then(() => { - this.renderingQueue.renderView(pageView); - }); - return true; + const actionsPromise = visitedPages.get(pageNumber); + if (!actionsPromise) { + return; } - return false; - } - get hasEqualPageSizes() { - const firstPageView = this._pages[0]; - for (let i = 1, ii = this._pages.length; i < ii; ++i) { - const pageView = this._pages[i]; - if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { - return false; - } + visitedPages.set(pageNumber, null); + await actionsPromise; + if (pdfDocument !== this.#pdfDocument) { + return; } - return true; - } - getPagesOverview() { - let initialOrientation; - return this._pages.map(pageView => { - const viewport = pageView.pdfPage.getViewport({ - scale: 1 - }); - const orientation = isPortraitOrientation(viewport); - if (initialOrientation === undefined) { - initialOrientation = orientation; - } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) { - return { - width: viewport.height, - height: viewport.width, - rotation: (viewport.rotation - 90) % 360 - }; - } - return { - width: viewport.width, - height: viewport.height, - rotation: viewport.rotation - }; + await this.#scripting?.dispatchEventInSandbox({ + id: "page", + name: "PageClose", + pageNumber }); } - get optionalContentConfigPromise() { - if (!this.pdfDocument) { - return Promise.resolve(null); - } - if (!this._optionalContentConfigPromise) { - console.error("optionalContentConfigPromise: Not initialized yet."); - return this.pdfDocument.getOptionalContentConfig({ - intent: "display" - }); + #initScripting() { + this.#destroyCapability = Promise.withResolvers(); + if (this.#scripting) { + throw new Error("#initScripting: Scripting already exists."); } - return this._optionalContentConfigPromise; + return this.#externalServices.createScripting(); } - set optionalContentConfigPromise(promise) { - if (!(promise instanceof Promise)) { - throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); - } - if (!this.pdfDocument) { + async #destroyScripting() { + if (!this.#scripting) { + this.#pdfDocument = null; + this.#destroyCapability?.resolve(); return; } - if (!this._optionalContentConfigPromise) { - return; + if (this.#closeCapability) { + await Promise.race([this.#closeCapability.promise, new Promise(resolve => { + setTimeout(resolve, 1000); + })]).catch(() => {}); + this.#closeCapability = null; } - this._optionalContentConfigPromise = promise; - this.refresh(false, { - optionalContentConfigPromise: promise - }); - this.eventBus.dispatch("optionalcontentconfigchanged", { - source: this, - promise + this.#pdfDocument = null; + try { + await this.#scripting.destroySandbox(); + } catch {} + this.#willPrintCapability?.reject(new Error("Scripting destroyed.")); + this.#willPrintCapability = null; + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + this._pageOpenPending.clear(); + this._visitedPages.clear(); + this.#scripting = null; + this.#ready = false; + this.#destroyCapability?.resolve(); + } +} + +;// ./web/pdf_scripting_manager.component.js + + +class PDFScriptingManagerComponents extends PDFScriptingManager { + constructor(options) { + if (!options.externalServices) { + window.addEventListener("updatefromsandbox", event => { + options.eventBus.dispatch("updatefromsandbox", { + source: window, + detail: event.detail + }); + }); + } + options.externalServices ||= { + createScripting: () => new GenericScripting(options.sandboxBundleSrc) + }; + options.docProperties ||= pdfDocument => docProperties(pdfDocument); + super(options); + } +} + +;// ./web/pdf_rendering_queue.js + + +const CLEANUP_TIMEOUT = 30000; +class PDFRenderingQueue { + constructor() { + this.pdfViewer = null; + this.pdfThumbnailViewer = null; + this.onIdle = null; + this.highestPriorityPage = null; + this.idleTimeout = null; + this.printing = false; + this.isThumbnailViewEnabled = false; + Object.defineProperty(this, "hasViewer", { + value: () => !!this.pdfViewer }); } - get scrollMode() { - return this._scrollMode; + setViewer(pdfViewer) { + this.pdfViewer = pdfViewer; } - set scrollMode(mode) { - if (this._scrollMode === mode) { - return; - } - if (!isValidScrollMode(mode)) { - throw new Error(`Invalid scroll mode: ${mode}`); + setThumbnailViewer(pdfThumbnailViewer) { + this.pdfThumbnailViewer = pdfThumbnailViewer; + } + isHighestPriority(view) { + return this.highestPriorityPage === view.renderingId; + } + renderHighestPriority(currentlyVisiblePages) { + if (this.idleTimeout) { + clearTimeout(this.idleTimeout); + this.idleTimeout = null; } - if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { + if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { return; } - this._previousScrollMode = this._scrollMode; - this._scrollMode = mode; - this.eventBus.dispatch("scrollmodechanged", { - source: this, - mode - }); - this._updateScrollMode(this._currentPageNumber); - } - _updateScrollMode(pageNumber = null) { - const scrollMode = this._scrollMode, - viewer = this.viewer; - viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL); - viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED); - if (!this.pdfDocument || !pageNumber) { + if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) { return; } - if (scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else if (this._previousScrollMode === ScrollMode.PAGE) { - this._updateSpreadMode(); - } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); - } - this._setCurrentPageNumber(pageNumber, true); - this.update(); - } - get spreadMode() { - return this._spreadMode; - } - set spreadMode(mode) { - if (this._spreadMode === mode) { + if (this.printing) { return; } - if (!isValidSpreadMode(mode)) { - throw new Error(`Invalid spread mode: ${mode}`); + if (this.onIdle) { + this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); } - this._spreadMode = mode; - this.eventBus.dispatch("spreadmodechanged", { - source: this, - mode - }); - this._updateSpreadMode(this._currentPageNumber); } - _updateSpreadMode(pageNumber = null) { - if (!this.pdfDocument) { - return; + getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { + const visibleViews = visible.views, + numVisible = visibleViews.length; + if (numVisible === 0) { + return null; } - const viewer = this.viewer, - pages = this._pages; - if (this._scrollMode === ScrollMode.PAGE) { - this.#ensurePageViewVisible(); - } else { - viewer.textContent = ""; - if (this._spreadMode === SpreadMode.NONE) { - for (const pageView of this._pages) { - viewer.append(pageView.div); + for (let i = 0; i < numVisible; i++) { + const view = visibleViews[i].view; + if (!this.isViewFinished(view)) { + return view; + } + } + const firstId = visible.first.id, + lastId = visible.last.id; + if (lastId - firstId + 1 > numVisible) { + const visibleIds = visible.ids; + for (let i = 1, ii = lastId - firstId; i < ii; i++) { + const holeId = scrolledDown ? firstId + i : lastId - i; + if (visibleIds.has(holeId)) { + continue; } - } else { - const parity = this._spreadMode - 1; - let spread = null; - for (let i = 0, ii = pages.length; i < ii; ++i) { - if (spread === null) { - spread = document.createElement("div"); - spread.className = "spread"; - viewer.append(spread); - } else if (i % 2 === parity) { - spread = spread.cloneNode(false); - viewer.append(spread); - } - spread.append(pages[i].div); + const holeView = views[holeId - 1]; + if (!this.isViewFinished(holeView)) { + return holeView; } } } - if (!pageNumber) { - return; + let preRenderIndex = scrolledDown ? lastId : firstId - 2; + let preRenderView = views[preRenderIndex]; + if (preRenderView && !this.isViewFinished(preRenderView)) { + return preRenderView; } - if (this._currentScaleValue && isNaN(this._currentScaleValue)) { - this.#setScale(this._currentScaleValue, { - noScroll: true - }); + if (preRenderExtra) { + preRenderIndex += scrolledDown ? 1 : -1; + preRenderView = views[preRenderIndex]; + if (preRenderView && !this.isViewFinished(preRenderView)) { + return preRenderView; + } } - this._setCurrentPageNumber(pageNumber, true); - this.update(); + return null; } - _getPageAdvance(currentPageNumber, previous = false) { - switch (this._scrollMode) { - case ScrollMode.WRAPPED: - { - const { - views - } = this._getVisiblePages(), - pageLayout = new Map(); - for (const { - id, - y, - percent, - widthPercent - } of views) { - if (percent === 0 || widthPercent < 100) { - continue; - } - let yArray = pageLayout.get(y); - if (!yArray) { - pageLayout.set(y, yArray ||= []); - } - yArray.push(id); - } - for (const yArray of pageLayout.values()) { - const currentIndex = yArray.indexOf(currentPageNumber); - if (currentIndex === -1) { - continue; - } - const numPages = yArray.length; - if (numPages === 1) { - break; - } - if (previous) { - for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { - const currentId = yArray[i], - expectedId = yArray[i + 1] - 1; - if (currentId < expectedId) { - return currentPageNumber - expectedId; - } - } - } else { - for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { - const currentId = yArray[i], - expectedId = yArray[i - 1] + 1; - if (currentId > expectedId) { - return expectedId - currentPageNumber; - } - } - } - if (previous) { - const firstId = yArray[0]; - if (firstId < currentPageNumber) { - return currentPageNumber - firstId + 1; - } - } else { - const lastId = yArray[numPages - 1]; - if (lastId > currentPageNumber) { - return lastId - currentPageNumber + 1; - } - } - break; - } - break; - } - case ScrollMode.HORIZONTAL: - { - break; - } - case ScrollMode.PAGE: - case ScrollMode.VERTICAL: - { - if (this._spreadMode === SpreadMode.NONE) { - break; - } - const parity = this._spreadMode - 1; - if (previous && currentPageNumber % 2 !== parity) { - break; - } else if (!previous && currentPageNumber % 2 === parity) { - break; - } - const { - views - } = this._getVisiblePages(), - expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; - for (const { - id, - percent, - widthPercent - } of views) { - if (id !== expectedId) { - continue; - } - if (percent > 0 && widthPercent === 100) { - return 2; - } - break; + isViewFinished(view) { + return view.renderingState === RenderingStates.FINISHED; + } + renderView(view) { + switch (view.renderingState) { + case RenderingStates.FINISHED: + return false; + case RenderingStates.PAUSED: + this.highestPriorityPage = view.renderingId; + view.resume(); + break; + case RenderingStates.RUNNING: + this.highestPriorityPage = view.renderingId; + break; + case RenderingStates.INITIAL: + this.highestPriorityPage = view.renderingId; + view.draw().finally(() => { + this.renderHighestPriority(); + }).catch(reason => { + if (reason instanceof RenderingCancelledException) { + return; } - break; - } + console.error("renderView:", reason); + }); + break; } - return 1; + return true; } - nextPage() { - const currentPageNumber = this._currentPageNumber, - pagesCount = this.pagesCount; - if (currentPageNumber >= pagesCount) { - return false; +} + +;// ./web/pdf_viewer.js + + + + + + +const DEFAULT_CACHE_SIZE = 10; +const PagesCountLimit = { + FORCE_SCROLL_MODE_PAGE: 10000, + FORCE_LAZY_PAGE_INIT: 5000, + PAUSE_EAGER_PAGE_INIT: 250 +}; +function isValidAnnotationEditorMode(mode) { + return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE; +} +class PDFPageViewBuffer { + #buf = new Set(); + #size = 0; + constructor(size) { + this.#size = size; + } + push(view) { + const buf = this.#buf; + if (buf.has(view)) { + buf.delete(view); + } + buf.add(view); + if (buf.size > this.#size) { + this.#destroyFirstView(); } - const advance = this._getPageAdvance(currentPageNumber, false) || 1; - this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); - return true; } - previousPage() { - const currentPageNumber = this._currentPageNumber; - if (currentPageNumber <= 1) { - return false; + resize(newSize, idsToKeep = null) { + this.#size = newSize; + const buf = this.#buf; + if (idsToKeep) { + const ii = buf.size; + let i = 1; + for (const view of buf) { + if (idsToKeep.has(view.id)) { + buf.delete(view); + buf.add(view); + } + if (++i > ii) { + break; + } + } + } + while (buf.size > this.#size) { + this.#destroyFirstView(); } - const advance = this._getPageAdvance(currentPageNumber, true) || 1; - this.currentPageNumber = Math.max(currentPageNumber - advance, 1); - return true; } - updateScale({ - drawingDelay, - scaleFactor = null, - steps = null, - origin - }) { - if (steps === null && scaleFactor === null) { - throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided."); + has(view) { + return this.#buf.has(view); + } + [Symbol.iterator]() { + return this.#buf.keys(); + } + #destroyFirstView() { + const firstView = this.#buf.keys().next().value; + firstView?.destroy(); + this.#buf.delete(firstView); + } +} +class PDFViewer { + #buffer = null; + #altTextManager = null; + #annotationEditorHighlightColors = null; + #annotationEditorMode = AnnotationEditorType.NONE; + #annotationEditorUIManager = null; + #annotationMode = AnnotationMode.ENABLE_FORMS; + #containerTopLeft = null; + #editorUndoBar = null; + #enableHWA = false; + #enableHighlightFloatingButton = false; + #enablePermissions = false; + #enableUpdatedAddImage = false; + #enableNewAltTextWhenAddingImage = false; + #eventAbortController = null; + #mlManager = null; + #switchAnnotationEditorModeAC = null; + #switchAnnotationEditorModeTimeoutId = null; + #getAllTextInProgress = false; + #hiddenCopyElement = null; + #interruptCopyCondition = false; + #previousContainerHeight = 0; + #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); + #scrollModePageState = null; + #scaleTimeoutId = null; + #supportsPinchToZoom = true; + #textLayerMode = TextLayerMode.ENABLE; + constructor(options) { + const viewerVersion = "4.10.38"; + if (version !== viewerVersion) { + throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`); } - if (!this.pdfDocument) { - return; + this.container = options.container; + this.viewer = options.viewer || options.container.firstElementChild; + if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") { + throw new Error("Invalid `container` and/or `viewer` option."); } - let newScale = this._currentScale; - if (scaleFactor > 0 && scaleFactor !== 1) { - newScale = Math.round(newScale * scaleFactor * 100) / 100; - } else if (steps) { - const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA; - const round = steps > 0 ? Math.ceil : Math.floor; - steps = Math.abs(steps); - do { - newScale = round((newScale * delta).toFixed(2) * 10) / 10; - } while (--steps > 0); + if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { + throw new Error("The `container` must be absolutely positioned."); } - newScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale)); - this.#setScale(newScale, { - noScroll: false, - drawingDelay, - origin + this.#resizeObserver.observe(this.container); + this.eventBus = options.eventBus; + this.linkService = options.linkService || new SimpleLinkService(); + this.downloadManager = options.downloadManager || null; + this.findController = options.findController || null; + this.#altTextManager = options.altTextManager || null; + this.#editorUndoBar = options.editorUndoBar || null; + if (this.findController) { + this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber); + } + this._scriptingManager = options.scriptingManager || null; + this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; + this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; + this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE; + this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null; + this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true; + this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true; + this.#enableNewAltTextWhenAddingImage = options.enableNewAltTextWhenAddingImage === true; + this.imageResourcesPath = options.imageResourcesPath || ""; + this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; + this.removePageBorders = options.removePageBorders || false; + this.maxCanvasPixels = options.maxCanvasPixels; + this.l10n = options.l10n; + this.l10n ||= new genericl10n_GenericL10n(); + this.#enablePermissions = options.enablePermissions || false; + this.pageColors = options.pageColors || null; + this.#mlManager = options.mlManager || null; + this.#enableHWA = options.enableHWA || false; + this.#supportsPinchToZoom = options.supportsPinchToZoom !== false; + this.defaultRenderingQueue = !options.renderingQueue; + if (this.defaultRenderingQueue) { + this.renderingQueue = new PDFRenderingQueue(); + this.renderingQueue.setViewer(this); + } else { + this.renderingQueue = options.renderingQueue; + } + const { + abortSignal + } = options; + abortSignal?.addEventListener("abort", () => { + this.#resizeObserver.disconnect(); + this.#resizeObserver = null; + }, { + once: true }); - } - increaseScale(options = {}) { - this.updateScale({ - ...options, - steps: options.steps ?? 1 + this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal); + this.presentationModeState = PresentationModeState.UNKNOWN; + this._resetView(); + if (this.removePageBorders) { + this.viewer.classList.add("removePageBorders"); + } + this.#updateContainerHeightCss(); + this.eventBus._on("thumbnailrendered", ({ + pageNumber, + pdfPage + }) => { + const pageView = this._pages[pageNumber - 1]; + if (!this.#buffer.has(pageView)) { + pdfPage?.cleanup(); + } }); + if (!options.l10n) { + this.l10n.translate(this.container); + } } - decreaseScale(options = {}) { - this.updateScale({ - ...options, - steps: -(options.steps ?? 1) - }); + get pagesCount() { + return this._pages.length; } - #updateContainerHeightCss(height = this.container.clientHeight) { - if (height !== this.#previousContainerHeight) { - this.#previousContainerHeight = height; - docStyle.setProperty("--viewer-container-height", `${height}px`); + getPageView(index) { + return this._pages[index]; + } + getCachedPageViews() { + return new Set(this.#buffer); + } + get pageViewsReady() { + return this._pages.every(pageView => pageView?.pdfPage); + } + get renderForms() { + return this.#annotationMode === AnnotationMode.ENABLE_FORMS; + } + get enableScripting() { + return !!this._scriptingManager; + } + get currentPageNumber() { + return this._currentPageNumber; + } + set currentPageNumber(val) { + if (!Number.isInteger(val)) { + throw new Error("Invalid page number."); + } + if (!this.pdfDocument) { + return; + } + if (!this._setCurrentPageNumber(val, true)) { + console.error(`currentPageNumber: "${val}" is not a valid page.`); } } - #resizeObserverCallback(entries) { - for (const entry of entries) { - if (entry.target === this.container) { - this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize)); - this.#containerTopLeft = null; - break; + _setCurrentPageNumber(val, resetCurrentPageView = false) { + if (this._currentPageNumber === val) { + if (resetCurrentPageView) { + this.#resetCurrentPageView(); } + return true; + } + if (!(0 < val && val <= this.pagesCount)) { + return false; + } + const previous = this._currentPageNumber; + this._currentPageNumber = val; + this.eventBus.dispatch("pagechanging", { + source: this, + pageNumber: val, + pageLabel: this._pageLabels?.[val - 1] ?? null, + previous + }); + if (resetCurrentPageView) { + this.#resetCurrentPageView(); } + return true; } - get containerTopLeft() { - return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft]; + get currentPageLabel() { + return this._pageLabels?.[this._currentPageNumber - 1] ?? null; } - #cleanupSwitchAnnotationEditorMode() { - this.#switchAnnotationEditorModeAC?.abort(); - this.#switchAnnotationEditorModeAC = null; - if (this.#switchAnnotationEditorModeTimeoutId !== null) { - clearTimeout(this.#switchAnnotationEditorModeTimeoutId); - this.#switchAnnotationEditorModeTimeoutId = null; + set currentPageLabel(val) { + if (!this.pdfDocument) { + return; + } + let page = val | 0; + if (this._pageLabels) { + const i = this._pageLabels.indexOf(val); + if (i >= 0) { + page = i + 1; + } + } + if (!this._setCurrentPageNumber(page, true)) { + console.error(`currentPageLabel: "${val}" is not a valid page.`); } } - get annotationEditorMode() { - return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE; + get currentScale() { + return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; } - set annotationEditorMode({ - mode, - editId = null, - isFromKeyboard = false - }) { - if (!this.#annotationEditorUIManager) { - throw new Error(`The AnnotationEditor is not enabled.`); + set currentScale(val) { + if (isNaN(val)) { + throw new Error("Invalid numeric scale."); } - if (this.#annotationEditorMode === mode) { + if (!this.pdfDocument) { return; } - if (!isValidAnnotationEditorMode(mode)) { - throw new Error(`Invalid AnnotationEditor mode: ${mode}`); - } + this.#setScale(val, { + noScroll: false + }); + } + get currentScaleValue() { + return this._currentScaleValue; + } + set currentScaleValue(val) { if (!this.pdfDocument) { return; } - if (mode === AnnotationEditorType.STAMP) { - this.#mlManager?.loadModel("altText"); - } - const { - eventBus - } = this; - const updater = () => { - this.#cleanupSwitchAnnotationEditorMode(); - this.#annotationEditorMode = mode; - this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard); - eventBus.dispatch("annotationeditormodechanged", { - source: this, - mode - }); - }; - if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) { - const isEditing = mode !== AnnotationEditorType.NONE; - if (!isEditing) { - this.pdfDocument.annotationStorage.resetModifiedIds(); - } - for (const pageView of this._pages) { - pageView.toggleEditingMode(isEditing); - } - const idsToRefresh = this.#switchToEditAnnotationMode(); - if (isEditing && idsToRefresh) { - this.#cleanupSwitchAnnotationEditorMode(); - this.#switchAnnotationEditorModeAC = new AbortController(); - const signal = AbortSignal.any([this.#eventAbortController.signal, this.#switchAnnotationEditorModeAC.signal]); - eventBus._on("pagerendered", ({ - pageNumber - }) => { - idsToRefresh.delete(pageNumber); - if (idsToRefresh.size === 0) { - this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0); - } - }, { - signal - }); - return; - } - } - updater(); + this.#setScale(val, { + noScroll: false + }); } - refresh(noUpdate = false, updateArgs = Object.create(null)) { + get pagesRotation() { + return this._pagesRotation; + } + set pagesRotation(rotation) { + if (!isValidRotation(rotation)) { + throw new Error("Invalid pages rotation angle."); + } if (!this.pdfDocument) { return; } - for (const pageView of this._pages) { - pageView.update(updateArgs); + rotation %= 360; + if (rotation < 0) { + rotation += 360; } - if (this.#scaleTimeoutId !== null) { - clearTimeout(this.#scaleTimeoutId); - this.#scaleTimeoutId = null; + if (this._pagesRotation === rotation) { + return; } - if (!noUpdate) { + this._pagesRotation = rotation; + const pageNumber = this._currentPageNumber; + this.refresh(true, { + rotation + }); + if (this._currentScaleValue) { + this.#setScale(this._currentScaleValue, { + noScroll: true + }); + } + this.eventBus.dispatch("rotationchanging", { + source: this, + pagesRotation: rotation, + pageNumber + }); + if (this.defaultRenderingQueue) { this.update(); } } -} - -;// ./web/secondary_toolbar.js - - -class SecondaryToolbar { - #opts; - constructor(options, eventBus) { - this.#opts = options; - const buttons = [{ - element: options.presentationModeButton, - eventName: "presentationmode", - close: true - }, { - element: options.printButton, - eventName: "print", - close: true - }, { - element: options.downloadButton, - eventName: "download", - close: true - }, { - element: options.viewBookmarkButton, - eventName: null, - close: true - }, { - element: options.firstPageButton, - eventName: "firstpage", - close: true - }, { - element: options.lastPageButton, - eventName: "lastpage", - close: true - }, { - element: options.pageRotateCwButton, - eventName: "rotatecw", - close: false - }, { - element: options.pageRotateCcwButton, - eventName: "rotateccw", - close: false - }, { - element: options.cursorSelectToolButton, - eventName: "switchcursortool", - eventDetails: { - tool: CursorTool.SELECT - }, - close: true - }, { - element: options.cursorHandToolButton, - eventName: "switchcursortool", - eventDetails: { - tool: CursorTool.HAND - }, - close: true - }, { - element: options.scrollPageButton, - eventName: "switchscrollmode", - eventDetails: { - mode: ScrollMode.PAGE + get firstPagePromise() { + return this.pdfDocument ? this._firstPageCapability.promise : null; + } + get onePageRendered() { + return this.pdfDocument ? this._onePageRenderedCapability.promise : null; + } + get pagesPromise() { + return this.pdfDocument ? this._pagesCapability.promise : null; + } + get _layerProperties() { + const self = this; + return shadow(this, "_layerProperties", { + get annotationEditorUIManager() { + return self.#annotationEditorUIManager; }, - close: true - }, { - element: options.scrollVerticalButton, - eventName: "switchscrollmode", - eventDetails: { - mode: ScrollMode.VERTICAL + get annotationStorage() { + return self.pdfDocument?.annotationStorage; }, - close: true - }, { - element: options.scrollHorizontalButton, - eventName: "switchscrollmode", - eventDetails: { - mode: ScrollMode.HORIZONTAL + get downloadManager() { + return self.downloadManager; }, - close: true - }, { - element: options.scrollWrappedButton, - eventName: "switchscrollmode", - eventDetails: { - mode: ScrollMode.WRAPPED + get enableScripting() { + return !!self._scriptingManager; }, - close: true - }, { - element: options.spreadNoneButton, - eventName: "switchspreadmode", - eventDetails: { - mode: SpreadMode.NONE + get fieldObjectsPromise() { + return self.pdfDocument?.getFieldObjects(); }, - close: true - }, { - element: options.spreadOddButton, - eventName: "switchspreadmode", - eventDetails: { - mode: SpreadMode.ODD + get findController() { + return self.findController; }, - close: true - }, { - element: options.spreadEvenButton, - eventName: "switchspreadmode", - eventDetails: { - mode: SpreadMode.EVEN + get hasJSActionsPromise() { + return self.pdfDocument?.hasJSActions(); }, - close: true - }, { - element: options.imageAltTextSettingsButton, - eventName: "imagealttextsettings", - close: true - }, { - element: options.documentPropertiesButton, - eventName: "documentproperties", - close: true - }]; - buttons.push({ - element: options.openFileButton, - eventName: "openfile", - close: true - }); - this.eventBus = eventBus; - this.opened = false; - this.#bindListeners(buttons); - this.reset(); - } - get isOpen() { - return this.opened; - } - setPageNumber(pageNumber) { - this.pageNumber = pageNumber; - this.#updateUIState(); - } - setPagesCount(pagesCount) { - this.pagesCount = pagesCount; - this.#updateUIState(); - } - reset() { - this.pageNumber = 0; - this.pagesCount = 0; - this.#updateUIState(); - this.eventBus.dispatch("switchcursortool", { - source: this, - reset: true - }); - this.#scrollModeChanged({ - mode: ScrollMode.VERTICAL - }); - this.#spreadModeChanged({ - mode: SpreadMode.NONE + get linkService() { + return self.linkService; + } }); } - #updateUIState() { - const { - firstPageButton, - lastPageButton, - pageRotateCwButton, - pageRotateCcwButton - } = this.#opts; - firstPageButton.disabled = this.pageNumber <= 1; - lastPageButton.disabled = this.pageNumber >= this.pagesCount; - pageRotateCwButton.disabled = this.pagesCount === 0; - pageRotateCcwButton.disabled = this.pagesCount === 0; - } - #bindListeners(buttons) { - const { - eventBus - } = this; - const { - toggleButton - } = this.#opts; - toggleButton.addEventListener("click", this.toggle.bind(this)); - for (const { - element, - eventName, - close, - eventDetails - } of buttons) { - element.addEventListener("click", evt => { - if (eventName !== null) { - eventBus.dispatch(eventName, { - source: this, - ...eventDetails - }); - } - if (close) { - this.close(); - } - eventBus.dispatch("reporttelemetry", { - source: this, - details: { - type: "buttons", - data: { - id: element.id - } - } - }); - }); + #initializePermissions(permissions) { + const params = { + annotationEditorMode: this.#annotationEditorMode, + annotationMode: this.#annotationMode, + textLayerMode: this.#textLayerMode + }; + if (!permissions) { + return params; + } + if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) { + params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS; + } + if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) { + params.annotationEditorMode = AnnotationEditorType.DISABLE; } - eventBus._on("cursortoolchanged", this.#cursorToolChanged.bind(this)); - eventBus._on("scrollmodechanged", this.#scrollModeChanged.bind(this)); - eventBus._on("spreadmodechanged", this.#spreadModeChanged.bind(this)); - } - #cursorToolChanged({ - tool, - disabled - }) { - const { - cursorSelectToolButton, - cursorHandToolButton - } = this.#opts; - toggleCheckedBtn(cursorSelectToolButton, tool === CursorTool.SELECT); - toggleCheckedBtn(cursorHandToolButton, tool === CursorTool.HAND); - cursorSelectToolButton.disabled = disabled; - cursorHandToolButton.disabled = disabled; - } - #scrollModeChanged({ - mode - }) { - const { - scrollPageButton, - scrollVerticalButton, - scrollHorizontalButton, - scrollWrappedButton, - spreadNoneButton, - spreadOddButton, - spreadEvenButton - } = this.#opts; - toggleCheckedBtn(scrollPageButton, mode === ScrollMode.PAGE); - toggleCheckedBtn(scrollVerticalButton, mode === ScrollMode.VERTICAL); - toggleCheckedBtn(scrollHorizontalButton, mode === ScrollMode.HORIZONTAL); - toggleCheckedBtn(scrollWrappedButton, mode === ScrollMode.WRAPPED); - const forceScrollModePage = this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE; - scrollPageButton.disabled = forceScrollModePage; - scrollVerticalButton.disabled = forceScrollModePage; - scrollHorizontalButton.disabled = forceScrollModePage; - scrollWrappedButton.disabled = forceScrollModePage; - const isHorizontal = mode === ScrollMode.HORIZONTAL; - spreadNoneButton.disabled = isHorizontal; - spreadOddButton.disabled = isHorizontal; - spreadEvenButton.disabled = isHorizontal; - } - #spreadModeChanged({ - mode - }) { - const { - spreadNoneButton, - spreadOddButton, - spreadEvenButton - } = this.#opts; - toggleCheckedBtn(spreadNoneButton, mode === SpreadMode.NONE); - toggleCheckedBtn(spreadOddButton, mode === SpreadMode.ODD); - toggleCheckedBtn(spreadEvenButton, mode === SpreadMode.EVEN); - } - open() { - if (this.opened) { - return; + if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) { + params.annotationMode = AnnotationMode.ENABLE; } - this.opened = true; - const { - toggleButton, - toolbar - } = this.#opts; - toggleExpandedBtn(toggleButton, true, toolbar); + return params; } - close() { - if (!this.opened) { + async #onePageRenderedOrForceFetch(signal) { + if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) { return; } - this.opened = false; - const { - toggleButton, - toolbar - } = this.#opts; - toggleExpandedBtn(toggleButton, false, toolbar); - } - toggle() { - if (this.opened) { - this.close(); - } else { - this.open(); - } - } -} - -;// ./web/toolbar.js - - -class Toolbar { - #opts; - constructor(options, eventBus, toolbarDensity = 0) { - this.#opts = options; - this.eventBus = eventBus; - const buttons = [{ - element: options.previous, - eventName: "previouspage" - }, { - element: options.next, - eventName: "nextpage" - }, { - element: options.zoomIn, - eventName: "zoomin" - }, { - element: options.zoomOut, - eventName: "zoomout" - }, { - element: options.print, - eventName: "print" - }, { - element: options.download, - eventName: "download" - }, { - element: options.editorFreeTextButton, - eventName: "switchannotationeditormode", - eventDetails: { - get mode() { - const { - classList - } = options.editorFreeTextButton; - return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.FREETEXT; - } - } - }, { - element: options.editorHighlightButton, - eventName: "switchannotationeditormode", - eventDetails: { - get mode() { - const { - classList - } = options.editorHighlightButton; - return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.HIGHLIGHT; - } + const hiddenCapability = Promise.withResolvers(), + ac = new AbortController(); + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "hidden") { + hiddenCapability.resolve(); } }, { - element: options.editorInkButton, - eventName: "switchannotationeditormode", - eventDetails: { - get mode() { - const { - classList - } = options.editorInkButton; - return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.INK; - } + signal: typeof AbortSignal.any === "function" ? AbortSignal.any([signal, ac.signal]) : signal + }); + await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]); + ac.abort(); + } + async getAllText() { + const texts = []; + const buffer = []; + for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) { + if (this.#interruptCopyCondition) { + return null; } - }, { - element: options.editorStampButton, - eventName: "switchannotationeditormode", - eventDetails: { - get mode() { - const { - classList - } = options.editorStampButton; - return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.STAMP; + buffer.length = 0; + const page = await this.pdfDocument.getPage(pageNum); + const { + items + } = await page.getTextContent(); + for (const item of items) { + if (item.str) { + buffer.push(item.str); } - }, - telemetry: { - type: "editing", - data: { - action: "pdfjs.image.icon_click" + if (item.hasEOL) { + buffer.push("\n"); } } - }]; - this.#bindListeners(buttons); - this.#updateToolbarDensity({ - value: toolbarDensity - }); - this.reset(); - } - #updateToolbarDensity({ - value - }) { - let name = "normal"; - switch (value) { - case 1: - name = "compact"; - break; - case 2: - name = "touch"; - break; + texts.push(removeNullCharacters(buffer.join(""))); } - document.documentElement.setAttribute("data-toolbar-density", name); - } - #setAnnotationEditorUIManager(uiManager, parentContainer) { - const colorPicker = new ColorPicker({ - uiManager - }); - uiManager.setMainHighlightColorPicker(colorPicker); - parentContainer.append(colorPicker.renderMainDropdown()); - } - setPageNumber(pageNumber, pageLabel) { - this.pageNumber = pageNumber; - this.pageLabel = pageLabel; - this.#updateUIState(false); - } - setPagesCount(pagesCount, hasPageLabels) { - this.pagesCount = pagesCount; - this.hasPageLabels = hasPageLabels; - this.#updateUIState(true); + return texts.join("\n"); } - setPageScale(pageScaleValue, pageScale) { - this.pageScaleValue = (pageScaleValue || pageScale).toString(); - this.pageScale = pageScale; - this.#updateUIState(false); + #copyCallback(textLayerMode, event) { + const selection = document.getSelection(); + const { + focusNode, + anchorNode + } = selection; + if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) { + if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) { + stopEvent(event); + return; + } + this.#getAllTextInProgress = true; + const { + classList + } = this.viewer; + classList.add("copyAll"); + const ac = new AbortController(); + window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", { + signal: ac.signal + }); + this.getAllText().then(async text => { + if (text !== null) { + await navigator.clipboard.writeText(text); + } + }).catch(reason => { + console.warn(`Something goes wrong when extracting the text: ${reason.message}`); + }).finally(() => { + this.#getAllTextInProgress = false; + this.#interruptCopyCondition = false; + ac.abort(); + classList.remove("copyAll"); + }); + stopEvent(event); + } } - reset() { - this.pageNumber = 0; - this.pageLabel = null; - this.hasPageLabels = false; - this.pagesCount = 0; - this.pageScaleValue = DEFAULT_SCALE_VALUE; - this.pageScale = DEFAULT_SCALE; - this.#updateUIState(true); - this.updateLoadingIndicatorState(); - this.#editorModeChanged({ - mode: AnnotationEditorType.DISABLE + setDocument(pdfDocument) { + if (this.pdfDocument) { + this.eventBus.dispatch("pagesdestroy", { + source: this + }); + this._cancelRendering(); + this._resetView(); + this.findController?.setDocument(null); + this._scriptingManager?.setDocument(null); + this.#annotationEditorUIManager?.destroy(); + this.#annotationEditorUIManager = null; + } + this.pdfDocument = pdfDocument; + if (!pdfDocument) { + return; + } + const pagesCount = pdfDocument.numPages; + const firstPagePromise = pdfDocument.getPage(1); + const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ + intent: "display" }); - } - #bindListeners(buttons) { + const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve(); const { - eventBus + eventBus, + pageColors, + viewer } = this; + this.#eventAbortController = new AbortController(); const { - editorHighlightColorPicker, - editorHighlightButton, - pageNumber, - scaleSelect - } = this.#opts; - const self = this; - for (const { - element, - eventName, - eventDetails, - telemetry - } of buttons) { - element.addEventListener("click", evt => { - if (eventName !== null) { - eventBus.dispatch(eventName, { + signal + } = this.#eventAbortController; + if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { + console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document."); + const mode = this._scrollMode = ScrollMode.PAGE; + eventBus.dispatch("scrollmodechanged", { + source: this, + mode + }); + } + this._pagesCapability.promise.then(() => { + eventBus.dispatch("pagesloaded", { + source: this, + pagesCount + }); + }, () => {}); + const onBeforeDraw = evt => { + const pageView = this._pages[evt.pageNumber - 1]; + if (!pageView) { + return; + } + this.#buffer.push(pageView); + }; + eventBus._on("pagerender", onBeforeDraw, { + signal + }); + const onAfterDraw = evt => { + if (evt.cssTransform) { + return; + } + this._onePageRenderedCapability.resolve({ + timestamp: evt.timestamp + }); + eventBus._off("pagerendered", onAfterDraw); + }; + eventBus._on("pagerendered", onAfterDraw, { + signal + }); + Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this._firstPageCapability.resolve(firstPdfPage); + this._optionalContentConfigPromise = optionalContentConfigPromise; + const { + annotationEditorMode, + annotationMode, + textLayerMode + } = this.#initializePermissions(permissions); + if (textLayerMode !== TextLayerMode.DISABLE) { + const element = this.#hiddenCopyElement = document.createElement("div"); + element.id = "hiddenCopyElement"; + viewer.before(element); + } + if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { + const mode = annotationEditorMode; + if (pdfDocument.isPureXfa) { + console.warn("Warning: XFA-editing is not implemented."); + } else if (isValidAnnotationEditorMode(mode)) { + this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#enableNewAltTextWhenAddingImage, this.#mlManager, this.#editorUndoBar, this.#supportsPinchToZoom); + eventBus.dispatch("annotationeditoruimanager", { source: this, - ...eventDetails, - isFromKeyboard: evt.detail === 0 + uiManager: this.#annotationEditorUIManager + }); + if (mode !== AnnotationEditorType.NONE) { + if (mode === AnnotationEditorType.STAMP) { + this.#mlManager?.loadModel("altText"); + } + this.#annotationEditorUIManager.updateMode(mode); + } + } else { + console.error(`Invalid AnnotationEditor mode: ${mode}`); + } + } + const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer; + const scale = this.currentScale; + const viewport = firstPdfPage.getViewport({ + scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS + }); + viewer.style.setProperty("--scale-factor", viewport.scale); + if (pageColors?.background) { + viewer.style.setProperty("--page-bg-color", pageColors.background); + } + if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") { + viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); + viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText")); + } + for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { + const pageView = new PDFPageView({ + container: viewerElement, + eventBus, + id: pageNum, + scale, + defaultViewport: viewport.clone(), + optionalContentConfigPromise, + renderingQueue: this.renderingQueue, + textLayerMode, + annotationMode, + imageResourcesPath: this.imageResourcesPath, + maxCanvasPixels: this.maxCanvasPixels, + pageColors, + l10n: this.l10n, + layerProperties: this._layerProperties, + enableHWA: this.#enableHWA + }); + this._pages.push(pageView); + } + this._pages[0]?.setPdfPage(firstPdfPage); + if (this._scrollMode === ScrollMode.PAGE) { + this.#ensurePageViewVisible(); + } else if (this._spreadMode !== SpreadMode.NONE) { + this._updateSpreadMode(); + } + this.#onePageRenderedOrForceFetch(signal).then(async () => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this.findController?.setDocument(pdfDocument); + this._scriptingManager?.setDocument(pdfDocument); + if (this.#hiddenCopyElement) { + document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), { + signal }); } - if (telemetry) { - eventBus.dispatch("reporttelemetry", { + if (this.#annotationEditorUIManager) { + eventBus.dispatch("annotationeditormodechanged", { source: this, - details: telemetry + mode: this.#annotationEditorMode + }); + } + if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) { + this._pagesCapability.resolve(); + return; + } + let getPagesLeft = pagesCount - 1; + if (getPagesLeft <= 0) { + this._pagesCapability.resolve(); + return; + } + for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { + const promise = pdfDocument.getPage(pageNum).then(pdfPage => { + const pageView = this._pages[pageNum - 1]; + if (!pageView.pdfPage) { + pageView.setPdfPage(pdfPage); + } + if (--getPagesLeft === 0) { + this._pagesCapability.resolve(); + } + }, reason => { + console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); + if (--getPagesLeft === 0) { + this._pagesCapability.resolve(); + } }); + if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) { + await promise; + } } }); - } - pageNumber.addEventListener("click", function () { - this.select(); - }); - pageNumber.addEventListener("change", function () { - eventBus.dispatch("pagenumberchanged", { - source: self, - value: this.value + eventBus.dispatch("pagesinit", { + source: this }); - }); - scaleSelect.addEventListener("change", function () { - if (this.value === "custom") { - return; - } - eventBus.dispatch("scalechanged", { - source: self, - value: this.value + pdfDocument.getMetadata().then(({ + info + }) => { + if (pdfDocument !== this.pdfDocument) { + return; + } + if (info.Language) { + viewer.lang = info.Language; + } }); - }); - scaleSelect.addEventListener("click", function ({ - target - }) { - if (this.value === self.pageScaleValue && target.tagName.toUpperCase() === "OPTION") { - this.blur(); - } - }); - scaleSelect.oncontextmenu = noContextMenu; - eventBus._on("annotationeditormodechanged", this.#editorModeChanged.bind(this)); - eventBus._on("showannotationeditorui", ({ - mode - }) => { - switch (mode) { - case AnnotationEditorType.HIGHLIGHT: - editorHighlightButton.click(); - break; + if (this.defaultRenderingQueue) { + this.update(); } + }).catch(reason => { + console.error("Unable to initialize viewer", reason); + this._pagesCapability.reject(reason); }); - eventBus._on("toolbardensity", this.#updateToolbarDensity.bind(this)); - if (editorHighlightColorPicker) { - eventBus._on("annotationeditoruimanager", ({ - uiManager - }) => { - this.#setAnnotationEditorUIManager(uiManager, editorHighlightColorPicker); - }, { - once: true - }); - } } - #editorModeChanged({ - mode - }) { - const { - editorFreeTextButton, - editorFreeTextParamsToolbar, - editorHighlightButton, - editorHighlightParamsToolbar, - editorInkButton, - editorInkParamsToolbar, - editorStampButton, - editorStampParamsToolbar - } = this.#opts; - toggleExpandedBtn(editorFreeTextButton, mode === AnnotationEditorType.FREETEXT, editorFreeTextParamsToolbar); - toggleExpandedBtn(editorHighlightButton, mode === AnnotationEditorType.HIGHLIGHT, editorHighlightParamsToolbar); - toggleExpandedBtn(editorInkButton, mode === AnnotationEditorType.INK, editorInkParamsToolbar); - toggleExpandedBtn(editorStampButton, mode === AnnotationEditorType.STAMP, editorStampParamsToolbar); - const isDisable = mode === AnnotationEditorType.DISABLE; - editorFreeTextButton.disabled = isDisable; - editorHighlightButton.disabled = isDisable; - editorInkButton.disabled = isDisable; - editorStampButton.disabled = isDisable; - } - #updateUIState(resetNumPages = false) { - const { - pageNumber, - pagesCount, - pageScaleValue, - pageScale - } = this; - const opts = this.#opts; - if (resetNumPages) { - if (this.hasPageLabels) { - opts.pageNumber.type = "text"; - opts.numPages.setAttribute("data-l10n-id", "pdfjs-page-of-pages"); - } else { - opts.pageNumber.type = "number"; - opts.numPages.setAttribute("data-l10n-id", "pdfjs-of-pages"); - opts.numPages.setAttribute("data-l10n-args", JSON.stringify({ - pagesCount - })); - } - opts.pageNumber.max = pagesCount; + setPageLabels(labels) { + if (!this.pdfDocument) { + return; } - if (this.hasPageLabels) { - opts.pageNumber.value = this.pageLabel; - opts.numPages.setAttribute("data-l10n-args", JSON.stringify({ - pageNumber, - pagesCount - })); + if (!labels) { + this._pageLabels = null; + } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { + this._pageLabels = null; + console.error(`setPageLabels: Invalid page labels.`); } else { - opts.pageNumber.value = pageNumber; - } - opts.previous.disabled = pageNumber <= 1; - opts.next.disabled = pageNumber >= pagesCount; - opts.zoomOut.disabled = pageScale <= MIN_SCALE; - opts.zoomIn.disabled = pageScale >= MAX_SCALE; - let predefinedValueFound = false; - for (const option of opts.scaleSelect.options) { - if (option.value !== pageScaleValue) { - option.selected = false; - continue; - } - option.selected = true; - predefinedValueFound = true; + this._pageLabels = labels; } - if (!predefinedValueFound) { - opts.customScaleOption.selected = true; - opts.customScaleOption.setAttribute("data-l10n-args", JSON.stringify({ - scale: Math.round(pageScale * 10000) / 100 - })); + for (let i = 0, ii = this._pages.length; i < ii; i++) { + this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); } } - updateLoadingIndicatorState(loading = false) { - const { - pageNumber - } = this.#opts; - pageNumber.classList.toggle("loading", loading); + _resetView() { + this._pages = []; + this._currentPageNumber = 1; + this._currentScale = UNKNOWN_SCALE; + this._currentScaleValue = null; + this._pageLabels = null; + this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); + this._location = null; + this._pagesRotation = 0; + this._optionalContentConfigPromise = null; + this._firstPageCapability = Promise.withResolvers(); + this._onePageRenderedCapability = Promise.withResolvers(); + this._pagesCapability = Promise.withResolvers(); + this._scrollMode = ScrollMode.VERTICAL; + this._previousScrollMode = ScrollMode.UNKNOWN; + this._spreadMode = SpreadMode.NONE; + this.#scrollModePageState = { + previousPageNumber: 1, + scrollDown: true, + pages: [] + }; + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + this.viewer.textContent = ""; + this._updateScrollMode(); + this.viewer.removeAttribute("lang"); + this.#hiddenCopyElement?.remove(); + this.#hiddenCopyElement = null; + this.#cleanupSwitchAnnotationEditorMode(); } -} - -;// ./web/view_history.js -const DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20; -class ViewHistory { - constructor(fingerprint, cacheSize = DEFAULT_VIEW_HISTORY_CACHE_SIZE) { - this.fingerprint = fingerprint; - this.cacheSize = cacheSize; - this._initializedPromise = this._readFromStorage().then(databaseStr => { - const database = JSON.parse(databaseStr || "{}"); - let index = -1; - if (!Array.isArray(database.files)) { - database.files = []; + #ensurePageViewVisible() { + if (this._scrollMode !== ScrollMode.PAGE) { + throw new Error("#ensurePageViewVisible: Invalid scrollMode value."); + } + const pageNumber = this._currentPageNumber, + state = this.#scrollModePageState, + viewer = this.viewer; + viewer.textContent = ""; + state.pages.length = 0; + if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) { + const pageView = this._pages[pageNumber - 1]; + viewer.append(pageView.div); + state.pages.push(pageView); + } else { + const pageIndexSet = new Set(), + parity = this._spreadMode - 1; + if (parity === -1) { + pageIndexSet.add(pageNumber - 1); + } else if (pageNumber % 2 !== parity) { + pageIndexSet.add(pageNumber - 1); + pageIndexSet.add(pageNumber); } else { - while (database.files.length >= this.cacheSize) { - database.files.shift(); - } - for (let i = 0, ii = database.files.length; i < ii; i++) { - const branch = database.files[i]; - if (branch.fingerprint === this.fingerprint) { - index = i; - break; - } - } + pageIndexSet.add(pageNumber - 2); + pageIndexSet.add(pageNumber - 1); } - if (index === -1) { - index = database.files.push({ - fingerprint: this.fingerprint - }) - 1; + const spread = document.createElement("div"); + spread.className = "spread"; + if (this.isInPresentationMode) { + const dummyPage = document.createElement("div"); + dummyPage.className = "dummyPage"; + spread.append(dummyPage); } - this.file = database.files[index]; - this.database = database; - }); - } - async _writeToStorage() { - const databaseStr = JSON.stringify(this.database); - localStorage.setItem("pdfjs.history", databaseStr); - } - async _readFromStorage() { - return localStorage.getItem("pdfjs.history"); - } - async set(name, val) { - await this._initializedPromise; - this.file[name] = val; - return this._writeToStorage(); - } - async setMultiple(properties) { - await this._initializedPromise; - for (const name in properties) { - this.file[name] = properties[name]; - } - return this._writeToStorage(); - } - async get(name, defaultValue) { - await this._initializedPromise; - const val = this.file[name]; - return val !== undefined ? val : defaultValue; - } - async getMultiple(properties) { - await this._initializedPromise; - const values = Object.create(null); - for (const name in properties) { - const val = this.file[name]; - values[name] = val !== undefined ? val : properties[name]; + for (const i of pageIndexSet) { + const pageView = this._pages[i]; + if (!pageView) { + continue; + } + spread.append(pageView.div); + state.pages.push(pageView); + } + viewer.append(spread); } - return values; + state.scrollDown = pageNumber >= state.previousPageNumber; + state.previousPageNumber = pageNumber; } -} - -;// ./web/app.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -const FORCE_PAGES_LOADED_TIMEOUT = 10000; -const ViewOnLoad = { - UNKNOWN: -1, - PREVIOUS: 0, - INITIAL: 1 -}; -const PDFViewerApplication = { - initialBookmark: document.location.hash.substring(1), - _initializedCapability: { - ...Promise.withResolvers(), - settled: false - }, - appConfig: null, - pdfDocument: null, - pdfLoadingTask: null, - printService: null, - pdfViewer: null, - pdfThumbnailViewer: null, - pdfRenderingQueue: null, - pdfPresentationMode: null, - pdfDocumentProperties: null, - pdfLinkService: null, - pdfHistory: null, - pdfSidebar: null, - pdfOutlineViewer: null, - pdfAttachmentViewer: null, - pdfLayerViewer: null, - pdfCursorTools: null, - pdfScriptingManager: null, - store: null, - downloadManager: null, - overlayManager: null, - preferences: new Preferences(), - toolbar: null, - secondaryToolbar: null, - eventBus: null, - l10n: null, - annotationEditorParams: null, - imageAltTextSettings: null, - isInitialViewSet: false, - isViewerEmbedded: window.parent !== window, - url: "", - baseUrl: "", - mlManager: null, - _downloadUrl: "", - _eventBusAbortController: null, - _windowAbortController: null, - _globalAbortController: new AbortController(), - documentInfo: null, - metadata: null, - _contentDispositionFilename: null, - _contentLength: null, - _saveInProgress: false, - _wheelUnusedTicks: 0, - _wheelUnusedFactor: 1, - _touchManager: null, - _touchUnusedTicks: 0, - _touchUnusedFactor: 1, - _PDFBug: null, - _hasAnnotationEditors: false, - _title: document.title, - _printAnnotationStoragePromise: null, - _isCtrlKeyDown: false, - _caretBrowsing: null, - _isScrolling: false, - editorUndoBar: null, - async initialize(appConfig) { - this.appConfig = appConfig; - try { - await this.preferences.initializedPromise; - } catch (ex) { - console.error("initialize:", ex); - } - if (AppOptions.get("pdfBugEnabled")) { - await this._parseHashParams(); - } - let mode; - switch (AppOptions.get("viewerCssTheme")) { - case 1: - mode = "is-light"; - break; - case 2: - mode = "is-dark"; - break; - } - if (mode) { - document.documentElement.classList.add(mode); - } - this.l10n = await this.externalServices.createL10n(); - document.getElementsByTagName("html")[0].dir = this.l10n.getDirection(); - this.l10n.translate(appConfig.appContainer || document.documentElement); - if (this.isViewerEmbedded && AppOptions.get("externalLinkTarget") === LinkTarget.NONE) { - AppOptions.set("externalLinkTarget", LinkTarget.TOP); - } - await this._initializeViewerComponents(); - this.bindEvents(); - this.bindWindowEvents(); - this._initializedCapability.settled = true; - this._initializedCapability.resolve(); - }, - async _parseHashParams() { - const hash = document.location.hash.substring(1); - if (!hash) { + _scrollUpdate() { + if (this.pagesCount === 0) { return; } + this.update(); + } + #scrollIntoView(pageView, pageSpot = null) { const { - mainContainer, - viewerContainer - } = this.appConfig, - params = parseQueryString(hash); - const loadPDFBug = async () => { - if (this._PDFBug) { - return; - } - const { - PDFBug - } = await import(/*webpackIgnore: true*/AppOptions.get("debuggerSrc")); - this._PDFBug = PDFBug; - }; - if (params.get("disableworker") === "true") { - try { - GlobalWorkerOptions.workerSrc ||= AppOptions.get("workerSrc"); - await import(/*webpackIgnore: true*/PDFWorker.workerSrc); - } catch (ex) { - console.error("_parseHashParams:", ex); - } + div, + id + } = pageView; + if (this._currentPageNumber !== id) { + this._setCurrentPageNumber(id); } - if (params.has("textlayer")) { - switch (params.get("textlayer")) { - case "off": - AppOptions.set("textLayerMode", TextLayerMode.DISABLE); - break; - case "visible": - case "shadow": - case "hover": - viewerContainer.classList.add(`textLayer-${params.get("textlayer")}`); - try { - await loadPDFBug(); - this._PDFBug.loadCSS(); - } catch (ex) { - console.error("_parseHashParams:", ex); - } - break; - } + if (this._scrollMode === ScrollMode.PAGE) { + this.#ensurePageViewVisible(); + this.update(); } - if (params.has("pdfbug")) { - AppOptions.setAll({ - pdfBug: true, - fontExtraProperties: true - }); - const enabled = params.get("pdfbug").split(","); - try { - await loadPDFBug(); - this._PDFBug.init(mainContainer, enabled); - } catch (ex) { - console.error("_parseHashParams:", ex); + if (!pageSpot && !this.isInPresentationMode) { + const left = div.offsetLeft + div.clientLeft, + right = left + div.clientWidth; + const { + scrollLeft, + clientWidth + } = this.container; + if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) { + pageSpot = { + left: 0, + top: 0 + }; } } - if (params.has("locale")) { - AppOptions.set("localeProperties", { - lang: params.get("locale") - }); + scrollIntoView(div, pageSpot); + if (!this._currentScaleValue && this._location) { + this._location = null; } - const opts = { - disableAutoFetch: x => x === "true", - disableFontFace: x => x === "true", - disableHistory: x => x === "true", - disableRange: x => x === "true", - disableStream: x => x === "true", - verbosity: x => x | 0 - }; - for (const name in opts) { - const check = opts[name], - key = name.toLowerCase(); - if (params.has(key)) { - AppOptions.set(name, check(params.get(key))); + } + #isSameScale(newScale) { + return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15; + } + #setScaleUpdatePages(newScale, newValue, { + noScroll = false, + preset = false, + drawingDelay = -1, + origin = null + }) { + this._currentScaleValue = newValue.toString(); + if (this.#isSameScale(newScale)) { + if (preset) { + this.eventBus.dispatch("scalechanging", { + source: this, + scale: newScale, + presetValue: newValue + }); } + return; } - }, - async _initializeViewerComponents() { - const { - appConfig, - externalServices, - l10n - } = this; - const eventBus = new EventBus(); - this.eventBus = AppOptions.eventBus = eventBus; - this.mlManager?.setEventBus(eventBus, this._globalAbortController.signal); - this.overlayManager = new OverlayManager(); - const pdfRenderingQueue = new PDFRenderingQueue(); - pdfRenderingQueue.onIdle = this._cleanup.bind(this); - this.pdfRenderingQueue = pdfRenderingQueue; - const pdfLinkService = new PDFLinkService({ - eventBus, - externalLinkTarget: AppOptions.get("externalLinkTarget"), - externalLinkRel: AppOptions.get("externalLinkRel"), - ignoreDestinationZoom: AppOptions.get("ignoreDestinationZoom") - }); - this.pdfLinkService = pdfLinkService; - const downloadManager = this.downloadManager = new DownloadManager(); - const findController = new PDFFindController({ - linkService: pdfLinkService, - eventBus, - updateMatchesCountOnProgress: true - }); - this.findController = findController; - const pdfScriptingManager = new PDFScriptingManager({ - eventBus, - externalServices, - docProperties: this._scriptingDocProperties.bind(this) + this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS); + const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; + this.refresh(true, { + scale: newScale, + drawingDelay: postponeDrawing ? drawingDelay : -1 }); - this.pdfScriptingManager = pdfScriptingManager; - const container = appConfig.mainContainer, - viewer = appConfig.viewerContainer; - const annotationEditorMode = AppOptions.get("annotationEditorMode"); - const pageColors = AppOptions.get("forcePageColors") || window.matchMedia("(forced-colors: active)").matches ? { - background: AppOptions.get("pageColorsBackground"), - foreground: AppOptions.get("pageColorsForeground") - } : null; - let altTextManager; - if (AppOptions.get("enableUpdatedAddImage")) { - altTextManager = appConfig.newAltTextDialog ? new NewAltTextManager(appConfig.newAltTextDialog, this.overlayManager, eventBus) : null; - } else { - altTextManager = appConfig.altTextDialog ? new AltTextManager(appConfig.altTextDialog, container, this.overlayManager, eventBus) : null; - } - if (appConfig.editorUndoBar) { - this.editorUndoBar = new EditorUndoBar(appConfig.editorUndoBar, eventBus); + if (postponeDrawing) { + this.#scaleTimeoutId = setTimeout(() => { + this.#scaleTimeoutId = null; + this.refresh(); + }, drawingDelay); } - const enableHWA = AppOptions.get("enableHWA"); - const pdfViewer = new PDFViewer({ - container, - viewer, - eventBus, - renderingQueue: pdfRenderingQueue, - linkService: pdfLinkService, - downloadManager, - altTextManager, - editorUndoBar: this.editorUndoBar, - findController, - scriptingManager: AppOptions.get("enableScripting") && pdfScriptingManager, - l10n, - textLayerMode: AppOptions.get("textLayerMode"), - annotationMode: AppOptions.get("annotationMode"), - annotationEditorMode, - annotationEditorHighlightColors: AppOptions.get("highlightEditorColors"), - enableHighlightFloatingButton: AppOptions.get("enableHighlightFloatingButton"), - enableUpdatedAddImage: AppOptions.get("enableUpdatedAddImage"), - enableNewAltTextWhenAddingImage: AppOptions.get("enableNewAltTextWhenAddingImage"), - imageResourcesPath: AppOptions.get("imageResourcesPath"), - enablePrintAutoRotate: AppOptions.get("enablePrintAutoRotate"), - maxCanvasPixels: AppOptions.get("maxCanvasPixels"), - enablePermissions: AppOptions.get("enablePermissions"), - pageColors, - mlManager: this.mlManager, - abortSignal: this._globalAbortController.signal, - enableHWA, - supportsPinchToZoom: this.supportsPinchToZoom - }); - this.pdfViewer = pdfViewer; - pdfRenderingQueue.setViewer(pdfViewer); - pdfLinkService.setViewer(pdfViewer); - pdfScriptingManager.setViewer(pdfViewer); - if (appConfig.sidebar?.thumbnailView) { - this.pdfThumbnailViewer = new PDFThumbnailViewer({ - container: appConfig.sidebar.thumbnailView, - eventBus, - renderingQueue: pdfRenderingQueue, - linkService: pdfLinkService, - pageColors, - abortSignal: this._globalAbortController.signal, - enableHWA + const previousScale = this._currentScale; + this._currentScale = newScale; + if (!noScroll) { + let page = this._currentPageNumber, + dest; + if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { + page = this._location.pageNumber; + dest = [null, { + name: "XYZ" + }, this._location.left, this._location.top, null]; + } + this.scrollPageIntoView({ + pageNumber: page, + destArray: dest, + allowNegativeOffset: true }); - pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer); + if (Array.isArray(origin)) { + const scaleDiff = newScale / previousScale - 1; + const [top, left] = this.containerTopLeft; + this.container.scrollLeft += (origin[0] - left) * scaleDiff; + this.container.scrollTop += (origin[1] - top) * scaleDiff; + } } - if (!this.isViewerEmbedded && !AppOptions.get("disableHistory")) { - this.pdfHistory = new PDFHistory({ - linkService: pdfLinkService, - eventBus - }); - pdfLinkService.setHistory(this.pdfHistory); + this.eventBus.dispatch("scalechanging", { + source: this, + scale: newScale, + presetValue: preset ? newValue : undefined + }); + if (this.defaultRenderingQueue) { + this.update(); } - if (!this.supportsIntegratedFind && appConfig.findBar) { - this.findBar = new PDFFindBar(appConfig.findBar, appConfig.principalContainer, eventBus); + } + get #pageWidthScaleFactor() { + if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) { + return 2; } - if (appConfig.annotationEditorParams) { - if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { - this.annotationEditorParams = new AnnotationEditorParams(appConfig.annotationEditorParams, eventBus); - } else { - for (const id of ["editorModeButtons", "editorModeSeparator"]) { - document.getElementById(id)?.classList.add("hidden"); + return 1; + } + #setScale(value, options) { + let scale = parseFloat(value); + if (scale > 0) { + options.preset = false; + this.#setScaleUpdatePages(scale, value, options); + } else { + const currentPage = this._pages[this._currentPageNumber - 1]; + if (!currentPage) { + return; + } + let hPadding = SCROLLBAR_PADDING, + vPadding = VERTICAL_PADDING; + if (this.isInPresentationMode) { + hPadding = vPadding = 4; + if (this._spreadMode !== SpreadMode.NONE) { + hPadding *= 2; } + } else if (this.removePageBorders) { + hPadding = vPadding = 0; + } else if (this._scrollMode === ScrollMode.HORIZONTAL) { + [hPadding, vPadding] = [vPadding, hPadding]; } - } - if (this.mlManager && appConfig.secondaryToolbar?.imageAltTextSettingsButton) { - this.imageAltTextSettings = new ImageAltTextSettings(appConfig.altTextSettingsDialog, this.overlayManager, eventBus, this.mlManager); - } - if (appConfig.documentProperties) { - this.pdfDocumentProperties = new PDFDocumentProperties(appConfig.documentProperties, this.overlayManager, eventBus, l10n, () => this._docFilename); - } - if (appConfig.secondaryToolbar?.cursorHandToolButton) { - this.pdfCursorTools = new PDFCursorTools({ - container, - eventBus, - cursorToolOnLoad: AppOptions.get("cursorToolOnLoad") - }); - } - if (appConfig.toolbar) { - this.toolbar = new Toolbar(appConfig.toolbar, eventBus, AppOptions.get("toolbarDensity")); - } - if (appConfig.secondaryToolbar) { - if (AppOptions.get("enableAltText")) { - appConfig.secondaryToolbar.imageAltTextSettingsButton?.classList.remove("hidden"); - appConfig.secondaryToolbar.imageAltTextSettingsSeparator?.classList.remove("hidden"); + const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor; + const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; + switch (value) { + case "page-actual": + scale = 1; + break; + case "page-width": + scale = pageWidthScale; + break; + case "page-height": + scale = pageHeightScale; + break; + case "page-fit": + scale = Math.min(pageWidthScale, pageHeightScale); + break; + case "auto": + const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); + scale = Math.min(MAX_AUTO_SCALE, horizontalScale); + break; + default: + console.error(`#setScale: "${value}" is an unknown zoom value.`); + return; } - this.secondaryToolbar = new SecondaryToolbar(appConfig.secondaryToolbar, eventBus); + options.preset = true; + this.#setScaleUpdatePages(scale, value, options); } - if (this.supportsFullscreen && appConfig.secondaryToolbar?.presentationModeButton) { - this.pdfPresentationMode = new PDFPresentationMode({ - container, - pdfViewer, - eventBus + } + #resetCurrentPageView() { + const pageView = this._pages[this._currentPageNumber - 1]; + if (this.isInPresentationMode) { + this.#setScale(this._currentScaleValue, { + noScroll: true }); } - if (appConfig.passwordOverlay) { - this.passwordPrompt = new PasswordPrompt(appConfig.passwordOverlay, this.overlayManager, this.isViewerEmbedded); + this.#scrollIntoView(pageView); + } + pageLabelToPageNumber(label) { + if (!this._pageLabels) { + return null; } - if (appConfig.sidebar?.outlineView) { - this.pdfOutlineViewer = new PDFOutlineViewer({ - container: appConfig.sidebar.outlineView, - eventBus, - l10n, - linkService: pdfLinkService, - downloadManager - }); + const i = this._pageLabels.indexOf(label); + if (i < 0) { + return null; } - if (appConfig.sidebar?.attachmentsView) { - this.pdfAttachmentViewer = new PDFAttachmentViewer({ - container: appConfig.sidebar.attachmentsView, - eventBus, - l10n, - downloadManager - }); + return i + 1; + } + scrollPageIntoView({ + pageNumber, + destArray = null, + allowNegativeOffset = false, + ignoreDestinationZoom = false + }) { + if (!this.pdfDocument) { + return; } - if (appConfig.sidebar?.layersView) { - this.pdfLayerViewer = new PDFLayerViewer({ - container: appConfig.sidebar.layersView, - eventBus, - l10n - }); + const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; + if (!pageView) { + console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); + return; } - if (appConfig.sidebar) { - this.pdfSidebar = new PDFSidebar({ - elements: appConfig.sidebar, - eventBus, - l10n - }); - this.pdfSidebar.onToggled = this.forceRendering.bind(this); - this.pdfSidebar.onUpdateThumbnails = () => { - for (const pageView of pdfViewer.getCachedPageViews()) { - if (pageView.renderingState === RenderingStates.FINISHED) { - this.pdfThumbnailViewer.getThumbnail(pageView.id - 1)?.setImage(pageView); - } - } - this.pdfThumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber); - }; + if (this.isInPresentationMode || !destArray) { + this._setCurrentPageNumber(pageNumber, true); + return; } - }, - async run(config) { - await this.initialize(config); - const { - appConfig, - eventBus - } = this; - let file; - const queryString = document.location.search.substring(1); - const params = parseQueryString(queryString); - file = params.get("file") ?? AppOptions.get("defaultUrl"); - validateFileURL(file); - const fileInput = this._openFileInput = document.createElement("input"); - fileInput.id = "fileInput"; - fileInput.hidden = true; - fileInput.type = "file"; - fileInput.value = null; - document.body.append(fileInput); - fileInput.addEventListener("change", function (evt) { - const { - files - } = evt.target; - if (!files || files.length === 0) { - return; - } - eventBus.dispatch("fileinputchange", { - source: this, - fileInput: evt.target - }); - }); - appConfig.mainContainer.addEventListener("dragover", function (evt) { - for (const item of evt.dataTransfer.items) { - if (item.type === "application/pdf") { - evt.dataTransfer.dropEffect = evt.dataTransfer.effectAllowed === "copy" ? "copy" : "move"; - stopEvent(evt); - return; + let x = 0, + y = 0; + let width = 0, + height = 0, + widthScale, + heightScale; + const changeOrientation = pageView.rotation % 180 !== 0; + const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; + const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; + let scale = 0; + switch (destArray[1].name) { + case "XYZ": + x = destArray[2]; + y = destArray[3]; + scale = destArray[4]; + x = x !== null ? x : 0; + y = y !== null ? y : pageHeight; + break; + case "Fit": + case "FitB": + scale = "page-fit"; + break; + case "FitH": + case "FitBH": + y = destArray[2]; + scale = "page-width"; + if (y === null && this._location) { + x = this._location.left; + y = this._location.top; + } else if (typeof y !== "number" || y < 0) { + y = pageHeight; } - } - }); - appConfig.mainContainer.addEventListener("drop", function (evt) { - if (evt.dataTransfer.files?.[0].type !== "application/pdf") { + break; + case "FitV": + case "FitBV": + x = destArray[2]; + width = pageWidth; + height = pageHeight; + scale = "page-height"; + break; + case "FitR": + x = destArray[2]; + y = destArray[3]; + width = destArray[4] - x; + height = destArray[5] - y; + let hPadding = SCROLLBAR_PADDING, + vPadding = VERTICAL_PADDING; + if (this.removePageBorders) { + hPadding = vPadding = 0; + } + widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS; + heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS; + scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); + break; + default: + console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); return; - } - stopEvent(evt); - eventBus.dispatch("fileinputchange", { - source: this, - fileInput: evt.dataTransfer - }); - }); - if (!AppOptions.get("supportsDocumentFonts")) { - AppOptions.set("disableFontFace", true); - this.l10n.get("pdfjs-web-fonts-disabled").then(msg => { - console.warn(msg); - }); - } - if (!this.supportsPrinting) { - appConfig.toolbar?.print?.classList.add("hidden"); - appConfig.secondaryToolbar?.printButton.classList.add("hidden"); - } - if (!this.supportsFullscreen) { - appConfig.secondaryToolbar?.presentationModeButton.classList.add("hidden"); - } - if (this.supportsIntegratedFind) { - appConfig.findBar?.toggleButton?.classList.add("hidden"); - } - if (file) { - this.open({ - url: file - }); - } else { - this._hideViewBookmark(); - } - }, - get externalServices() { - return shadow(this, "externalServices", new ExternalServices()); - }, - get initialized() { - return this._initializedCapability.settled; - }, - get initializedPromise() { - return this._initializedCapability.promise; - }, - updateZoom(steps, scaleFactor, origin) { - if (this.pdfViewer.isInPresentationMode) { - return; - } - this.pdfViewer.updateScale({ - drawingDelay: AppOptions.get("defaultZoomDelay"), - steps, - scaleFactor, - origin - }); - }, - zoomIn() { - this.updateZoom(1); - }, - zoomOut() { - this.updateZoom(-1); - }, - zoomReset() { - if (this.pdfViewer.isInPresentationMode) { - return; - } - this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE; - }, - touchPinchCallback(origin, prevDistance, distance) { - if (this.supportsPinchToZoom) { - const newScaleFactor = this._accumulateFactor(this.pdfViewer.currentScale, distance / prevDistance, "_touchUnusedFactor"); - this.updateZoom(null, newScaleFactor, origin); - } else { - const PIXELS_PER_LINE_SCALE = 30; - const ticks = this._accumulateTicks((distance - prevDistance) / PIXELS_PER_LINE_SCALE, "_touchUnusedTicks"); - this.updateZoom(ticks, null, origin); - } - }, - touchPinchEndCallback() { - this._touchUnusedTicks = 0; - this._touchUnusedFactor = 1; - }, - get pagesCount() { - return this.pdfDocument ? this.pdfDocument.numPages : 0; - }, - get page() { - return this.pdfViewer.currentPageNumber; - }, - set page(val) { - this.pdfViewer.currentPageNumber = val; - }, - get supportsPrinting() { - return PDFPrintServiceFactory.supportsPrinting; - }, - get supportsFullscreen() { - return shadow(this, "supportsFullscreen", document.fullscreenEnabled); - }, - get supportsPinchToZoom() { - return shadow(this, "supportsPinchToZoom", AppOptions.get("supportsPinchToZoom")); - }, - get supportsIntegratedFind() { - return shadow(this, "supportsIntegratedFind", AppOptions.get("supportsIntegratedFind")); - }, - get loadingBar() { - const barElement = document.getElementById("loadingBar"); - const bar = barElement ? new ProgressBar(barElement) : null; - return shadow(this, "loadingBar", bar); - }, - get supportsMouseWheelZoomCtrlKey() { - return shadow(this, "supportsMouseWheelZoomCtrlKey", AppOptions.get("supportsMouseWheelZoomCtrlKey")); - }, - get supportsMouseWheelZoomMetaKey() { - return shadow(this, "supportsMouseWheelZoomMetaKey", AppOptions.get("supportsMouseWheelZoomMetaKey")); - }, - get supportsCaretBrowsingMode() { - return AppOptions.get("supportsCaretBrowsingMode"); - }, - moveCaret(isUp, select) { - this._caretBrowsing ||= new CaretBrowsingMode(this._globalAbortController.signal, this.appConfig.mainContainer, this.appConfig.viewerContainer, this.appConfig.toolbar?.container); - this._caretBrowsing.moveCaret(isUp, select); - }, - setTitleUsingUrl(url = "", downloadUrl = null) { - this.url = url; - this.baseUrl = url.split("#", 1)[0]; - if (downloadUrl) { - this._downloadUrl = downloadUrl === url ? this.baseUrl : downloadUrl.split("#", 1)[0]; - } - if (isDataScheme(url)) { - this._hideViewBookmark(); - } - let title = pdfjs_getPdfFilenameFromUrl(url, ""); - if (!title) { - try { - title = decodeURIComponent(getFilenameFromUrl(url)); - } catch {} - } - this.setTitle(title || url); - }, - setTitle(title = this._title) { - this._title = title; - if (this.isViewerEmbedded) { - return; } - const editorIndicator = this._hasAnnotationEditors && !this.pdfRenderingQueue.printing; - document.title = `${editorIndicator ? "* " : ""}${title}`; - }, - get _docFilename() { - return this._contentDispositionFilename || pdfjs_getPdfFilenameFromUrl(this.url); - }, - _hideViewBookmark() { - const { - secondaryToolbar - } = this.appConfig; - secondaryToolbar?.viewBookmarkButton.classList.add("hidden"); - if (secondaryToolbar?.presentationModeButton.classList.contains("hidden")) { - document.getElementById("viewBookmarkSeparator")?.classList.add("hidden"); + if (!ignoreDestinationZoom) { + if (scale && scale !== this._currentScale) { + this.currentScaleValue = scale; + } else if (this._currentScale === UNKNOWN_SCALE) { + this.currentScaleValue = DEFAULT_SCALE_VALUE; + } } - }, - async close() { - this._unblockDocumentLoadEvent(); - this._hideViewBookmark(); - if (!this.pdfLoadingTask) { + if (scale === "page-fit" && !destArray[4]) { + this.#scrollIntoView(pageView); return; } - if (this.pdfDocument?.annotationStorage.size > 0 && this._annotationStorageModified) { - try { - await this.save(); - } catch {} + const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; + let left = Math.min(boundingRect[0][0], boundingRect[1][0]); + let top = Math.min(boundingRect[0][1], boundingRect[1][1]); + if (!allowNegativeOffset) { + left = Math.max(left, 0); + top = Math.max(top, 0); } - const promises = []; - promises.push(this.pdfLoadingTask.destroy()); - this.pdfLoadingTask = null; - if (this.pdfDocument) { - this.pdfDocument = null; - this.pdfThumbnailViewer?.setDocument(null); - this.pdfViewer.setDocument(null); - this.pdfLinkService.setDocument(null); - this.pdfDocumentProperties?.setDocument(null); - } - this.pdfLinkService.externalLinkEnabled = true; - this.store = null; - this.isInitialViewSet = false; - this.url = ""; - this.baseUrl = ""; - this._downloadUrl = ""; - this.documentInfo = null; - this.metadata = null; - this._contentDispositionFilename = null; - this._contentLength = null; - this._saveInProgress = false; - this._hasAnnotationEditors = false; - promises.push(this.pdfScriptingManager.destroyPromise, this.passwordPrompt.close()); - this.setTitle(); - this.pdfSidebar?.reset(); - this.pdfOutlineViewer?.reset(); - this.pdfAttachmentViewer?.reset(); - this.pdfLayerViewer?.reset(); - this.pdfHistory?.reset(); - this.findBar?.reset(); - this.toolbar?.reset(); - this.secondaryToolbar?.reset(); - this._PDFBug?.cleanup(); - await Promise.all(promises); - }, - async open(args) { - if (this.pdfLoadingTask) { - await this.close(); - } - const workerParams = AppOptions.getAll(OptionKind.WORKER); - Object.assign(GlobalWorkerOptions, workerParams); - if (args.url) { - this.setTitleUsingUrl(args.originalUrl || args.url, args.url); - } - const apiParams = AppOptions.getAll(OptionKind.API); - const loadingTask = getDocument({ - ...apiParams, - ...args + this.#scrollIntoView(pageView, { + left, + top }); - this.pdfLoadingTask = loadingTask; - loadingTask.onPassword = (updateCallback, reason) => { - if (this.isViewerEmbedded) { - this._unblockDocumentLoadEvent(); - } - this.pdfLinkService.externalLinkEnabled = false; - this.passwordPrompt.setUpdateCallback(updateCallback, reason); - this.passwordPrompt.open(); - }; - loadingTask.onProgress = ({ - loaded, - total - }) => { - this.progress(loaded / total); + } + _updateLocation(firstPage) { + const currentScale = this._currentScale; + const currentScaleValue = this._currentScaleValue; + const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; + const pageNumber = firstPage.id; + const currentPageView = this._pages[pageNumber - 1]; + const container = this.container; + const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); + const intLeft = Math.round(topLeft[0]); + const intTop = Math.round(topLeft[1]); + let pdfOpenParams = `#page=${pageNumber}`; + if (!this.isInPresentationMode) { + pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`; + } + this._location = { + pageNumber, + scale: normalizedScaleValue, + top: intTop, + left: intLeft, + rotation: this._pagesRotation, + pdfOpenParams }; - return loadingTask.promise.then(pdfDocument => { - this.load(pdfDocument); - }, reason => { - if (loadingTask !== this.pdfLoadingTask) { - return undefined; - } - let key = "pdfjs-loading-error"; - if (reason instanceof InvalidPDFException) { - key = "pdfjs-invalid-file-error"; - } else if (reason instanceof MissingPDFException) { - key = "pdfjs-missing-file-error"; - } else if (reason instanceof UnexpectedResponseException) { - key = "pdfjs-unexpected-response-error"; - } - return this._documentError(key, { - message: reason.message - }).then(() => { - throw reason; - }); - }); - }, - async download() { - let data; - try { - data = await this.pdfDocument.getData(); - } catch {} - this.downloadManager.download(data, this._downloadUrl, this._docFilename); - }, - async save() { - if (this._saveInProgress) { + } + update() { + const visible = this._getVisiblePages(); + const visiblePages = visible.views, + numVisiblePages = visiblePages.length; + if (numVisiblePages === 0) { return; } - this._saveInProgress = true; - await this.pdfScriptingManager.dispatchWillSave(); - try { - const data = await this.pdfDocument.saveDocument(); - this.downloadManager.download(data, this._downloadUrl, this._docFilename); - } catch (reason) { - console.error(`Error when saving the document:`, reason); - await this.download(); - } finally { - await this.pdfScriptingManager.dispatchDidSave(); - this._saveInProgress = false; - } - if (this._hasAnnotationEditors) { - this.externalServices.reportTelemetry({ - type: "editing", - data: { - type: "save", - stats: this.pdfDocument?.annotationStorage.editorStats - } - }); + const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); + this.#buffer.resize(newCacheSize, visible.ids); + this.renderingQueue.renderHighestPriority(visible); + const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL); + const currentId = this._currentPageNumber; + let stillFullyVisible = false; + for (const page of visiblePages) { + if (page.percent < 100) { + break; + } + if (page.id === currentId && isSimpleLayout) { + stillFullyVisible = true; + break; + } } - }, - async downloadOrSave() { - const { - classList - } = this.appConfig.appContainer; - classList.add("wait"); - await (this.pdfDocument?.annotationStorage.size > 0 ? this.save() : this.download()); - classList.remove("wait"); - }, - async _documentError(key, moreInfo = null) { - this._unblockDocumentLoadEvent(); - const message = await this._otherError(key || "pdfjs-loading-error", moreInfo); - this.eventBus.dispatch("documenterror", { + this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id); + this._updateLocation(visible.first); + this.eventBus.dispatch("updateviewarea", { source: this, - message, - reason: moreInfo?.message ?? null + location: this._location }); - }, - async _otherError(key, moreInfo = null) { - const message = await this.l10n.get(key); - const moreInfoText = [`PDF.js v${version || "?"} (build: ${build || "?"})`]; - if (moreInfo) { - moreInfoText.push(`Message: ${moreInfo.message}`); - if (moreInfo.stack) { - moreInfoText.push(`Stack: ${moreInfo.stack}`); - } else { - if (moreInfo.filename) { - moreInfoText.push(`File: ${moreInfo.filename}`); - } - if (moreInfo.lineNumber) { - moreInfoText.push(`Line: ${moreInfo.lineNumber}`); - } + } + #switchToEditAnnotationMode() { + const visible = this._getVisiblePages(); + const pagesToRefresh = []; + const { + ids, + views + } = visible; + for (const page of views) { + const { + view + } = page; + if (!view.hasEditableAnnotations()) { + ids.delete(view.id); + continue; } + pagesToRefresh.push(page); } - console.error(`${message}\n\n${moreInfoText.join("\n")}`); - return message; - }, - progress(level) { - const percent = Math.round(level * 100); - if (!this.loadingBar || percent <= this.loadingBar.percent) { - return; - } - this.loadingBar.percent = percent; - if (this.pdfDocument?.loadingParams.disableAutoFetch ?? AppOptions.get("disableAutoFetch")) { - this.loadingBar.setDisableAutoFetch(); + if (pagesToRefresh.length === 0) { + return null; } - }, - load(pdfDocument) { - this.pdfDocument = pdfDocument; - pdfDocument.getDownloadInfo().then(({ - length - }) => { - this._contentLength = length; - this.loadingBar?.hide(); - firstPagePromise.then(() => { - this.eventBus.dispatch("documentloaded", { - source: this - }); - }); - }); - const pageLayoutPromise = pdfDocument.getPageLayout().catch(() => {}); - const pageModePromise = pdfDocument.getPageMode().catch(() => {}); - const openActionPromise = pdfDocument.getOpenAction().catch(() => {}); - this.toolbar?.setPagesCount(pdfDocument.numPages, false); - this.secondaryToolbar?.setPagesCount(pdfDocument.numPages); - this.pdfLinkService.setDocument(pdfDocument); - this.pdfDocumentProperties?.setDocument(pdfDocument); - const pdfViewer = this.pdfViewer; - pdfViewer.setDocument(pdfDocument); - const { - firstPagePromise, - onePageRendered, - pagesPromise - } = pdfViewer; - this.pdfThumbnailViewer?.setDocument(pdfDocument); - const storedPromise = (this.store = new ViewHistory(pdfDocument.fingerprints[0])).getMultiple({ - page: null, - zoom: DEFAULT_SCALE_VALUE, - scrollLeft: "0", - scrollTop: "0", - rotation: null, - sidebarView: SidebarView.UNKNOWN, - scrollMode: ScrollMode.UNKNOWN, - spreadMode: SpreadMode.UNKNOWN - }).catch(() => {}); - firstPagePromise.then(pdfPage => { - this.loadingBar?.setWidth(this.appConfig.viewerContainer); - this._initializeAnnotationStorageCallbacks(pdfDocument); - Promise.all([animationStarted, storedPromise, pageLayoutPromise, pageModePromise, openActionPromise]).then(async ([timeStamp, stored, pageLayout, pageMode, openAction]) => { - const viewOnLoad = AppOptions.get("viewOnLoad"); - this._initializePdfHistory({ - fingerprint: pdfDocument.fingerprints[0], - viewOnLoad, - initialDest: openAction?.dest - }); - const initialBookmark = this.initialBookmark; - const zoom = AppOptions.get("defaultZoomValue"); - let hash = zoom ? `zoom=${zoom}` : null; - let rotation = null; - let sidebarView = AppOptions.get("sidebarViewOnLoad"); - let scrollMode = AppOptions.get("scrollModeOnLoad"); - let spreadMode = AppOptions.get("spreadModeOnLoad"); - if (stored?.page && viewOnLoad !== ViewOnLoad.INITIAL) { - hash = `page=${stored.page}&zoom=${zoom || stored.zoom},` + `${stored.scrollLeft},${stored.scrollTop}`; - rotation = parseInt(stored.rotation, 10); - if (sidebarView === SidebarView.UNKNOWN) { - sidebarView = stored.sidebarView | 0; - } - if (scrollMode === ScrollMode.UNKNOWN) { - scrollMode = stored.scrollMode | 0; - } - if (spreadMode === SpreadMode.UNKNOWN) { - spreadMode = stored.spreadMode | 0; - } - } - if (pageMode && sidebarView === SidebarView.UNKNOWN) { - sidebarView = apiPageModeToSidebarView(pageMode); - } - if (pageLayout && scrollMode === ScrollMode.UNKNOWN && spreadMode === SpreadMode.UNKNOWN) { - const modes = apiPageLayoutToViewerModes(pageLayout); - spreadMode = modes.spreadMode; - } - this.setInitialView(hash, { - rotation, - sidebarView, - scrollMode, - spreadMode - }); - this.eventBus.dispatch("documentinit", { - source: this - }); - if (!this.isViewerEmbedded) { - pdfViewer.focus(); - } - await Promise.race([pagesPromise, new Promise(resolve => { - setTimeout(resolve, FORCE_PAGES_LOADED_TIMEOUT); - })]); - if (!initialBookmark && !hash) { - return; - } - if (pdfViewer.hasEqualPageSizes) { - return; - } - this.initialBookmark = initialBookmark; - pdfViewer.currentScaleValue = pdfViewer.currentScaleValue; - this.setInitialView(hash); - }).catch(() => { - this.setInitialView(); - }).then(function () { - pdfViewer.update(); - }); - }); - pagesPromise.then(() => { - this._unblockDocumentLoadEvent(); - this._initializeAutoPrint(pdfDocument, openActionPromise); - }, reason => { - this._documentError("pdfjs-loading-error", { - message: reason.message - }); + this.renderingQueue.renderHighestPriority({ + first: pagesToRefresh[0], + last: pagesToRefresh.at(-1), + views: pagesToRefresh, + ids }); - onePageRendered.then(data => { - this.externalServices.reportTelemetry({ - type: "pageInfo", - timestamp: data.timestamp - }); - if (this.pdfOutlineViewer) { - pdfDocument.getOutline().then(outline => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this.pdfOutlineViewer.render({ - outline, - pdfDocument - }); - }); - } - if (this.pdfAttachmentViewer) { - pdfDocument.getAttachments().then(attachments => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this.pdfAttachmentViewer.render({ - attachments - }); - }); - } - if (this.pdfLayerViewer) { - pdfViewer.optionalContentConfigPromise.then(optionalContentConfig => { - if (pdfDocument !== this.pdfDocument) { - return; - } - this.pdfLayerViewer.render({ - optionalContentConfig, - pdfDocument - }); - }); - } + return ids; + } + containsElement(element) { + return this.container.contains(element); + } + focus() { + this.container.focus(); + } + get _isContainerRtl() { + return getComputedStyle(this.container).direction === "rtl"; + } + get isInPresentationMode() { + return this.presentationModeState === PresentationModeState.FULLSCREEN; + } + get isChangingPresentationMode() { + return this.presentationModeState === PresentationModeState.CHANGING; + } + get isHorizontalScrollbarEnabled() { + return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; + } + get isVerticalScrollbarEnabled() { + return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; + } + _getVisiblePages() { + const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages, + horizontal = this._scrollMode === ScrollMode.HORIZONTAL, + rtl = horizontal && this._isContainerRtl; + return getVisibleElements({ + scrollEl: this.container, + views, + sortByVisibility: true, + horizontal, + rtl }); - this._initializePageLabels(pdfDocument); - this._initializeMetadata(pdfDocument); - }, - async _scriptingDocProperties(pdfDocument) { - if (!this.documentInfo) { - await new Promise(resolve => { - this.eventBus._on("metadataloaded", resolve, { - once: true - }); - }); - if (pdfDocument !== this.pdfDocument) { - return null; + } + cleanup() { + for (const pageView of this._pages) { + if (pageView.renderingState !== RenderingStates.FINISHED) { + pageView.reset(); } } - if (!this._contentLength) { - await new Promise(resolve => { - this.eventBus._on("documentloaded", resolve, { - once: true - }); - }); - if (pdfDocument !== this.pdfDocument) { - return null; - } + } + _cancelRendering() { + for (const pageView of this._pages) { + pageView.cancelRendering(); } - return { - ...this.documentInfo, - baseURL: this.baseUrl, - filesize: this._contentLength, - filename: this._docFilename, - metadata: this.metadata?.getRaw(), - authors: this.metadata?.get("dc:creator"), - numPages: this.pagesCount, - URL: this.url - }; - }, - async _initializeAutoPrint(pdfDocument, openActionPromise) { - const [openAction, jsActions] = await Promise.all([openActionPromise, this.pdfViewer.enableScripting ? null : pdfDocument.getJSActions()]); - if (pdfDocument !== this.pdfDocument) { - return; + } + async #ensurePdfPageLoaded(pageView) { + if (pageView.pdfPage) { + return pageView.pdfPage; } - let triggerAutoPrint = openAction?.action === "Print"; - if (jsActions) { - console.warn("Warning: JavaScript support is not enabled"); - for (const name in jsActions) { - if (triggerAutoPrint) { - break; - } - switch (name) { - case "WillClose": - case "WillSave": - case "DidSave": - case "WillPrint": - case "DidPrint": - continue; - } - triggerAutoPrint = jsActions[name].some(js => AutoPrintRegExp.test(js)); + try { + const pdfPage = await this.pdfDocument.getPage(pageView.id); + if (!pageView.pdfPage) { + pageView.setPdfPage(pdfPage); } + return pdfPage; + } catch (reason) { + console.error("Unable to get page for page view", reason); + return null; } - if (triggerAutoPrint) { - this.triggerPrinting(); - } - }, - async _initializeMetadata(pdfDocument) { - const { - info, - metadata, - contentDispositionFilename, - contentLength - } = await pdfDocument.getMetadata(); - if (pdfDocument !== this.pdfDocument) { - return; + } + #getScrollAhead(visible) { + if (visible.first?.id === 1) { + return true; + } else if (visible.last?.id === this.pagesCount) { + return false; } - this.documentInfo = info; - this.metadata = metadata; - this._contentDispositionFilename ??= contentDispositionFilename; - this._contentLength ??= contentLength; - console.log(`PDF ${pdfDocument.fingerprints[0]} [${info.PDFFormatVersion} ` + `${(info.Producer || "-").trim()} / ${(info.Creator || "-").trim()}] ` + `(PDF.js: ${version || "?"} [${build || "?"}])`); - let pdfTitle = info.Title; - const metadataTitle = metadata?.get("dc:title"); - if (metadataTitle) { - if (metadataTitle !== "Untitled" && !/[\uFFF0-\uFFFF]/g.test(metadataTitle)) { - pdfTitle = metadataTitle; - } + switch (this._scrollMode) { + case ScrollMode.PAGE: + return this.#scrollModePageState.scrollDown; + case ScrollMode.HORIZONTAL: + return this.scroll.right; } - if (pdfTitle) { - this.setTitle(`${pdfTitle} - ${this._contentDispositionFilename || this._title}`); - } else if (this._contentDispositionFilename) { - this.setTitle(this._contentDispositionFilename); + return this.scroll.down; + } + forceRendering(currentlyVisiblePages) { + const visiblePages = currentlyVisiblePages || this._getVisiblePages(); + const scrollAhead = this.#getScrollAhead(visiblePages); + const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL; + const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); + if (pageView) { + this.#ensurePdfPageLoaded(pageView).then(() => { + this.renderingQueue.renderView(pageView); + }); + return true; } - if (info.IsXFAPresent && !info.IsAcroFormPresent && !pdfDocument.isPureXfa) { - if (pdfDocument.loadingParams.enableXfa) { - console.warn("Warning: XFA Foreground documents are not supported"); - } else { - console.warn("Warning: XFA support is not enabled"); + return false; + } + get hasEqualPageSizes() { + const firstPageView = this._pages[0]; + for (let i = 1, ii = this._pages.length; i < ii; ++i) { + const pageView = this._pages[i]; + if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { + return false; } - } else if ((info.IsAcroFormPresent || info.IsXFAPresent) && !this.pdfViewer.renderForms) { - console.warn("Warning: Interactive form support is not enabled"); - } - if (info.IsSignaturesPresent) { - console.warn("Warning: Digital signatures validation is not supported"); - } - this.eventBus.dispatch("metadataloaded", { - source: this - }); - }, - async _initializePageLabels(pdfDocument) { - const labels = await pdfDocument.getPageLabels(); - if (pdfDocument !== this.pdfDocument) { - return; } - if (!labels || AppOptions.get("disablePageLabels")) { - return; - } - const numLabels = labels.length; - let standardLabels = 0, - emptyLabels = 0; - for (let i = 0; i < numLabels; i++) { - const label = labels[i]; - if (label === (i + 1).toString()) { - standardLabels++; - } else if (label === "") { - emptyLabels++; - } else { - break; + return true; + } + getPagesOverview() { + let initialOrientation; + return this._pages.map(pageView => { + const viewport = pageView.pdfPage.getViewport({ + scale: 1 + }); + const orientation = isPortraitOrientation(viewport); + if (initialOrientation === undefined) { + initialOrientation = orientation; + } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) { + return { + width: viewport.height, + height: viewport.width, + rotation: (viewport.rotation - 90) % 360 + }; } - } - if (standardLabels >= numLabels || emptyLabels >= numLabels) { - return; - } - const { - pdfViewer, - pdfThumbnailViewer, - toolbar - } = this; - pdfViewer.setPageLabels(labels); - pdfThumbnailViewer?.setPageLabels(labels); - toolbar?.setPagesCount(numLabels, true); - toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel); - }, - _initializePdfHistory({ - fingerprint, - viewOnLoad, - initialDest = null - }) { - if (!this.pdfHistory) { - return; - } - this.pdfHistory.initialize({ - fingerprint, - resetHistory: viewOnLoad === ViewOnLoad.INITIAL, - updateUrl: AppOptions.get("historyUpdateUrl") + return { + width: viewport.width, + height: viewport.height, + rotation: viewport.rotation + }; }); - if (this.pdfHistory.initialBookmark) { - this.initialBookmark = this.pdfHistory.initialBookmark; - this.initialRotation = this.pdfHistory.initialRotation; + } + get optionalContentConfigPromise() { + if (!this.pdfDocument) { + return Promise.resolve(null); } - if (initialDest && !this.initialBookmark && viewOnLoad === ViewOnLoad.UNKNOWN) { - this.initialBookmark = JSON.stringify(initialDest); - this.pdfHistory.push({ - explicitDest: initialDest, - pageNumber: null + if (!this._optionalContentConfigPromise) { + console.error("optionalContentConfigPromise: Not initialized yet."); + return this.pdfDocument.getOptionalContentConfig({ + intent: "display" }); } - }, - _initializeAnnotationStorageCallbacks(pdfDocument) { - if (pdfDocument !== this.pdfDocument) { - return; - } - const { - annotationStorage - } = pdfDocument; - annotationStorage.onSetModified = () => { - window.addEventListener("beforeunload", beforeUnload); - this._annotationStorageModified = true; - }; - annotationStorage.onResetModified = () => { - window.removeEventListener("beforeunload", beforeUnload); - delete this._annotationStorageModified; - }; - annotationStorage.onAnnotationEditor = typeStr => { - this._hasAnnotationEditors = !!typeStr; - this.setTitle(); - }; - }, - setInitialView(storedHash, { - rotation, - sidebarView, - scrollMode, - spreadMode - } = {}) { - const setRotation = angle => { - if (isValidRotation(angle)) { - this.pdfViewer.pagesRotation = angle; - } - }; - const setViewerModes = (scroll, spread) => { - if (isValidScrollMode(scroll)) { - this.pdfViewer.scrollMode = scroll; - } - if (isValidSpreadMode(spread)) { - this.pdfViewer.spreadMode = spread; - } - }; - this.isInitialViewSet = true; - this.pdfSidebar?.setInitialView(sidebarView); - setViewerModes(scrollMode, spreadMode); - if (this.initialBookmark) { - setRotation(this.initialRotation); - delete this.initialRotation; - this.pdfLinkService.setHash(this.initialBookmark); - this.initialBookmark = null; - } else if (storedHash) { - setRotation(rotation); - this.pdfLinkService.setHash(storedHash); - } - this.toolbar?.setPageNumber(this.pdfViewer.currentPageNumber, this.pdfViewer.currentPageLabel); - this.secondaryToolbar?.setPageNumber(this.pdfViewer.currentPageNumber); - if (!this.pdfViewer.currentScaleValue) { - this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE; + return this._optionalContentConfigPromise; + } + set optionalContentConfigPromise(promise) { + if (!(promise instanceof Promise)) { + throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); } - }, - _cleanup() { if (!this.pdfDocument) { return; } - this.pdfViewer.cleanup(); - this.pdfThumbnailViewer?.cleanup(); - this.pdfDocument.cleanup(AppOptions.get("fontExtraProperties")); - }, - forceRendering() { - this.pdfRenderingQueue.printing = !!this.printService; - this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar?.visibleView === SidebarView.THUMBS; - this.pdfRenderingQueue.renderHighestPriority(); - }, - beforePrint() { - this._printAnnotationStoragePromise = this.pdfScriptingManager.dispatchWillPrint().catch(() => {}).then(() => this.pdfDocument?.annotationStorage.print); - if (this.printService) { - return; - } - if (!this.supportsPrinting) { - this._otherError("pdfjs-printing-not-supported"); - return; - } - if (!this.pdfViewer.pageViewsReady) { - this.l10n.get("pdfjs-printing-not-ready").then(msg => { - window.alert(msg); - }); + if (!this._optionalContentConfigPromise) { return; } - this.printService = PDFPrintServiceFactory.createPrintService({ - pdfDocument: this.pdfDocument, - pagesOverview: this.pdfViewer.getPagesOverview(), - printContainer: this.appConfig.printContainer, - printResolution: AppOptions.get("printResolution"), - printAnnotationStoragePromise: this._printAnnotationStoragePromise + this._optionalContentConfigPromise = promise; + this.refresh(false, { + optionalContentConfigPromise: promise }); - this.forceRendering(); - this.setTitle(); - this.printService.layout(); - if (this._hasAnnotationEditors) { - this.externalServices.reportTelemetry({ - type: "editing", - data: { - type: "print", - stats: this.pdfDocument?.annotationStorage.editorStats - } - }); - } - }, - afterPrint() { - if (this._printAnnotationStoragePromise) { - this._printAnnotationStoragePromise.then(() => { - this.pdfScriptingManager.dispatchDidPrint(); - }); - this._printAnnotationStoragePromise = null; - } - if (this.printService) { - this.printService.destroy(); - this.printService = null; - this.pdfDocument?.annotationStorage.resetModified(); - } - this.forceRendering(); - this.setTitle(); - }, - rotatePages(delta) { - this.pdfViewer.pagesRotation += delta; - }, - requestPresentationMode() { - this.pdfPresentationMode?.request(); - }, - triggerPrinting() { - if (this.supportsPrinting) { - window.print(); - } - }, - bindEvents() { - if (this._eventBusAbortController) { - return; - } - const ac = this._eventBusAbortController = new AbortController(); - const opts = { - signal: ac.signal - }; - const { - eventBus, - externalServices, - pdfDocumentProperties, - pdfViewer, - preferences - } = this; - eventBus._on("resize", onResize.bind(this), opts); - eventBus._on("hashchange", onHashchange.bind(this), opts); - eventBus._on("beforeprint", this.beforePrint.bind(this), opts); - eventBus._on("afterprint", this.afterPrint.bind(this), opts); - eventBus._on("pagerender", onPageRender.bind(this), opts); - eventBus._on("pagerendered", onPageRendered.bind(this), opts); - eventBus._on("updateviewarea", onUpdateViewarea.bind(this), opts); - eventBus._on("pagechanging", onPageChanging.bind(this), opts); - eventBus._on("scalechanging", onScaleChanging.bind(this), opts); - eventBus._on("rotationchanging", onRotationChanging.bind(this), opts); - eventBus._on("sidebarviewchanged", onSidebarViewChanged.bind(this), opts); - eventBus._on("pagemode", onPageMode.bind(this), opts); - eventBus._on("namedaction", onNamedAction.bind(this), opts); - eventBus._on("presentationmodechanged", evt => pdfViewer.presentationModeState = evt.state, opts); - eventBus._on("presentationmode", this.requestPresentationMode.bind(this), opts); - eventBus._on("switchannotationeditormode", evt => pdfViewer.annotationEditorMode = evt, opts); - eventBus._on("print", this.triggerPrinting.bind(this), opts); - eventBus._on("download", this.downloadOrSave.bind(this), opts); - eventBus._on("firstpage", () => this.page = 1, opts); - eventBus._on("lastpage", () => this.page = this.pagesCount, opts); - eventBus._on("nextpage", () => pdfViewer.nextPage(), opts); - eventBus._on("previouspage", () => pdfViewer.previousPage(), opts); - eventBus._on("zoomin", this.zoomIn.bind(this), opts); - eventBus._on("zoomout", this.zoomOut.bind(this), opts); - eventBus._on("zoomreset", this.zoomReset.bind(this), opts); - eventBus._on("pagenumberchanged", onPageNumberChanged.bind(this), opts); - eventBus._on("scalechanged", evt => pdfViewer.currentScaleValue = evt.value, opts); - eventBus._on("rotatecw", this.rotatePages.bind(this, 90), opts); - eventBus._on("rotateccw", this.rotatePages.bind(this, -90), opts); - eventBus._on("optionalcontentconfig", evt => pdfViewer.optionalContentConfigPromise = evt.promise, opts); - eventBus._on("switchscrollmode", evt => pdfViewer.scrollMode = evt.mode, opts); - eventBus._on("scrollmodechanged", onViewerModesChanged.bind(this, "scrollMode"), opts); - eventBus._on("switchspreadmode", evt => pdfViewer.spreadMode = evt.mode, opts); - eventBus._on("spreadmodechanged", onViewerModesChanged.bind(this, "spreadMode"), opts); - eventBus._on("imagealttextsettings", onImageAltTextSettings.bind(this), opts); - eventBus._on("documentproperties", () => pdfDocumentProperties?.open(), opts); - eventBus._on("findfromurlhash", onFindFromUrlHash.bind(this), opts); - eventBus._on("updatefindmatchescount", onUpdateFindMatchesCount.bind(this), opts); - eventBus._on("updatefindcontrolstate", onUpdateFindControlState.bind(this), opts); - eventBus._on("fileinputchange", onFileInputChange.bind(this), opts); - eventBus._on("openfile", onOpenFile.bind(this), opts); - }, - bindWindowEvents() { - if (this._windowAbortController) { + this.eventBus.dispatch("optionalcontentconfigchanged", { + source: this, + promise + }); + } + get scrollMode() { + return this._scrollMode; + } + set scrollMode(mode) { + if (this._scrollMode === mode) { return; } - this._windowAbortController = new AbortController(); - const { - eventBus, - appConfig: { - mainContainer - }, - pdfViewer, - _windowAbortController: { - signal - } - } = this; - if (typeof AbortSignal.any === "function") { - this._touchManager = new TouchManager({ - container: window, - isPinchingDisabled: () => pdfViewer.isInPresentationMode, - isPinchingStopped: () => this.overlayManager?.active, - onPinching: this.touchPinchCallback.bind(this), - onPinchEnd: this.touchPinchEndCallback.bind(this), - signal - }); + if (!isValidScrollMode(mode)) { + throw new Error(`Invalid scroll mode: ${mode}`); } - function addWindowResolutionChange(evt = null) { - if (evt) { - pdfViewer.refresh(); - } - const mediaQueryList = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`); - mediaQueryList.addEventListener("change", addWindowResolutionChange, { - once: true, - signal - }); + if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { + return; } - addWindowResolutionChange(); - window.addEventListener("wheel", onWheel.bind(this), { - passive: false, - signal - }); - window.addEventListener("click", onClick.bind(this), { - signal - }); - window.addEventListener("keydown", onKeyDown.bind(this), { - signal - }); - window.addEventListener("keyup", onKeyUp.bind(this), { - signal - }); - window.addEventListener("resize", () => eventBus.dispatch("resize", { - source: window - }), { - signal - }); - window.addEventListener("hashchange", () => { - eventBus.dispatch("hashchange", { - source: window, - hash: document.location.hash.substring(1) - }); - }, { - signal - }); - window.addEventListener("beforeprint", () => eventBus.dispatch("beforeprint", { - source: window - }), { - signal - }); - window.addEventListener("afterprint", () => eventBus.dispatch("afterprint", { - source: window - }), { - signal - }); - window.addEventListener("updatefromsandbox", evt => { - eventBus.dispatch("updatefromsandbox", { - source: window, - detail: evt.detail - }); - }, { - signal - }); - if (!("onscrollend" in document.documentElement)) { - return; - } - ({ - scrollTop: this._lastScrollTop, - scrollLeft: this._lastScrollLeft - } = mainContainer); - const scrollend = () => { - ({ - scrollTop: this._lastScrollTop, - scrollLeft: this._lastScrollLeft - } = mainContainer); - this._isScrolling = false; - mainContainer.addEventListener("scroll", scroll, { - passive: true, - signal - }); - mainContainer.removeEventListener("scrollend", scrollend); - mainContainer.removeEventListener("blur", scrollend); - }; - const scroll = () => { - if (this._isCtrlKeyDown) { - return; - } - if (this._lastScrollTop === mainContainer.scrollTop && this._lastScrollLeft === mainContainer.scrollLeft) { - return; - } - mainContainer.removeEventListener("scroll", scroll); - this._isScrolling = true; - mainContainer.addEventListener("scrollend", scrollend, { - signal - }); - mainContainer.addEventListener("blur", scrollend, { - signal - }); - }; - mainContainer.addEventListener("scroll", scroll, { - passive: true, - signal + this._previousScrollMode = this._scrollMode; + this._scrollMode = mode; + this.eventBus.dispatch("scrollmodechanged", { + source: this, + mode }); - }, - unbindEvents() { - this._eventBusAbortController?.abort(); - this._eventBusAbortController = null; - }, - unbindWindowEvents() { - this._windowAbortController?.abort(); - this._windowAbortController = null; - this._touchManager = null; - }, - async testingClose() { - this.unbindEvents(); - this.unbindWindowEvents(); - this._globalAbortController?.abort(); - this._globalAbortController = null; - this.findBar?.close(); - await Promise.all([this.l10n?.destroy(), this.close()]); - }, - _accumulateTicks(ticks, prop) { - if (this[prop] > 0 && ticks < 0 || this[prop] < 0 && ticks > 0) { - this[prop] = 0; - } - this[prop] += ticks; - const wholeTicks = Math.trunc(this[prop]); - this[prop] -= wholeTicks; - return wholeTicks; - }, - _accumulateFactor(previousScale, factor, prop) { - if (factor === 1) { - return 1; - } - if (this[prop] > 1 && factor < 1 || this[prop] < 1 && factor > 1) { - this[prop] = 1; - } - const newFactor = Math.floor(previousScale * factor * this[prop] * 100) / (100 * previousScale); - this[prop] = factor / newFactor; - return newFactor; - }, - _unblockDocumentLoadEvent() { - document.blockUnblockOnload?.(false); - this._unblockDocumentLoadEvent = () => {}; - }, - get scriptingReady() { - return this.pdfScriptingManager.ready; + this._updateScrollMode(this._currentPageNumber); } -}; -initCom(PDFViewerApplication); -{ - PDFPrintServiceFactory.initGlobals(PDFViewerApplication); -} -{ - const HOSTED_VIEWER_ORIGINS = ["null", "http://mozilla.github.io", "https://mozilla.github.io"]; - var validateFileURL = function (file) { - if (!file) { + _updateScrollMode(pageNumber = null) { + const scrollMode = this._scrollMode, + viewer = this.viewer; + viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL); + viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED); + if (!this.pdfDocument || !pageNumber) { return; } - try { - const viewerOrigin = new URL(window.location.href).origin || "null"; - if (HOSTED_VIEWER_ORIGINS.includes(viewerOrigin)) { - return; - } - const fileOrigin = new URL(file, window.location.href).origin; - if (fileOrigin !== viewerOrigin) { - throw new Error("file origin does not match viewer's"); - } - } catch (ex) { - PDFViewerApplication._documentError("pdfjs-loading-error", { - message: ex.message - }); - throw ex; + if (scrollMode === ScrollMode.PAGE) { + this.#ensurePageViewVisible(); + } else if (this._previousScrollMode === ScrollMode.PAGE) { + this._updateSpreadMode(); } - }; - var onFileInputChange = function (evt) { - if (this.pdfViewer?.isInPresentationMode) { - return; + if (this._currentScaleValue && isNaN(this._currentScaleValue)) { + this.#setScale(this._currentScaleValue, { + noScroll: true + }); } - const file = evt.fileInput.files[0]; - this.open({ - url: URL.createObjectURL(file), - originalUrl: file.name - }); - }; - var onOpenFile = function (evt) { - this._openFileInput?.click(); - }; -} -function onPageRender({ - pageNumber -}) { - if (pageNumber === this.page) { - this.toolbar?.updateLoadingIndicatorState(true); + this._setCurrentPageNumber(pageNumber, true); + this.update(); } -} -function onPageRendered({ - pageNumber, - error -}) { - if (pageNumber === this.page) { - this.toolbar?.updateLoadingIndicatorState(false); + get spreadMode() { + return this._spreadMode; } - if (this.pdfSidebar?.visibleView === SidebarView.THUMBS) { - const pageView = this.pdfViewer.getPageView(pageNumber - 1); - const thumbnailView = this.pdfThumbnailViewer?.getThumbnail(pageNumber - 1); - if (pageView) { - thumbnailView?.setImage(pageView); + set spreadMode(mode) { + if (this._spreadMode === mode) { + return; } + if (!isValidSpreadMode(mode)) { + throw new Error(`Invalid spread mode: ${mode}`); + } + this._spreadMode = mode; + this.eventBus.dispatch("spreadmodechanged", { + source: this, + mode + }); + this._updateSpreadMode(this._currentPageNumber); } - if (error) { - this._otherError("pdfjs-rendering-error", error); - } -} -function onPageMode({ - mode -}) { - let view; - switch (mode) { - case "thumbs": - view = SidebarView.THUMBS; - break; - case "bookmarks": - case "outline": - view = SidebarView.OUTLINE; - break; - case "attachments": - view = SidebarView.ATTACHMENTS; - break; - case "layers": - view = SidebarView.LAYERS; - break; - case "none": - view = SidebarView.NONE; - break; - default: - console.error('Invalid "pagemode" hash parameter: ' + mode); + _updateSpreadMode(pageNumber = null) { + if (!this.pdfDocument) { return; - } - this.pdfSidebar?.switchView(view, true); -} -function onNamedAction(evt) { - switch (evt.action) { - case "GoToPage": - this.appConfig.toolbar?.pageNumber.select(); - break; - case "Find": - if (!this.supportsIntegratedFind) { - this.findBar?.toggle(); + } + const viewer = this.viewer, + pages = this._pages; + if (this._scrollMode === ScrollMode.PAGE) { + this.#ensurePageViewVisible(); + } else { + viewer.textContent = ""; + if (this._spreadMode === SpreadMode.NONE) { + for (const pageView of this._pages) { + viewer.append(pageView.div); + } + } else { + const parity = this._spreadMode - 1; + let spread = null; + for (let i = 0, ii = pages.length; i < ii; ++i) { + if (spread === null) { + spread = document.createElement("div"); + spread.className = "spread"; + viewer.append(spread); + } else if (i % 2 === parity) { + spread = spread.cloneNode(false); + viewer.append(spread); + } + spread.append(pages[i].div); + } } - break; - case "Print": - this.triggerPrinting(); - break; - case "SaveAs": - this.downloadOrSave(); - break; - } -} -function onSidebarViewChanged({ - view -}) { - this.pdfRenderingQueue.isThumbnailViewEnabled = view === SidebarView.THUMBS; - if (this.isInitialViewSet) { - this.store?.set("sidebarView", view).catch(() => {}); - } -} -function onUpdateViewarea({ - location -}) { - if (this.isInitialViewSet) { - this.store?.setMultiple({ - page: location.pageNumber, - zoom: location.scale, - scrollLeft: location.left, - scrollTop: location.top, - rotation: location.rotation - }).catch(() => {}); - } - if (this.appConfig.secondaryToolbar) { - this.appConfig.secondaryToolbar.viewBookmarkButton.href = this.pdfLinkService.getAnchorUrl(location.pdfOpenParams); - } -} -function onViewerModesChanged(name, evt) { - if (this.isInitialViewSet && !this.pdfViewer.isInPresentationMode) { - this.store?.set(name, evt.mode).catch(() => {}); - } -} -function onResize() { - const { - pdfDocument, - pdfViewer, - pdfRenderingQueue - } = this; - if (pdfRenderingQueue.printing && window.matchMedia("print").matches) { - return; - } - if (!pdfDocument) { - return; - } - const currentScaleValue = pdfViewer.currentScaleValue; - if (currentScaleValue === "auto" || currentScaleValue === "page-fit" || currentScaleValue === "page-width") { - pdfViewer.currentScaleValue = currentScaleValue; - } - pdfViewer.update(); -} -function onHashchange(evt) { - const hash = evt.hash; - if (!hash) { - return; - } - if (!this.isInitialViewSet) { - this.initialBookmark = hash; - } else if (!this.pdfHistory?.popStateInProgress) { - this.pdfLinkService.setHash(hash); + } + if (!pageNumber) { + return; + } + if (this._currentScaleValue && isNaN(this._currentScaleValue)) { + this.#setScale(this._currentScaleValue, { + noScroll: true + }); + } + this._setCurrentPageNumber(pageNumber, true); + this.update(); } -} -function onPageNumberChanged(evt) { - const { - pdfViewer - } = this; - if (evt.value !== "") { - this.pdfLinkService.goToPage(evt.value); + _getPageAdvance(currentPageNumber, previous = false) { + switch (this._scrollMode) { + case ScrollMode.WRAPPED: + { + const { + views + } = this._getVisiblePages(), + pageLayout = new Map(); + for (const { + id, + y, + percent, + widthPercent + } of views) { + if (percent === 0 || widthPercent < 100) { + continue; + } + let yArray = pageLayout.get(y); + if (!yArray) { + pageLayout.set(y, yArray ||= []); + } + yArray.push(id); + } + for (const yArray of pageLayout.values()) { + const currentIndex = yArray.indexOf(currentPageNumber); + if (currentIndex === -1) { + continue; + } + const numPages = yArray.length; + if (numPages === 1) { + break; + } + if (previous) { + for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { + const currentId = yArray[i], + expectedId = yArray[i + 1] - 1; + if (currentId < expectedId) { + return currentPageNumber - expectedId; + } + } + } else { + for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { + const currentId = yArray[i], + expectedId = yArray[i - 1] + 1; + if (currentId > expectedId) { + return expectedId - currentPageNumber; + } + } + } + if (previous) { + const firstId = yArray[0]; + if (firstId < currentPageNumber) { + return currentPageNumber - firstId + 1; + } + } else { + const lastId = yArray[numPages - 1]; + if (lastId > currentPageNumber) { + return lastId - currentPageNumber + 1; + } + } + break; + } + break; + } + case ScrollMode.HORIZONTAL: + { + break; + } + case ScrollMode.PAGE: + case ScrollMode.VERTICAL: + { + if (this._spreadMode === SpreadMode.NONE) { + break; + } + const parity = this._spreadMode - 1; + if (previous && currentPageNumber % 2 !== parity) { + break; + } else if (!previous && currentPageNumber % 2 === parity) { + break; + } + const { + views + } = this._getVisiblePages(), + expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; + for (const { + id, + percent, + widthPercent + } of views) { + if (id !== expectedId) { + continue; + } + if (percent > 0 && widthPercent === 100) { + return 2; + } + break; + } + break; + } + } + return 1; } - if (evt.value !== pdfViewer.currentPageNumber.toString() && evt.value !== pdfViewer.currentPageLabel) { - this.toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel); + nextPage() { + const currentPageNumber = this._currentPageNumber, + pagesCount = this.pagesCount; + if (currentPageNumber >= pagesCount) { + return false; + } + const advance = this._getPageAdvance(currentPageNumber, false) || 1; + this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); + return true; } -} -function onImageAltTextSettings() { - this.imageAltTextSettings?.open({ - enableGuessAltText: AppOptions.get("enableGuessAltText"), - enableNewAltTextWhenAddingImage: AppOptions.get("enableNewAltTextWhenAddingImage") - }); -} -function onFindFromUrlHash(evt) { - this.eventBus.dispatch("find", { - source: evt.source, - type: "", - query: evt.query, - caseSensitive: false, - entireWord: false, - highlightAll: true, - findPrevious: false, - matchDiacritics: true - }); -} -function onUpdateFindMatchesCount({ - matchesCount -}) { - if (this.supportsIntegratedFind) { - this.externalServices.updateFindMatchesCount(matchesCount); - } else { - this.findBar?.updateResultsCount(matchesCount); + previousPage() { + const currentPageNumber = this._currentPageNumber; + if (currentPageNumber <= 1) { + return false; + } + const advance = this._getPageAdvance(currentPageNumber, true) || 1; + this.currentPageNumber = Math.max(currentPageNumber - advance, 1); + return true; } -} -function onUpdateFindControlState({ - state, - previous, - entireWord, - matchesCount, - rawQuery -}) { - if (this.supportsIntegratedFind) { - this.externalServices.updateFindControlState({ - result: state, - findPrevious: previous, - entireWord, - matchesCount, - rawQuery + updateScale({ + drawingDelay, + scaleFactor = null, + steps = null, + origin + }) { + if (steps === null && scaleFactor === null) { + throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided."); + } + if (!this.pdfDocument) { + return; + } + let newScale = this._currentScale; + if (scaleFactor > 0 && scaleFactor !== 1) { + newScale = Math.round(newScale * scaleFactor * 100) / 100; + } else if (steps) { + const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA; + const round = steps > 0 ? Math.ceil : Math.floor; + steps = Math.abs(steps); + do { + newScale = round((newScale * delta).toFixed(2) * 10) / 10; + } while (--steps > 0); + } + newScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale)); + this.#setScale(newScale, { + noScroll: false, + drawingDelay, + origin }); - } else { - this.findBar?.updateUIState(state, previous, matchesCount); } -} -function onScaleChanging(evt) { - this.toolbar?.setPageScale(evt.presetValue, evt.scale); - this.pdfViewer.update(); -} -function onRotationChanging(evt) { - if (this.pdfThumbnailViewer) { - this.pdfThumbnailViewer.pagesRotation = evt.pagesRotation; + increaseScale(options = {}) { + this.updateScale({ + ...options, + steps: options.steps ?? 1 + }); } - this.forceRendering(); - this.pdfViewer.currentPageNumber = evt.pageNumber; -} -function onPageChanging({ - pageNumber, - pageLabel -}) { - this.toolbar?.setPageNumber(pageNumber, pageLabel); - this.secondaryToolbar?.setPageNumber(pageNumber); - if (this.pdfSidebar?.visibleView === SidebarView.THUMBS) { - this.pdfThumbnailViewer?.scrollThumbnailIntoView(pageNumber); + decreaseScale(options = {}) { + this.updateScale({ + ...options, + steps: -(options.steps ?? 1) + }); } - const currentPage = this.pdfViewer.getPageView(pageNumber - 1); - this.toolbar?.updateLoadingIndicatorState(currentPage?.renderingState === RenderingStates.RUNNING); -} -function onWheel(evt) { - const { - pdfViewer, - supportsMouseWheelZoomCtrlKey, - supportsMouseWheelZoomMetaKey, - supportsPinchToZoom - } = this; - if (pdfViewer.isInPresentationMode) { - return; + #updateContainerHeightCss(height = this.container.clientHeight) { + if (height !== this.#previousContainerHeight) { + this.#previousContainerHeight = height; + docStyle.setProperty("--viewer-container-height", `${height}px`); + } } - const deltaMode = evt.deltaMode; - let scaleFactor = Math.exp(-evt.deltaY / 100); - const isBuiltInMac = false; - const isPinchToZoom = evt.ctrlKey && !this._isCtrlKeyDown && deltaMode === WheelEvent.DOM_DELTA_PIXEL && evt.deltaX === 0 && (Math.abs(scaleFactor - 1) < 0.05 || isBuiltInMac) && evt.deltaZ === 0; - const origin = [evt.clientX, evt.clientY]; - if (isPinchToZoom || evt.ctrlKey && supportsMouseWheelZoomCtrlKey || evt.metaKey && supportsMouseWheelZoomMetaKey) { - evt.preventDefault(); - if (this._isScrolling || document.visibilityState === "hidden" || this.overlayManager.active) { - return; - } - if (isPinchToZoom && supportsPinchToZoom) { - scaleFactor = this._accumulateFactor(pdfViewer.currentScale, scaleFactor, "_wheelUnusedFactor"); - this.updateZoom(null, scaleFactor, origin); - } else { - const delta = normalizeWheelEventDirection(evt); - let ticks = 0; - if (deltaMode === WheelEvent.DOM_DELTA_LINE || deltaMode === WheelEvent.DOM_DELTA_PAGE) { - ticks = Math.abs(delta) >= 1 ? Math.sign(delta) : this._accumulateTicks(delta, "_wheelUnusedTicks"); - } else { - const PIXELS_PER_LINE_SCALE = 30; - ticks = this._accumulateTicks(delta / PIXELS_PER_LINE_SCALE, "_wheelUnusedTicks"); + #resizeObserverCallback(entries) { + for (const entry of entries) { + if (entry.target === this.container) { + this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize)); + this.#containerTopLeft = null; + break; } - this.updateZoom(ticks, null, origin); } } -} -function closeSecondaryToolbar(evt) { - if (!this.secondaryToolbar?.isOpen) { - return; - } - const appConfig = this.appConfig; - if (this.pdfViewer.containsElement(evt.target) || appConfig.toolbar?.container.contains(evt.target) && !appConfig.secondaryToolbar?.toggleButton.contains(evt.target)) { - this.secondaryToolbar.close(); - } -} -function closeEditorUndoBar(evt) { - if (!this.editorUndoBar?.isOpen) { - return; - } - if (this.appConfig.secondaryToolbar?.toolbar.contains(evt.target)) { - this.editorUndoBar.hide(); - } -} -function onClick(evt) { - closeSecondaryToolbar.call(this, evt); - closeEditorUndoBar.call(this, evt); -} -function onKeyUp(evt) { - if (evt.key === "Control") { - this._isCtrlKeyDown = false; - } -} -function onKeyDown(evt) { - this._isCtrlKeyDown = evt.key === "Control"; - if (this.editorUndoBar?.isOpen && evt.keyCode !== 9 && evt.keyCode !== 16 && !((evt.keyCode === 13 || evt.keyCode === 32) && getActiveOrFocusedElement() === this.appConfig.editorUndoBar.undoButton)) { - this.editorUndoBar.hide(); - } - if (this.overlayManager.active) { - return; + get containerTopLeft() { + return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft]; } - const { - eventBus, - pdfViewer - } = this; - const isViewerInPresentationMode = pdfViewer.isInPresentationMode; - let handled = false, - ensureViewerFocused = false; - const cmd = (evt.ctrlKey ? 1 : 0) | (evt.altKey ? 2 : 0) | (evt.shiftKey ? 4 : 0) | (evt.metaKey ? 8 : 0); - if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) { - switch (evt.keyCode) { - case 70: - if (!this.supportsIntegratedFind && !evt.shiftKey) { - this.findBar?.open(); - handled = true; - } - break; - case 71: - if (!this.supportsIntegratedFind) { - const { - state - } = this.findController; - if (state) { - const newState = { - source: window, - type: "again", - findPrevious: cmd === 5 || cmd === 12 - }; - eventBus.dispatch("find", { - ...state, - ...newState - }); - } - handled = true; - } - break; - case 61: - case 107: - case 187: - case 171: - this.zoomIn(); - handled = true; - break; - case 173: - case 109: - case 189: - this.zoomOut(); - handled = true; - break; - case 48: - case 96: - if (!isViewerInPresentationMode) { - setTimeout(() => { - this.zoomReset(); - }); - handled = false; - } - break; - case 38: - if (isViewerInPresentationMode || this.page > 1) { - this.page = 1; - handled = true; - ensureViewerFocused = true; - } - break; - case 40: - if (isViewerInPresentationMode || this.page < this.pagesCount) { - this.page = this.pagesCount; - handled = true; - ensureViewerFocused = true; - } - break; + #cleanupSwitchAnnotationEditorMode() { + this.#switchAnnotationEditorModeAC?.abort(); + this.#switchAnnotationEditorModeAC = null; + if (this.#switchAnnotationEditorModeTimeoutId !== null) { + clearTimeout(this.#switchAnnotationEditorModeTimeoutId); + this.#switchAnnotationEditorModeTimeoutId = null; } } - if (cmd === 1 || cmd === 8) { - switch (evt.keyCode) { - case 83: - eventBus.dispatch("download", { - source: window - }); - handled = true; - break; - case 79: - { - eventBus.dispatch("openfile", { - source: window - }); - handled = true; - } - break; - } + get annotationEditorMode() { + return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE; } - if (cmd === 3 || cmd === 10) { - switch (evt.keyCode) { - case 80: - this.requestPresentationMode(); - handled = true; - this.externalServices.reportTelemetry({ - type: "buttons", - data: { - id: "presentationModeKeyboard" - } - }); - break; - case 71: - if (this.appConfig.toolbar) { - this.appConfig.toolbar.pageNumber.select(); - handled = true; - } - break; + set annotationEditorMode({ + mode, + editId = null, + isFromKeyboard = false + }) { + if (!this.#annotationEditorUIManager) { + throw new Error(`The AnnotationEditor is not enabled.`); } - } - if (handled) { - if (ensureViewerFocused && !isViewerInPresentationMode) { - pdfViewer.focus(); + if (this.#annotationEditorMode === mode) { + return; } - evt.preventDefault(); - return; - } - const curElement = getActiveOrFocusedElement(); - const curElementTagName = curElement?.tagName.toUpperCase(); - if (curElementTagName === "INPUT" || curElementTagName === "TEXTAREA" || curElementTagName === "SELECT" || curElementTagName === "BUTTON" && (evt.keyCode === 13 || evt.keyCode === 32) || curElement?.isContentEditable) { - if (evt.keyCode !== 27) { + if (!isValidAnnotationEditorMode(mode)) { + throw new Error(`Invalid AnnotationEditor mode: ${mode}`); + } + if (!this.pdfDocument) { return; } - } - if (cmd === 0) { - let turnPage = 0, - turnOnlyIfPageFit = false; - switch (evt.keyCode) { - case 38: - if (this.supportsCaretBrowsingMode) { - this.moveCaret(true, false); - handled = true; - break; - } - case 33: - if (pdfViewer.isVerticalScrollbarEnabled) { - turnOnlyIfPageFit = true; - } - turnPage = -1; - break; - case 8: - if (!isViewerInPresentationMode) { - turnOnlyIfPageFit = true; - } - turnPage = -1; - break; - case 37: - if (this.supportsCaretBrowsingMode) { - return; - } - if (pdfViewer.isHorizontalScrollbarEnabled) { - turnOnlyIfPageFit = true; - } - case 75: - case 80: - turnPage = -1; - break; - case 27: - if (this.secondaryToolbar?.isOpen) { - this.secondaryToolbar.close(); - handled = true; - } - if (!this.supportsIntegratedFind && this.findBar?.opened) { - this.findBar.close(); - handled = true; - } - break; - case 40: - if (this.supportsCaretBrowsingMode) { - this.moveCaret(false, false); - handled = true; - break; - } - case 34: - if (pdfViewer.isVerticalScrollbarEnabled) { - turnOnlyIfPageFit = true; - } - turnPage = 1; - break; - case 13: - case 32: - if (!isViewerInPresentationMode) { - turnOnlyIfPageFit = true; - } - turnPage = 1; - break; - case 39: - if (this.supportsCaretBrowsingMode) { - return; - } - if (pdfViewer.isHorizontalScrollbarEnabled) { - turnOnlyIfPageFit = true; - } - case 74: - case 78: - turnPage = 1; - break; - case 36: - if (isViewerInPresentationMode || this.page > 1) { - this.page = 1; - handled = true; - ensureViewerFocused = true; - } - break; - case 35: - if (isViewerInPresentationMode || this.page < this.pagesCount) { - this.page = this.pagesCount; - handled = true; - ensureViewerFocused = true; - } - break; - case 83: - this.pdfCursorTools?.switchTool(CursorTool.SELECT); - break; - case 72: - this.pdfCursorTools?.switchTool(CursorTool.HAND); - break; - case 82: - this.rotatePages(90); - break; - case 115: - this.pdfSidebar?.toggle(); - break; + if (mode === AnnotationEditorType.STAMP) { + this.#mlManager?.loadModel("altText"); } - if (turnPage !== 0 && (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === "page-fit")) { - if (turnPage > 0) { - pdfViewer.nextPage(); - } else { - pdfViewer.previousPage(); + const { + eventBus + } = this; + const updater = () => { + this.#cleanupSwitchAnnotationEditorMode(); + this.#annotationEditorMode = mode; + this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard); + eventBus.dispatch("annotationeditormodechanged", { + source: this, + mode + }); + }; + if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) { + const isEditing = mode !== AnnotationEditorType.NONE; + if (!isEditing) { + this.pdfDocument.annotationStorage.resetModifiedIds(); + } + for (const pageView of this._pages) { + pageView.toggleEditingMode(isEditing); + } + const idsToRefresh = this.#switchToEditAnnotationMode(); + if (isEditing && idsToRefresh) { + this.#cleanupSwitchAnnotationEditorMode(); + this.#switchAnnotationEditorModeAC = new AbortController(); + const signal = AbortSignal.any([this.#eventAbortController.signal, this.#switchAnnotationEditorModeAC.signal]); + eventBus._on("pagerendered", ({ + pageNumber + }) => { + idsToRefresh.delete(pageNumber); + if (idsToRefresh.size === 0) { + this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0); + } + }, { + signal + }); + return; } - handled = true; } + updater(); } - if (cmd === 4) { - switch (evt.keyCode) { - case 13: - case 32: - if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== "page-fit") { - break; - } - pdfViewer.previousPage(); - handled = true; - break; - case 38: - this.moveCaret(true, true); - handled = true; - break; - case 40: - this.moveCaret(false, true); - handled = true; - break; - case 82: - this.rotatePages(-90); - break; + refresh(noUpdate = false, updateArgs = Object.create(null)) { + if (!this.pdfDocument) { + return; } - } - if (!handled && !isViewerInPresentationMode) { - if (evt.keyCode >= 33 && evt.keyCode <= 40 || evt.keyCode === 32 && curElementTagName !== "BUTTON") { - ensureViewerFocused = true; + for (const pageView of this._pages) { + pageView.update(updateArgs); + } + if (this.#scaleTimeoutId !== null) { + clearTimeout(this.#scaleTimeoutId); + this.#scaleTimeoutId = null; + } + if (!noUpdate) { + this.update(); } - } - if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) { - pdfViewer.focus(); - } - if (handled) { - evt.preventDefault(); } } -function beforeUnload(evt) { - evt.preventDefault(); - evt.returnValue = ""; - return false; + +;// ./web/pdf_single_page_viewer.js + + +class PDFSinglePageViewer extends PDFViewer { + _resetView() { + super._resetView(); + this._scrollMode = ScrollMode.PAGE; + this._spreadMode = SpreadMode.NONE; + } + set scrollMode(mode) {} + _updateScrollMode() {} + set spreadMode(mode) {} + _updateSpreadMode() {} } -;// ./web/viewer.js +;// ./web/pdf_viewer.component.js + + + + + + + + + + + const pdfjsVersion = "4.10.38"; const pdfjsBuild = "f9bea397f"; -const AppConstants = { - LinkTarget: LinkTarget, - RenderingStates: RenderingStates, - ScrollMode: ScrollMode, - SpreadMode: SpreadMode -}; -window.PDFViewerApplication = PDFViewerApplication; -window.PDFViewerApplicationConstants = AppConstants; -window.PDFViewerApplicationOptions = AppOptions; -function getViewerConfiguration() { - return { - appContainer: document.body, - principalContainer: document.getElementById("mainContainer"), - mainContainer: document.getElementById("viewerContainer"), - viewerContainer: document.getElementById("viewer"), - toolbar: { - container: document.getElementById("toolbarContainer"), - numPages: document.getElementById("numPages"), - pageNumber: document.getElementById("pageNumber"), - scaleSelect: document.getElementById("scaleSelect"), - customScaleOption: document.getElementById("customScaleOption"), - previous: document.getElementById("previous"), - next: document.getElementById("next"), - zoomIn: document.getElementById("zoomInButton"), - zoomOut: document.getElementById("zoomOutButton"), - print: document.getElementById("printButton"), - editorFreeTextButton: document.getElementById("editorFreeTextButton"), - editorFreeTextParamsToolbar: document.getElementById("editorFreeTextParamsToolbar"), - editorHighlightButton: document.getElementById("editorHighlightButton"), - editorHighlightParamsToolbar: document.getElementById("editorHighlightParamsToolbar"), - editorHighlightColorPicker: document.getElementById("editorHighlightColorPicker"), - editorInkButton: document.getElementById("editorInkButton"), - editorInkParamsToolbar: document.getElementById("editorInkParamsToolbar"), - editorStampButton: document.getElementById("editorStampButton"), - editorStampParamsToolbar: document.getElementById("editorStampParamsToolbar"), - download: document.getElementById("downloadButton") - }, - secondaryToolbar: { - toolbar: document.getElementById("secondaryToolbar"), - toggleButton: document.getElementById("secondaryToolbarToggleButton"), - presentationModeButton: document.getElementById("presentationMode"), - openFileButton: document.getElementById("secondaryOpenFile"), - printButton: document.getElementById("secondaryPrint"), - downloadButton: document.getElementById("secondaryDownload"), - viewBookmarkButton: document.getElementById("viewBookmark"), - firstPageButton: document.getElementById("firstPage"), - lastPageButton: document.getElementById("lastPage"), - pageRotateCwButton: document.getElementById("pageRotateCw"), - pageRotateCcwButton: document.getElementById("pageRotateCcw"), - cursorSelectToolButton: document.getElementById("cursorSelectTool"), - cursorHandToolButton: document.getElementById("cursorHandTool"), - scrollPageButton: document.getElementById("scrollPage"), - scrollVerticalButton: document.getElementById("scrollVertical"), - scrollHorizontalButton: document.getElementById("scrollHorizontal"), - scrollWrappedButton: document.getElementById("scrollWrapped"), - spreadNoneButton: document.getElementById("spreadNone"), - spreadOddButton: document.getElementById("spreadOdd"), - spreadEvenButton: document.getElementById("spreadEven"), - imageAltTextSettingsButton: document.getElementById("imageAltTextSettings"), - imageAltTextSettingsSeparator: document.getElementById("imageAltTextSettingsSeparator"), - documentPropertiesButton: document.getElementById("documentProperties") - }, - sidebar: { - outerContainer: document.getElementById("outerContainer"), - sidebarContainer: document.getElementById("sidebarContainer"), - toggleButton: document.getElementById("sidebarToggleButton"), - resizer: document.getElementById("sidebarResizer"), - thumbnailButton: document.getElementById("viewThumbnail"), - outlineButton: document.getElementById("viewOutline"), - attachmentsButton: document.getElementById("viewAttachments"), - layersButton: document.getElementById("viewLayers"), - thumbnailView: document.getElementById("thumbnailView"), - outlineView: document.getElementById("outlineView"), - attachmentsView: document.getElementById("attachmentsView"), - layersView: document.getElementById("layersView"), - currentOutlineItemButton: document.getElementById("currentOutlineItem") - }, - findBar: { - bar: document.getElementById("findbar"), - toggleButton: document.getElementById("viewFindButton"), - findField: document.getElementById("findInput"), - highlightAllCheckbox: document.getElementById("findHighlightAll"), - caseSensitiveCheckbox: document.getElementById("findMatchCase"), - matchDiacriticsCheckbox: document.getElementById("findMatchDiacritics"), - entireWordCheckbox: document.getElementById("findEntireWord"), - findMsg: document.getElementById("findMsg"), - findResultsCount: document.getElementById("findResultsCount"), - findPreviousButton: document.getElementById("findPreviousButton"), - findNextButton: document.getElementById("findNextButton") - }, - passwordOverlay: { - dialog: document.getElementById("passwordDialog"), - label: document.getElementById("passwordText"), - input: document.getElementById("password"), - submitButton: document.getElementById("passwordSubmit"), - cancelButton: document.getElementById("passwordCancel") - }, - documentProperties: { - dialog: document.getElementById("documentPropertiesDialog"), - closeButton: document.getElementById("documentPropertiesClose"), - fields: { - fileName: document.getElementById("fileNameField"), - fileSize: document.getElementById("fileSizeField"), - title: document.getElementById("titleField"), - author: document.getElementById("authorField"), - subject: document.getElementById("subjectField"), - keywords: document.getElementById("keywordsField"), - creationDate: document.getElementById("creationDateField"), - modificationDate: document.getElementById("modificationDateField"), - creator: document.getElementById("creatorField"), - producer: document.getElementById("producerField"), - version: document.getElementById("versionField"), - pageCount: document.getElementById("pageCountField"), - pageSize: document.getElementById("pageSizeField"), - linearized: document.getElementById("linearizedField") - } - }, - altTextDialog: { - dialog: document.getElementById("altTextDialog"), - optionDescription: document.getElementById("descriptionButton"), - optionDecorative: document.getElementById("decorativeButton"), - textarea: document.getElementById("descriptionTextarea"), - cancelButton: document.getElementById("altTextCancel"), - saveButton: document.getElementById("altTextSave") - }, - newAltTextDialog: { - dialog: document.getElementById("newAltTextDialog"), - title: document.getElementById("newAltTextTitle"), - descriptionContainer: document.getElementById("newAltTextDescriptionContainer"), - textarea: document.getElementById("newAltTextDescriptionTextarea"), - disclaimer: document.getElementById("newAltTextDisclaimer"), - learnMore: document.getElementById("newAltTextLearnMore"), - imagePreview: document.getElementById("newAltTextImagePreview"), - createAutomatically: document.getElementById("newAltTextCreateAutomatically"), - createAutomaticallyButton: document.getElementById("newAltTextCreateAutomaticallyButton"), - downloadModel: document.getElementById("newAltTextDownloadModel"), - downloadModelDescription: document.getElementById("newAltTextDownloadModelDescription"), - error: document.getElementById("newAltTextError"), - errorCloseButton: document.getElementById("newAltTextCloseButton"), - cancelButton: document.getElementById("newAltTextCancel"), - notNowButton: document.getElementById("newAltTextNotNow"), - saveButton: document.getElementById("newAltTextSave") - }, - altTextSettingsDialog: { - dialog: document.getElementById("altTextSettingsDialog"), - createModelButton: document.getElementById("createModelButton"), - aiModelSettings: document.getElementById("aiModelSettings"), - learnMore: document.getElementById("altTextSettingsLearnMore"), - deleteModelButton: document.getElementById("deleteModelButton"), - downloadModelButton: document.getElementById("downloadModelButton"), - showAltTextDialogButton: document.getElementById("showAltTextDialogButton"), - altTextSettingsCloseButton: document.getElementById("altTextSettingsCloseButton"), - closeButton: document.getElementById("altTextSettingsCloseButton") - }, - annotationEditorParams: { - editorFreeTextFontSize: document.getElementById("editorFreeTextFontSize"), - editorFreeTextColor: document.getElementById("editorFreeTextColor"), - editorInkColor: document.getElementById("editorInkColor"), - editorInkThickness: document.getElementById("editorInkThickness"), - editorInkOpacity: document.getElementById("editorInkOpacity"), - editorStampAddImage: document.getElementById("editorStampAddImage"), - editorFreeHighlightThickness: document.getElementById("editorFreeHighlightThickness"), - editorHighlightShowAll: document.getElementById("editorHighlightShowAll") - }, - printContainer: document.getElementById("printContainer"), - editorUndoBar: { - container: document.getElementById("editorUndoBar"), - message: document.getElementById("editorUndoBarMessage"), - undoButton: document.getElementById("editorUndoBarUndoButton"), - closeButton: document.getElementById("editorUndoBarCloseButton") - } - }; -} -function webViewerLoad() { - const config = getViewerConfiguration(); - const event = new CustomEvent("webviewerloaded", { - bubbles: true, - cancelable: true, - detail: { - source: window - } - }); - try { - parent.document.dispatchEvent(event); - } catch (ex) { - console.error("webviewerloaded:", ex); - document.dispatchEvent(event); - } - PDFViewerApplication.run(config); -} -document.blockUnblockOnload?.(true); -if (document.readyState === "interactive" || document.readyState === "complete") { - webViewerLoad(); -} else { - document.addEventListener("DOMContentLoaded", webViewerLoad, true); -} - -var __webpack_exports__PDFViewerApplication = __webpack_exports__.PDFViewerApplication; -var __webpack_exports__PDFViewerApplicationConstants = __webpack_exports__.PDFViewerApplicationConstants; -var __webpack_exports__PDFViewerApplicationOptions = __webpack_exports__.PDFViewerApplicationOptions; -export { __webpack_exports__PDFViewerApplication as PDFViewerApplication, __webpack_exports__PDFViewerApplicationConstants as PDFViewerApplicationConstants, __webpack_exports__PDFViewerApplicationOptions as PDFViewerApplicationOptions }; -//# sourceMappingURL=viewer.mjs.map \ No newline at end of file +var __webpack_exports__AnnotationLayerBuilder = __webpack_exports__.AnnotationLayerBuilder; +var __webpack_exports__DownloadManager = __webpack_exports__.DownloadManager; +var __webpack_exports__EventBus = __webpack_exports__.EventBus; +var __webpack_exports__FindState = __webpack_exports__.FindState; +var __webpack_exports__GenericL10n = __webpack_exports__.GenericL10n; +var __webpack_exports__LinkTarget = __webpack_exports__.LinkTarget; +var __webpack_exports__PDFFindController = __webpack_exports__.PDFFindController; +var __webpack_exports__PDFHistory = __webpack_exports__.PDFHistory; +var __webpack_exports__PDFLinkService = __webpack_exports__.PDFLinkService; +var __webpack_exports__PDFPageView = __webpack_exports__.PDFPageView; +var __webpack_exports__PDFScriptingManager = __webpack_exports__.PDFScriptingManager; +var __webpack_exports__PDFSinglePageViewer = __webpack_exports__.PDFSinglePageViewer; +var __webpack_exports__PDFViewer = __webpack_exports__.PDFViewer; +var __webpack_exports__ProgressBar = __webpack_exports__.ProgressBar; +var __webpack_exports__RenderingStates = __webpack_exports__.RenderingStates; +var __webpack_exports__ScrollMode = __webpack_exports__.ScrollMode; +var __webpack_exports__SimpleLinkService = __webpack_exports__.SimpleLinkService; +var __webpack_exports__SpreadMode = __webpack_exports__.SpreadMode; +var __webpack_exports__StructTreeLayerBuilder = __webpack_exports__.StructTreeLayerBuilder; +var __webpack_exports__TextLayerBuilder = __webpack_exports__.TextLayerBuilder; +var __webpack_exports__XfaLayerBuilder = __webpack_exports__.XfaLayerBuilder; +var __webpack_exports__parseQueryString = __webpack_exports__.parseQueryString; +export { __webpack_exports__AnnotationLayerBuilder as AnnotationLayerBuilder, __webpack_exports__DownloadManager as DownloadManager, __webpack_exports__EventBus as EventBus, __webpack_exports__FindState as FindState, __webpack_exports__GenericL10n as GenericL10n, __webpack_exports__LinkTarget as LinkTarget, __webpack_exports__PDFFindController as PDFFindController, __webpack_exports__PDFHistory as PDFHistory, __webpack_exports__PDFLinkService as PDFLinkService, __webpack_exports__PDFPageView as PDFPageView, __webpack_exports__PDFScriptingManager as PDFScriptingManager, __webpack_exports__PDFSinglePageViewer as PDFSinglePageViewer, __webpack_exports__PDFViewer as PDFViewer, __webpack_exports__ProgressBar as ProgressBar, __webpack_exports__RenderingStates as RenderingStates, __webpack_exports__ScrollMode as ScrollMode, __webpack_exports__SimpleLinkService as SimpleLinkService, __webpack_exports__SpreadMode as SpreadMode, __webpack_exports__StructTreeLayerBuilder as StructTreeLayerBuilder, __webpack_exports__TextLayerBuilder as TextLayerBuilder, __webpack_exports__XfaLayerBuilder as XfaLayerBuilder, __webpack_exports__parseQueryString as parseQueryString }; + +//# sourceMappingURL=pdf_viewer.mjs.map \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/tailwindcss/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/tailwindcss/README.md similarity index 85% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/tailwindcss/README.md rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/tailwindcss/README.md index 7baede5a2c1..c3a1597ee61 100644 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/tailwindcss/README.md +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/tailwindcss/README.md @@ -4,4 +4,4 @@ License: MIT This template uses only `preflight.css`, the CSS reset stylesheet from Tailwind. For simplicity, this template doesn't use a complete deployment of Tailwind. If you want to use the full Tailwind library, remove `preflight.css` and reference the full version of Tailwind. -To update, replace the `preflight.css` file with the one in an updated build from https://github.com/tailwindlabs/tailwindcss/releases +To update, replace the `preflight.css` file with the one in an updated build from https://www.npmjs.com/package/tailwindcss diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/tailwindcss/web/preflight.css b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/tailwindcss/dist/preflight.css similarity index 100% rename from src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/tailwindcss/web/preflight.css rename to src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/lib/tailwindcss/dist/preflight.css diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/marked/README.md b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/marked/README.md deleted file mode 100644 index 626d9329c38..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/marked/README.md +++ /dev/null @@ -1,5 +0,0 @@ -marked version 15.0.6 -https://github.com/markedjs/marked -License: MIT - -To update, replace the files with those installed by following the instructions in https://github.com/markedjs/marked/blob/master/README.md#installation diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/marked/web/marked.esm.js.map b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/marked/web/marked.esm.js.map deleted file mode 100644 index 8dac010e0e3..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/marked/web/marked.esm.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"marked.esm.js","sources":["../src/defaults.ts","../src/rules.ts","../src/helpers.ts","../src/Tokenizer.ts","../src/Lexer.ts","../src/Renderer.ts","../src/TextRenderer.ts","../src/Parser.ts","../src/Hooks.ts","../src/Instance.ts","../src/marked.ts"],"sourcesContent":["/**\n * Gets the original marked default options.\n */\nexport function _getDefaults() {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null,\n };\n}\nexport let _defaults = _getDefaults();\nexport function changeDefaults(newDefaults) {\n _defaults = newDefaults;\n}\n","const noopTest = { exec: () => null };\nfunction edit(regex, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name, val) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n },\n };\n return obj;\n}\nexport const other = {\n codeRemoveIndent: /^(?: {1,4}| {0,3}\\t)/gm,\n outputLinkReplace: /\\\\([\\[\\]])/g,\n indentCodeCompensation: /^(\\s+)(?:```)/,\n beginningSpace: /^\\s+/,\n endingHash: /#$/,\n startingSpaceChar: /^ /,\n endingSpaceChar: / $/,\n nonSpaceChar: /[^ ]/,\n newLineCharGlobal: /\\n/g,\n tabCharGlobal: /\\t/g,\n multipleSpaceGlobal: /\\s+/g,\n blankLine: /^[ \\t]*$/,\n doubleBlankLine: /\\n[ \\t]*\\n[ \\t]*$/,\n blockquoteStart: /^ {0,3}>/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceTabs: /^\\t+/,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] /,\n listReplaceTask: /^\\[[ xX]\\] +/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^/i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n unescapeTest: /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'),\n};\n/**\n * Block-Level Grammar\n */\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\.|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /|$))/;\nconst html = edit('^ {0,3}(?:' // optional indentation\n + '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:[^\\\\n]*\\\\n+|$)' // (1)\n + '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n + '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n + '|\\\\n*|$)' // (4)\n + '|\\\\n*|$)' // (5)\n + '|)[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (6)\n + '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n + '|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) closing tag\n + ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n/**\n * Normal Block Grammar\n */\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText,\n};\n/**\n * GFM Block Grammar\n */\nconst gfmTable = edit('^ *([^\\\\n ].*)\\\\n' // Header\n + ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n + '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', '(?: {4}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\nconst blockGfm = {\n ...blockNormal,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex(),\n};\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\nconst blockPedantic = {\n ...blockNormal,\n html: edit('^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+? *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex(),\n};\n/**\n * Inline-Level Grammar\n */\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\\nconst blockSkip = /\\[[^[\\]]*?\\]\\((?:\\\\.|[^\\\\\\(\\)]|\\((?:\\\\.|[^\\\\\\(\\)])*\\))*\\)|`[^`]*?`|<[^<>]*?>/g;\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|[^\\s*]))|^_+(?:((?!_)punct)|([^\\s_]))/;\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\nconst emStrongRDelimAstCore = '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n + '|[^*]+(?=[^*])' // Consume to delim\n + '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n + '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n + '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter\n + '|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)' // (4) ***# can only be Left Delimiter\n + '|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter\n + '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit('^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n + '|[^_]+(?=[^_])' // Consume to delim\n + '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n + '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n + '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter\n + '|[\\\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter\n + '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit('^comment'\n + '|^' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. \n + '|^' // declaration, e.g. \n + '|^') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\nconst _inlineLabel = /(?:\\[(?:\\\\.|[^\\[\\]\\\\])*\\]|\\\\.|`[^`]*`|[^\\[\\]\\\\`])*?/;\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:\\s+(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^\\s\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n/**\n * Normal Inline Grammar\n */\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest,\n};\n/**\n * Pedantic Inline Grammar\n */\nconst inlinePedantic = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex(),\n};\n/**\n * GFM Inline Grammar\n */\nconst inlineGfm = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n url: edit(/^((?:ftp|https?):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/, 'i')\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])((?:\\\\.|[^\\\\])*?(?:\\\\.|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: /^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch) => escapeReplacements[ch];\nexport function escape(html, encode) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n }\n else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n return html;\n}\nexport function unescape(html) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(other.unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon')\n return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\nexport function cleanUrl(href) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n }\n catch {\n return null;\n }\n return href;\n}\nexport function splitCells(tableRow, count) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\')\n escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n }\n else {\n // add space before unescaped |\n return ' |';\n }\n }), cells = row.split(other.splitPipe);\n let i = 0;\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells.at(-1)?.trim()) {\n cells.pop();\n }\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n }\n else {\n while (cells.length < count)\n cells.push('');\n }\n }\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(other.slashPipe, '|');\n }\n return cells;\n}\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str, c, invert) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n }\n else if (currChar !== c && invert) {\n suffLen++;\n }\n else {\n break;\n }\n }\n return str.slice(0, l - suffLen);\n}\nexport function findClosingBracket(str, b) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n }\n else if (str[i] === b[0]) {\n level++;\n }\n else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n return -1;\n}\n","import { _defaults } from './defaults.ts';\nimport { rtrim, splitCells, findClosingBracket, } from './helpers.ts';\nfunction outputLink(cap, link, raw, lexer, rules) {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n if (cap[0].charAt(0) !== '!') {\n lexer.state.inLink = true;\n const token = {\n type: 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text),\n };\n lexer.state.inLink = false;\n return token;\n }\n return {\n type: 'image',\n raw,\n href,\n title,\n text,\n };\n}\nfunction indentCodeCompensation(raw, text, rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n if (matchIndentToCode === null) {\n return text;\n }\n const indentToCode = matchIndentToCode[1];\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n const [indentInNode] = matchIndentInNode;\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n return node;\n })\n .join('\\n');\n}\n/**\n * Tokenizer\n */\nexport class _Tokenizer {\n options;\n rules; // set by the lexer\n lexer; // set by the lexer\n constructor(options) {\n this.options = options || _defaults;\n }\n space(src) {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0],\n };\n }\n }\n code(src) {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text,\n };\n }\n }\n fences(src) {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text,\n };\n }\n }\n heading(src) {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n }\n else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n hr(src) {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n'),\n };\n }\n }\n blockquote(src) {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens = [];\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n }\n else if (!inBlockquote) {\n currentLines.push(lines[i]);\n }\n else {\n break;\n }\n }\n lines = lines.slice(i);\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n }\n else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n }\n else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens.at(-1).raw.length).split('\\n');\n continue;\n }\n }\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n list(src) {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n const list = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let raw = '';\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n raw = cap[0];\n src = src.substring(raw.length);\n let line = cap[2].split('\\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n }\n else if (blankLine) {\n indent = cap[1].length + 1;\n }\n else {\n indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n }\n else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');\n }\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n }\n else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n itemContents += '\\n' + nextLine;\n }\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\n }\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n }\n else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n let istask = null;\n let ischecked;\n // Check for task list items\n if (this.options.gfm) {\n istask = this.rules.other.listIsTask.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== '[ ] ';\n itemContents = itemContents.replace(this.rules.other.listReplaceTask, '');\n }\n }\n list.items.push({\n type: 'list_item',\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: [],\n });\n list.raw += raw;\n }\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n }\n else {\n // not a list since there were no items\n return;\n }\n list.raw = list.raw.trimEnd();\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (let i = 0; i < list.items.length; i++) {\n this.lexer.state.top = false;\n list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n if (!list.loose) {\n // Check if list should be loose\n const spacers = list.items[i].tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n list.loose = hasMultipleLineBreaks;\n }\n }\n // Set all items to loose if list is loose\n if (list.loose) {\n for (let i = 0; i < list.items.length; i++) {\n list.items[i].loose = true;\n }\n }\n return list;\n }\n }\n html(src) {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0],\n };\n return token;\n }\n }\n def(src) {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title,\n };\n }\n }\n table(src) {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n const item = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: [],\n };\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n }\n else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n }\n else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n }\n else {\n item.align.push(null);\n }\n }\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i],\n });\n }\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i],\n };\n }));\n }\n return item;\n }\n lheading(src) {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1]),\n };\n }\n }\n paragraph(src) {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n text(src) {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0]),\n };\n }\n }\n escape(src) {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n tag(src) {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n }\n else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n }\n else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0],\n };\n }\n }\n link(src) {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n }\n else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = this.rules.other.pedanticHrefTitle.exec(href);\n if (link) {\n href = link[1];\n title = link[3];\n }\n }\n else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n }\n else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,\n }, cap[0], this.lexer, this.rules);\n }\n }\n reflink(src, links) {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text,\n };\n }\n return outputLink(cap, link, cap[0], this.lexer, this.rules);\n }\n }\n emStrong(src, maskedSrc, prevChar = '') {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match)\n return;\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric))\n return;\n const nextChar = match[1] || match[2] || '';\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n if (!rDelim)\n continue; // skip single * in __abc*abc__\n rLength = [...rDelim].length;\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n }\n else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n delimTotal -= rLength;\n if (delimTotal > 0)\n continue; // Haven't found enough closing delimiters\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n codespan(src) {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n br(src) {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0],\n };\n }\n }\n del(src) {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2]),\n };\n }\n }\n autolink(src) {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n }\n else {\n text = cap[1];\n href = text;\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n url(src) {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\n }\n else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n }\n else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n inlineText(src) {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n escaped,\n };\n }\n }\n}\n","import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\n/**\n * Block Lexer\n */\nexport class _Lexer {\n tokens;\n options;\n state;\n tokenizer;\n inlineQueue;\n constructor(options) {\n // TokenList cannot be created in one go\n this.tokens = [];\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true,\n };\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n }\n else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n }\n else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n /**\n * Static Lex Method\n */\n static lex(src, options) {\n const lexer = new _Lexer(options);\n return lexer.lex(src);\n }\n /**\n * Static Lex Inline Method\n */\n static lexInline(src, options) {\n const lexer = new _Lexer(options);\n return lexer.inlineTokens(src);\n }\n /**\n * Preprocessing\n */\n lex(src) {\n src = src.replace(other.carriageReturn, '\\n');\n this.blockTokens(src, this.tokens);\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n return this.tokens;\n }\n blockTokens(src, tokens = [], lastParagraphClipped = false) {\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n while (src) {\n let token;\n if (this.options.extensions?.block?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n lastToken.raw += '\\n';\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1).src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1).src = lastToken.text;\n }\n else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n }\n continue;\n }\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1).src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += '\\n' + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1).src = lastToken.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n this.state.top = true;\n return tokens;\n }\n inline(src, tokens = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n /**\n * Lexing/Compiling\n */\n inlineTokens(src, tokens = []) {\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match = null;\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index)\n + '[' + 'a'.repeat(match[0].length - 2) + ']'\n + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n // Mask out other blocks\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n let keepPrevChar = false;\n let prevChar = '';\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n let token;\n // extensions\n if (this.options.extensions?.inline?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n }\n else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n }\n else {\n throw new Error(errMsg);\n }\n }\n }\n return tokens;\n }\n}\n","import { _defaults } from './defaults.ts';\nimport { cleanUrl, escape, } from './helpers.ts';\nimport { other } from './rules.ts';\n/**\n * Renderer\n */\nexport class _Renderer {\n options;\n parser; // set by the parser\n constructor(options) {\n this.options = options || _defaults;\n }\n space(token) {\n return '';\n }\n code({ text, lang, escaped }) {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n const code = text.replace(other.endingNewline, '') + '\\n';\n if (!langString) {\n return '
'\n                + (escaped ? code : escape(code, true))\n                + '
\\n';\n }\n return '
'\n            + (escaped ? code : escape(code, true))\n            + '
\\n';\n }\n blockquote({ tokens }) {\n const body = this.parser.parse(tokens);\n return `
\\n${body}
\\n`;\n }\n html({ text }) {\n return text;\n }\n heading({ tokens, depth }) {\n return `${this.parser.parseInline(tokens)}\\n`;\n }\n hr(token) {\n return '
\\n';\n }\n list(token) {\n const ordered = token.ordered;\n const start = token.start;\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '\\n';\n }\n listitem(item) {\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!item.checked });\n if (item.loose) {\n if (item.tokens[0]?.type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text);\n item.tokens[0].tokens[0].escaped = true;\n }\n }\n else {\n item.tokens.unshift({\n type: 'text',\n raw: checkbox + ' ',\n text: checkbox + ' ',\n escaped: true,\n });\n }\n }\n else {\n itemBody += checkbox + ' ';\n }\n }\n itemBody += this.parser.parse(item.tokens, !!item.loose);\n return `
  • ${itemBody}
  • \\n`;\n }\n checkbox({ checked }) {\n return '';\n }\n paragraph({ tokens }) {\n return `

    ${this.parser.parseInline(tokens)}

    \\n`;\n }\n table(token) {\n let header = '';\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell });\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n body += this.tablerow({ text: cell });\n }\n if (body)\n body = `${body}`;\n return '\\n'\n + '\\n'\n + header\n + '\\n'\n + body\n + '
    \\n';\n }\n tablerow({ text }) {\n return `\\n${text}\\n`;\n }\n tablecell(token) {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `\\n`;\n }\n /**\n * span level renderer\n */\n strong({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n em({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n codespan({ text }) {\n return `${escape(text, true)}`;\n }\n br(token) {\n return '
    ';\n }\n del({ tokens }) {\n return `${this.parser.parseInline(tokens)}`;\n }\n link({ href, title, tokens }) {\n const text = this.parser.parseInline(tokens);\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = '
    ';\n return out;\n }\n image({ href, title, text }) {\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escape(text);\n }\n href = cleanHref;\n let out = `\"${text}\"`;\n {\n const tokens = genericToken[childTokens].flat(Infinity);\n values = values.concat(this.walkTokens(tokens, callback));\n });\n }\n else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n use(...args) {\n const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack };\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function (...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n }\n else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n }\n else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n }\n else {\n extensions.startBlock = [ext.start];\n }\n }\n else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n }\n else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop;\n const rendererFunc = pack.renderer[rendererProp];\n const prevRenderer = renderer[rendererProp];\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return ret || '';\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop;\n const tokenizerFunc = pack.tokenizer[tokenizerProp];\n const prevTokenizer = tokenizer[tokenizerProp];\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop;\n const hooksFunc = pack.hooks[hooksProp];\n const prevHook = hooks[hooksProp];\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg) => {\n if (this.defaults.async) {\n return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {\n return prevHook.call(hooks, ret);\n });\n }\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n }\n else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args) => {\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function (token) {\n let values = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n this.defaults = { ...this.defaults, ...opts };\n });\n return this;\n }\n setOptions(opt) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n lexer(src, options) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n parser(tokens, options) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n parseMarkdown(blockType) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse = (src, options) => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n const throwError = this.onError(!!opt.silent, !!opt.async);\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n if (opt.async) {\n return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)\n .then(src => lexer(src, opt))\n .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)\n .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)\n .then(tokens => parser(tokens, opt))\n .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)\n .catch(throwError);\n }\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src);\n }\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n }\n catch (e) {\n return throwError(e);\n }\n };\n return parse;\n }\n onError(silent, async) {\n return (e) => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n if (silent) {\n const msg = '

    An error occurred:

    '\n                    + escape(e.message + '', true)\n                    + '
    ';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n","import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport { _getDefaults, changeDefaults, _defaults, } from './defaults.ts';\nconst markedInstance = new Marked();\nexport function marked(src, opt) {\n return markedInstance.parse(src, opt);\n}\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function (options) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\nmarked.defaults = _defaults;\n/**\n * Use Extension\n */\nmarked.use = function (...args) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n/**\n * Run callback for every token\n */\nmarked.walkTokens = function (tokens, callback) {\n return markedInstance.walkTokens(tokens, callback);\n};\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.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I,MAAM,CAAC,QAAQ,GAAG,cAAc,CAAC,QAAQ;AAC7C,IAAI,cAAc,CAAC,MAAM,CAAC,QAAQ,CAAC;AACnC,IAAI,OAAO,MAAM;AACjB,CAAC;AACD;AACA;AACA;AACA,MAAM,CAAC,UAAU,GAAG,UAAU,MAAM,EAAE,QAAQ,EAAE;AAChD,IAAI,OAAO,cAAc,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,CAAC;AACtD,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,CAAC,WAAW,GAAG,cAAc,CAAC,WAAW;AAC/C;AACA;AACA;AACA,MAAM,CAAC,MAAM,GAAG,OAAO;AACvB,MAAM,CAAC,MAAM,GAAG,OAAO,CAAC,KAAK;AAC7B,MAAM,CAAC,QAAQ,GAAG,SAAS;AAC3B,MAAM,CAAC,YAAY,GAAG,aAAa;AACnC,MAAM,CAAC,KAAK,GAAG,MAAM;AACrB,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG;AACzB,MAAM,CAAC,SAAS,GAAG,UAAU;AAC7B,MAAM,CAAC,KAAK,GAAG,MAAM;AACrB,MAAM,CAAC,KAAK,GAAG,MAAM;AACT,MAAC,OAAO,GAAG,MAAM,CAAC;AAClB,MAAC,UAAU,GAAG,MAAM,CAAC;AACrB,MAAC,GAAG,GAAG,MAAM,CAAC;AACd,MAAC,UAAU,GAAG,MAAM,CAAC;AACrB,MAAC,WAAW,GAAG,MAAM,CAAC;AACtB,MAAC,KAAK,GAAG;AACT,MAAC,MAAM,GAAG,OAAO,CAAC;AAClB,MAAC,KAAK,GAAG,MAAM,CAAC;;;;"} \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdf_viewer/viewer.html b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdf_viewer/viewer.html new file mode 100644 index 00000000000..15afdb9607a --- /dev/null +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdf_viewer/viewer.html @@ -0,0 +1,31 @@ + + + + + + PDF viewer + + + + + + +
    +
    +
    + + + + diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdf_viewer/viewer.mjs b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdf_viewer/viewer.mjs new file mode 100644 index 00000000000..b0e01112afd --- /dev/null +++ b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdf_viewer/viewer.mjs @@ -0,0 +1,62 @@ +import { GlobalWorkerOptions } from '../lib/pdfjs-dist/dist/build/pdf.min.mjs'; +import { EventBus, PDFLinkService, PDFFindController, PDFViewer } from '../lib/pdfjs-dist/dist/web/pdf_viewer.mjs'; + +GlobalWorkerOptions.workerSrc = '../lib/pdfjs-dist/dist/build/pdf.worker.min.mjs'; + +// Extract the file path from the URL query string. +const url = new URL(window.location); +const fileUrl = url.searchParams.get('file'); +if (!fileUrl) { + throw new Error('File not specified in the URL query string'); +} + +const container = document.getElementById('viewerContainer'); +const eventBus = new EventBus(); + +// Enable hyperlinks within PDF files. +const pdfLinkService = new PDFLinkService({ + eventBus, +}); + +// Enable the find controller. +const pdfFindController = new PDFFindController({ + eventBus, + linkService: pdfLinkService, +}); + +// Create the PDF viewer. +const pdfViewer = new PDFViewer({ + container, + eventBus, + linkService: pdfLinkService, + findController: pdfFindController, +}); +pdfLinkService.setViewer(pdfViewer); + +// Allow navigation to a citation from the URL hash. +eventBus.on('pagesinit', function () { + pdfLinkService.setHash(window.location.hash.substring(1)); +}); + +// Define how the "search" query parameter is handled. +eventBus.on('findfromurlhash', function(evt) { + eventBus.dispatch('find', { + source: evt.source, + type: '', + query: evt.query, + caseSensitive: false, + entireWord: false, + highlightAll: false, + findPrevious: false, + matchDiacritics: true, + }); +}); + +// Load and initialize the document. +const pdfDocument = await pdfjsLib.getDocument({ + url: fileUrl, + enableXfa: true, +}).promise; + +pdfViewer.setDocument(pdfDocument); +pdfLinkService.setDocument(pdfDocument, null); diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_add.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_add.svg deleted file mode 100644 index 3451b536ce7..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_add.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_disclaimer.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_disclaimer.svg deleted file mode 100644 index 6fe79e710c8..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_disclaimer.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_done.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_done.svg deleted file mode 100644 index f54924ebf92..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_done.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_spinner.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_spinner.svg deleted file mode 100644 index fedb4724f7e..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_spinner.svg +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_warning.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_warning.svg deleted file mode 100644 index 03014ceab25..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/altText_warning.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-check.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-check.svg deleted file mode 100644 index 71cd16df576..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-check.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-comment.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-comment.svg deleted file mode 100644 index 86f1f17249f..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-comment.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-help.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-help.svg deleted file mode 100644 index 00938fefe04..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-help.svg +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-insert.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-insert.svg deleted file mode 100644 index 519ef6826e5..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-insert.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-key.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-key.svg deleted file mode 100644 index 8d09d5378d5..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-key.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-newparagraph.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-newparagraph.svg deleted file mode 100644 index 38d2497da91..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-newparagraph.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-noicon.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-noicon.svg deleted file mode 100644 index c07d1080832..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-noicon.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-note.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-note.svg deleted file mode 100644 index 70173651c7e..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-note.svg +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-paperclip.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-paperclip.svg deleted file mode 100644 index 2bed2250aee..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-paperclip.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-paragraph.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-paragraph.svg deleted file mode 100644 index 6ae5212b75d..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-paragraph.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-pushpin.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-pushpin.svg deleted file mode 100644 index 6e0896cf4ac..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/annotation-pushpin.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorFreeHighlight.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorFreeHighlight.svg deleted file mode 100644 index 513f6bdfdaa..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorFreeHighlight.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorFreeText.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorFreeText.svg deleted file mode 100644 index de2838ef102..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorFreeText.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorInk.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorInk.svg deleted file mode 100644 index 1dadb5c0155..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorInk.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorTextHighlight.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorTextHighlight.svg deleted file mode 100644 index 800340cb5b1..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/cursor-editorTextHighlight.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/editor-toolbar-delete.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/editor-toolbar-delete.svg deleted file mode 100644 index f84520d85a3..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/editor-toolbar-delete.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/findbarButton-next.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/findbarButton-next.svg deleted file mode 100644 index 8cb39bec6f1..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/findbarButton-next.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/findbarButton-previous.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/findbarButton-previous.svg deleted file mode 100644 index b610879dafc..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/findbarButton-previous.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/gv-toolbarButton-download.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/gv-toolbarButton-download.svg deleted file mode 100644 index d56cf3ce70e..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/gv-toolbarButton-download.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/loading.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/loading.svg deleted file mode 100644 index 0a15ff6885d..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/loading.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/messageBar_closingButton.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/messageBar_closingButton.svg deleted file mode 100644 index 8a40715ded3..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/messageBar_closingButton.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/messageBar_warning.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/messageBar_warning.svg deleted file mode 100644 index 011cfcf3e14..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/messageBar_warning.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-documentProperties.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-documentProperties.svg deleted file mode 100644 index dd3917b91d9..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-documentProperties.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-firstPage.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-firstPage.svg deleted file mode 100644 index f5c917f12a6..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-firstPage.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-handTool.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-handTool.svg deleted file mode 100644 index b7073b59895..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-handTool.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-lastPage.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-lastPage.svg deleted file mode 100644 index c04f65079c5..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-lastPage.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-rotateCcw.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-rotateCcw.svg deleted file mode 100644 index da73a1b16be..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-rotateCcw.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-rotateCw.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-rotateCw.svg deleted file mode 100644 index c41ce7365eb..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-rotateCw.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollHorizontal.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollHorizontal.svg deleted file mode 100644 index fb440b94653..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollHorizontal.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollPage.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollPage.svg deleted file mode 100644 index 64a9f500732..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollPage.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollVertical.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollVertical.svg deleted file mode 100644 index dc7e8052007..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollVertical.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollWrapped.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollWrapped.svg deleted file mode 100644 index 75fe26bcfcc..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-scrollWrapped.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-selectTool.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-selectTool.svg deleted file mode 100644 index 94d51410dd4..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-selectTool.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-spreadEven.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-spreadEven.svg deleted file mode 100644 index ce201e33c0a..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-spreadEven.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-spreadNone.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-spreadNone.svg deleted file mode 100644 index e8d487fa389..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-spreadNone.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-spreadOdd.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-spreadOdd.svg deleted file mode 100644 index 9211a427bfe..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/secondaryToolbarButton-spreadOdd.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-bookmark.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-bookmark.svg deleted file mode 100644 index c4c37c90582..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-bookmark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-currentOutlineItem.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-currentOutlineItem.svg deleted file mode 100644 index 01e67623bf2..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-currentOutlineItem.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-download.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-download.svg deleted file mode 100644 index e2e850adf73..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-download.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorFreeText.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorFreeText.svg deleted file mode 100644 index 13a67bd9b6a..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorFreeText.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorHighlight.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorHighlight.svg deleted file mode 100644 index b3cd7fda9c9..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorHighlight.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorInk.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorInk.svg deleted file mode 100644 index b579eec7ee5..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorInk.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorStamp.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorStamp.svg deleted file mode 100644 index a1fef4922d9..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-editorStamp.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-menuArrow.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-menuArrow.svg deleted file mode 100644 index 82ffeaabb9e..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-menuArrow.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-openFile.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-openFile.svg deleted file mode 100644 index e773781d607..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-openFile.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-pageDown.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-pageDown.svg deleted file mode 100644 index 1fc12e733d9..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-pageDown.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-pageUp.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-pageUp.svg deleted file mode 100644 index 0936b9a578f..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-pageUp.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-presentationMode.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-presentationMode.svg deleted file mode 100644 index 901d5672bcb..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-presentationMode.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-print.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-print.svg deleted file mode 100644 index 97a390474d9..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-print.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-search.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-search.svg deleted file mode 100644 index 0cc7ae21ac1..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-search.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-secondaryToolbarToggle.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-secondaryToolbarToggle.svg deleted file mode 100644 index cace863728a..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-secondaryToolbarToggle.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-sidebarToggle.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-sidebarToggle.svg deleted file mode 100644 index 1d8d0e4b23a..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-sidebarToggle.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewAttachments.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewAttachments.svg deleted file mode 100644 index ab73f6e6e07..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewAttachments.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewLayers.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewLayers.svg deleted file mode 100644 index 1d726682642..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewLayers.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewOutline.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewOutline.svg deleted file mode 100644 index 7ed1bd97f2f..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewOutline.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewThumbnail.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewThumbnail.svg deleted file mode 100644 index 040d123266a..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-viewThumbnail.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-zoomIn.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-zoomIn.svg deleted file mode 100644 index 30ec51a2ffd..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-zoomIn.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-zoomOut.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-zoomOut.svg deleted file mode 100644 index f273b5995cd..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/toolbarButton-zoomOut.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/treeitem-collapsed.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/treeitem-collapsed.svg deleted file mode 100644 index 831cddfc869..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/treeitem-collapsed.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/treeitem-expanded.svg b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/treeitem-expanded.svg deleted file mode 100644 index 2d45f0c8d18..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/images/treeitem-expanded.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.html b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.html deleted file mode 100644 index 5fc2634cae5..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.html +++ /dev/null @@ -1,637 +0,0 @@ - - - - - - - - PDF.js viewer - - - - - - - - - - - -
    - -
    -
    -
    -
    - - - - -
    -
    - -
    -
    -
    - - -
    -
    -
    -
    -
    -
    - - - -
    -
    -
    - -
    - -
    - -
    - -
    -
    - -
    -
    - - -
    -
    - -
    - File name: -

    -

    -
    -
    - File size: -

    -

    -
    -
    -
    - Title: -

    -

    -
    -
    - Author: -

    -

    -
    -
    - Subject: -

    -

    -
    -
    - Keywords: -

    -

    -
    -
    - Creation Date: -

    -

    -
    -
    - Modification Date: -

    -

    -
    -
    - Creator: -

    -

    -
    -
    -
    - PDF Producer: -

    -

    -
    -
    - PDF Version: -

    -

    -
    -
    - Page Count: -

    -

    -
    -
    - Page Size: -

    -

    -
    -
    -
    - Fast Web View: -

    -

    -
    -
    - -
    -
    - -
    -
    - Choose an option - - Alt text (alternative text) helps when people can’t see the image or when it doesn’t load. - -
    -
    -
    -
    - - -
    -
    - - Aim for 1-2 sentences that describe the subject, setting, or actions. - -
    -
    -
    - -
    -
    -
    -
    -
    - - -
    -
    - - This is used for ornamental images, like borders or watermarks. - -
    -
    -
    -
    - - -
    -
    -
    - -
    -
    - Edit alt text (image description) -
    -
    -
    -
    -
    - Couldn’t create alt text automatically - Please write your own alt text or try again later. -
    - -
    -
    -
    - - - -
    -
    - - - -
    -
    - Image alt text settings -
    -
    - Automatic alt text -
    -
    -
    - - -
    -
    - Suggests descriptions to help people who can’t see the image or when the image doesn’t load. Learn more -
    -
    -
    -
    - Alt text AI model (180MB) -
    - Runs locally on your device so your data stays private. Required for automatic alt text. -
    -
    - - -
    -
    -
    -
    -
    - Alt text editor -
    -
    - - -
    -
    - Helps you make sure all your images have alt text. -
    -
    -
    -
    - -
    -
    -
    - -
    - Preparing document for printing… -
    -
    - - 0% -
    -
    - -
    -
    -
    - - - -
    -
    - - diff --git a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.mjs.map b/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.mjs.map deleted file mode 100644 index 8534712ff8b..00000000000 --- a/src/ProjectTemplates/Microsoft.Extensions.AI.Templates/src/ChatWithCustomData/ChatWithCustomData.Web/wwwroot/pdfjs/web/viewer.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"viewer.mjs","mappings":";;;;;;;;;;;;;;;;;;;;;;SAAA;SACA;;;;;UCDA;UACA;UACA;UACA;UACA,yCAAyC,wCAAwC;UACjF;UACA;UACA;;;;;UCPA;;;;;;;;;;;;;;ACeA,MAAMA,mBAAmB,GAAG,MAAM;AAClC,MAAMC,aAAa,GAAG,GAAG;AACzB,MAAMC,mBAAmB,GAAG,GAAG;AAC/B,MAAMC,SAAS,GAAG,GAAG;AACrB,MAAMC,SAAS,GAAG,IAAI;AACtB,MAAMC,aAAa,GAAG,CAAC;AACvB,M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AK,UAAU,EAClC;EACAD,aAAa,CAAC,CAAC;AACjB,CAAC,MAAM;EACLxrF,QAAQ,CAACrI,gBAAgB,CAAC,kBAAkB,EAAE6zF,aAAa,EAAE,IAAI,CAAC;AACpE","sources":["webpack://pdf.js/webpack/bootstrap","webpack://pdf.js/webpack/runtime/define property getters","webpack://pdf.js/webpack/runtime/hasOwnProperty shorthand","webpack://pdf.js/./web/ui_utils.js","webpack://pdf.js/./web/app_options.js","webpack://pdf.js/./web/pdf_link_service.js","webpack://pdf.js/./web/pdfjs.js","webpack://pdf.js/./web/event_utils.js","webpack://pdf.js/./web/external_services.js","webpack://pdf.js/./web/preferences.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/types.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/resolver.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/scope.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/builtins.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/memoizer.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/bundle.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/resource.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/index.js","webpack://pdf.js/./node_modules/@fluent/dom/esm/overlay.js","webpack://pdf.js/./node_modules/cached-iterable/src/cached_iterable.mjs","webpack://pdf.js/./node_modules/cached-iterable/src/cached_sync_iterable.mjs","webpack://pdf.js/./node_modules/cached-iterable/src/cached_async_iterable.mjs","webpack://pdf.js/./node_modules/cached-iterable/src/index.mjs","webpack://pdf.js/./node_modules/@fluent/dom/esm/localization.js","webpack://pdf.js/./node_modules/@fluent/dom/esm/dom_localization.js","webpack://pdf.js/./node_modules/@fluent/dom/esm/index.js","webpack://pdf.js/./web/l10n.js","webpack://pdf.js/./web/genericl10n.js","webpack://pdf.js/./web/generic_scripting.js","webpack://pdf.js/./web/genericcom.js","webpack://pdf.js/./web/new_alt_text_manager.js","webpack://pdf.js/./web/alt_text_manager.js","webpack://pdf.js/./web/annotation_editor_params.js","webpack://pdf.js/./web/caret_browsing.js","webpack://pdf.js/./web/download_manager.js","webpack://pdf.js/./web/editor_undo_bar.js","webpack://pdf.js/./web/overlay_manager.js","webpack://pdf.js/./web/password_prompt.js","webpack://pdf.js/./web/base_tree_viewer.js","webpack://pdf.js/./web/pdf_attachment_viewer.js","webpack://pdf.js/./web/grab_to_pan.js","webpack://pdf.js/./web/pdf_cursor_tools.js","webpack://pdf.js/./web/pdf_document_properties.js","webpack://pdf.js/./web/pdf_find_utils.js","webpack://pdf.js/./web/pdf_find_controller.js","webpack://pdf.js/./web/pdf_find_bar.js","webpack://pdf.js/./web/pdf_history.js","webpack://pdf.js/./web/pdf_layer_viewer.js","webpack://pdf.js/./web/pdf_outline_viewer.js","webpack://pdf.js/./web/pdf_presentation_mode.js","webpack://pdf.js/./web/xfa_layer_builder.js","webpack://pdf.js/./web/print_utils.js","webpack://pdf.js/./web/pdf_print_service.js","webpack://pdf.js/./web/pdf_rendering_queue.js","webpack://pdf.js/./web/pdf_scripting_manager.js","webpack://pdf.js/./web/pdf_sidebar.js","webpack://pdf.js/./web/pdf_thumbnail_view.js","webpack://pdf.js/./web/pdf_thumbnail_viewer.js","webpack://pdf.js/./web/annotation_editor_layer_builder.js","webpack://pdf.js/./web/annotation_layer_builder.js","webpack://pdf.js/./web/draw_layer_builder.js","webpack://pdf.js/./web/struct_tree_layer_builder.js","webpack://pdf.js/./web/text_accessibility.js","webpack://pdf.js/./web/text_highlighter.js","webpack://pdf.js/./web/text_layer_builder.js","webpack://pdf.js/./web/pdf_page_view.js","webpack://pdf.js/./web/pdf_viewer.js","webpack://pdf.js/./web/secondary_toolbar.js","webpack://pdf.js/./web/toolbar.js","webpack://pdf.js/./web/view_history.js","webpack://pdf.js/./web/app.js","webpack://pdf.js/./web/viewer.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst DEFAULT_SCALE_VALUE = \"auto\";\nconst DEFAULT_SCALE = 1.0;\nconst DEFAULT_SCALE_DELTA = 1.1;\nconst MIN_SCALE = 0.1;\nconst MAX_SCALE = 10.0;\nconst UNKNOWN_SCALE = 0;\nconst MAX_AUTO_SCALE = 1.25;\nconst SCROLLBAR_PADDING = 40;\nconst VERTICAL_PADDING = 5;\n\nconst RenderingStates = {\n INITIAL: 0,\n RUNNING: 1,\n PAUSED: 2,\n FINISHED: 3,\n};\n\nconst PresentationModeState = {\n UNKNOWN: 0,\n NORMAL: 1,\n CHANGING: 2,\n FULLSCREEN: 3,\n};\n\nconst SidebarView = {\n UNKNOWN: -1,\n NONE: 0,\n THUMBS: 1, // Default value.\n OUTLINE: 2,\n ATTACHMENTS: 3,\n LAYERS: 4,\n};\n\nconst TextLayerMode = {\n DISABLE: 0,\n ENABLE: 1,\n ENABLE_PERMISSIONS: 2,\n};\n\nconst ScrollMode = {\n UNKNOWN: -1,\n VERTICAL: 0, // Default value.\n HORIZONTAL: 1,\n WRAPPED: 2,\n PAGE: 3,\n};\n\nconst SpreadMode = {\n UNKNOWN: -1,\n NONE: 0, // Default value.\n ODD: 1,\n EVEN: 2,\n};\n\nconst CursorTool = {\n SELECT: 0, // The default value.\n HAND: 1,\n ZOOM: 2,\n};\n\n// Used by `PDFViewerApplication`, and by the API unit-tests.\nconst AutoPrintRegExp = /\\bprint\\s*\\(/;\n\n/**\n * Scrolls specified element into view of its parent.\n * @param {HTMLElement} element - The element to be visible.\n * @param {Object} [spot] - An object with optional top and left properties,\n * specifying the offset from the top left edge.\n * @param {number} [spot.left]\n * @param {number} [spot.top]\n * @param {boolean} [scrollMatches] - When scrolling search results into view,\n * ignore elements that either: Contains marked content identifiers,\n * or have the CSS-rule `overflow: hidden;` set. The default value is `false`.\n */\nfunction scrollIntoView(element, spot, scrollMatches = false) {\n // Assuming offsetParent is available (it's not available when viewer is in\n // hidden iframe or object). We have to scroll: if the offsetParent is not set\n // producing the error. See also animationStarted.\n let parent = element.offsetParent;\n if (!parent) {\n console.error(\"offsetParent is not set -- cannot scroll\");\n return;\n }\n let offsetY = element.offsetTop + element.clientTop;\n let offsetX = element.offsetLeft + element.clientLeft;\n while (\n (parent.clientHeight === parent.scrollHeight &&\n parent.clientWidth === parent.scrollWidth) ||\n (scrollMatches &&\n (parent.classList.contains(\"markedContent\") ||\n getComputedStyle(parent).overflow === \"hidden\"))\n ) {\n offsetY += parent.offsetTop;\n offsetX += parent.offsetLeft;\n\n parent = parent.offsetParent;\n if (!parent) {\n return; // no need to scroll\n }\n }\n if (spot) {\n if (spot.top !== undefined) {\n offsetY += spot.top;\n }\n if (spot.left !== undefined) {\n offsetX += spot.left;\n parent.scrollLeft = offsetX;\n }\n }\n parent.scrollTop = offsetY;\n}\n\n/**\n * Helper function to start monitoring the scroll event and converting them into\n * PDF.js friendly one: with scroll debounce and scroll direction.\n */\nfunction watchScroll(viewAreaElement, callback, abortSignal = undefined) {\n const debounceScroll = function (evt) {\n if (rAF) {\n return;\n }\n // schedule an invocation of scroll for next animation frame.\n rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {\n rAF = null;\n\n const currentX = viewAreaElement.scrollLeft;\n const lastX = state.lastX;\n if (currentX !== lastX) {\n state.right = currentX > lastX;\n }\n state.lastX = currentX;\n const currentY = viewAreaElement.scrollTop;\n const lastY = state.lastY;\n if (currentY !== lastY) {\n state.down = currentY > lastY;\n }\n state.lastY = currentY;\n callback(state);\n });\n };\n\n const state = {\n right: true,\n down: true,\n lastX: viewAreaElement.scrollLeft,\n lastY: viewAreaElement.scrollTop,\n _eventHandler: debounceScroll,\n };\n\n let rAF = null;\n viewAreaElement.addEventListener(\"scroll\", debounceScroll, {\n useCapture: true,\n signal: abortSignal,\n });\n abortSignal?.addEventListener(\n \"abort\",\n () => window.cancelAnimationFrame(rAF),\n { once: true }\n );\n return state;\n}\n\n/**\n * Helper function to parse query string (e.g. ?param1=value¶m2=...).\n * @param {string} query\n * @returns {Map}\n */\nfunction parseQueryString(query) {\n const params = new Map();\n for (const [key, value] of new URLSearchParams(query)) {\n params.set(key.toLowerCase(), value);\n }\n return params;\n}\n\nconst InvisibleCharsRegExp = /[\\x00-\\x1F]/g;\n\n/**\n * @param {string} str\n * @param {boolean} [replaceInvisible]\n */\nfunction removeNullCharacters(str, replaceInvisible = false) {\n if (!InvisibleCharsRegExp.test(str)) {\n return str;\n }\n if (replaceInvisible) {\n return str.replaceAll(InvisibleCharsRegExp, m => (m === \"\\x00\" ? \"\" : \" \"));\n }\n return str.replaceAll(\"\\x00\", \"\");\n}\n\n/**\n * Use binary search to find the index of the first item in a given array which\n * passes a given condition. The items are expected to be sorted in the sense\n * that if the condition is true for one item in the array, then it is also true\n * for all following items.\n *\n * @returns {number} Index of the first array element to pass the test,\n * or |items.length| if no such element exists.\n */\nfunction binarySearchFirstItem(items, condition, start = 0) {\n let minIndex = start;\n let maxIndex = items.length - 1;\n\n if (maxIndex < 0 || !condition(items[maxIndex])) {\n return items.length;\n }\n if (condition(items[minIndex])) {\n return minIndex;\n }\n\n while (minIndex < maxIndex) {\n const currentIndex = (minIndex + maxIndex) >> 1;\n const currentItem = items[currentIndex];\n if (condition(currentItem)) {\n maxIndex = currentIndex;\n } else {\n minIndex = currentIndex + 1;\n }\n }\n return minIndex; /* === maxIndex */\n}\n\n/**\n * Approximates float number as a fraction using Farey sequence (max order\n * of 8).\n * @param {number} x - Positive float number.\n * @returns {Array} Estimated fraction: the first array item is a numerator,\n * the second one is a denominator.\n * They are both natural numbers.\n */\nfunction approximateFraction(x) {\n // Fast paths for int numbers or their inversions.\n if (Math.floor(x) === x) {\n return [x, 1];\n }\n const xinv = 1 / x;\n const limit = 8;\n if (xinv > limit) {\n return [1, limit];\n } else if (Math.floor(xinv) === xinv) {\n return [1, xinv];\n }\n\n const x_ = x > 1 ? xinv : x;\n // a/b and c/d are neighbours in Farey sequence.\n let a = 0,\n b = 1,\n c = 1,\n d = 1;\n // Limiting search to order 8.\n while (true) {\n // Generating next term in sequence (order of q).\n const p = a + c,\n q = b + d;\n if (q > limit) {\n break;\n }\n if (x_ <= p / q) {\n c = p;\n d = q;\n } else {\n a = p;\n b = q;\n }\n }\n let result;\n // Select closest of the neighbours to x.\n if (x_ - a / b < c / d - x_) {\n result = x_ === x ? [a, b] : [b, a];\n } else {\n result = x_ === x ? [c, d] : [d, c];\n }\n return result;\n}\n\n/**\n * @param {number} x - A positive number to round to a multiple of `div`.\n * @param {number} div - A natural number.\n */\nfunction floorToDivide(x, div) {\n return x - (x % div);\n}\n\n/**\n * @typedef {Object} GetPageSizeInchesParameters\n * @property {number[]} view\n * @property {number} userUnit\n * @property {number} rotate\n */\n\n/**\n * @typedef {Object} PageSize\n * @property {number} width - In inches.\n * @property {number} height - In inches.\n */\n\n/**\n * Gets the size of the specified page, converted from PDF units to inches.\n * @param {GetPageSizeInchesParameters} params\n * @returns {PageSize}\n */\nfunction getPageSizeInches({ view, userUnit, rotate }) {\n const [x1, y1, x2, y2] = view;\n // We need to take the page rotation into account as well.\n const changeOrientation = rotate % 180 !== 0;\n\n const width = ((x2 - x1) / 72) * userUnit;\n const height = ((y2 - y1) / 72) * userUnit;\n\n return {\n width: changeOrientation ? height : width,\n height: changeOrientation ? width : height,\n };\n}\n\n/**\n * Helper function for getVisibleElements.\n *\n * @param {number} index - initial guess at the first visible element\n * @param {Array} views - array of pages, into which `index` is an index\n * @param {number} top - the top of the scroll pane\n * @returns {number} less than or equal to `index` that is definitely at or\n * before the first visible element in `views`, but not by too much. (Usually,\n * this will be the first element in the first partially visible row in\n * `views`, although sometimes it goes back one row further.)\n */\nfunction backtrackBeforeAllVisibleElements(index, views, top) {\n // binarySearchFirstItem's assumption is that the input is ordered, with only\n // one index where the conditions flips from false to true: [false ...,\n // true...]. With vertical scrolling and spreads, it is possible to have\n // [false ..., true, false, true ...]. With wrapped scrolling we can have a\n // similar sequence, with many more mixed true and false in the middle.\n //\n // So there is no guarantee that the binary search yields the index of the\n // first visible element. It could have been any of the other visible elements\n // that were preceded by a hidden element.\n\n // Of course, if either this element or the previous (hidden) element is also\n // the first element, there's nothing to worry about.\n if (index < 2) {\n return index;\n }\n\n // That aside, the possible cases are represented below.\n //\n // **** = fully hidden\n // A*B* = mix of partially visible and/or hidden pages\n // CDEF = fully visible\n //\n // (1) Binary search could have returned A, in which case we can stop.\n // (2) Binary search could also have returned B, in which case we need to\n // check the whole row.\n // (3) Binary search could also have returned C, in which case we need to\n // check the whole previous row.\n //\n // There's one other possibility:\n //\n // **** = fully hidden\n // ABCD = mix of fully and/or partially visible pages\n //\n // (4) Binary search could only have returned A.\n\n // Initially assume that we need to find the beginning of the current row\n // (case 1, 2, or 4), which means finding a page that is above the current\n // page's top. If the found page is partially visible, we're definitely not in\n // case 3, and this assumption is correct.\n let elt = views[index].div;\n let pageTop = elt.offsetTop + elt.clientTop;\n\n if (pageTop >= top) {\n // The found page is fully visible, so we're actually either in case 3 or 4,\n // and unfortunately we can't tell the difference between them without\n // scanning the entire previous row, so we just conservatively assume that\n // we do need to backtrack to that row. In both cases, the previous page is\n // in the previous row, so use its top instead.\n elt = views[index - 1].div;\n pageTop = elt.offsetTop + elt.clientTop;\n }\n\n // Now we backtrack to the first page that still has its bottom below\n // `pageTop`, which is the top of a page in the first visible row (unless\n // we're in case 4, in which case it's the row before that).\n // `index` is found by binary search, so the page at `index - 1` is\n // invisible and we can start looking for potentially visible pages from\n // `index - 2`. (However, if this loop terminates on its first iteration,\n // which is the case when pages are stacked vertically, `index` should remain\n // unchanged, so we use a distinct loop variable.)\n for (let i = index - 2; i >= 0; --i) {\n elt = views[i].div;\n if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) {\n // We have reached the previous row, so stop now.\n // This loop is expected to terminate relatively quickly because the\n // number of pages per row is expected to be small.\n break;\n }\n index = i;\n }\n return index;\n}\n\n/**\n * @typedef {Object} GetVisibleElementsParameters\n * @property {HTMLElement} scrollEl - A container that can possibly scroll.\n * @property {Array} views - Objects with a `div` property that contains an\n * HTMLElement, which should all be descendants of `scrollEl` satisfying the\n * relevant layout assumptions.\n * @property {boolean} sortByVisibility - If `true`, the returned elements are\n * sorted in descending order of the percent of their padding box that is\n * visible. The default value is `false`.\n * @property {boolean} horizontal - If `true`, the elements are assumed to be\n * laid out horizontally instead of vertically. The default value is `false`.\n * @property {boolean} rtl - If `true`, the `scrollEl` container is assumed to\n * be in right-to-left mode. The default value is `false`.\n */\n\n/**\n * Generic helper to find out what elements are visible within a scroll pane.\n *\n * Well, pretty generic. There are some assumptions placed on the elements\n * referenced by `views`:\n * - If `horizontal`, no left of any earlier element is to the right of the\n * left of any later element.\n * - Otherwise, `views` can be split into contiguous rows where, within a row,\n * no top of any element is below the bottom of any other element, and\n * between rows, no bottom of any element in an earlier row is below the\n * top of any element in a later row.\n *\n * (Here, top, left, etc. all refer to the padding edge of the element in\n * question. For pages, that ends up being equivalent to the bounding box of the\n * rendering canvas. Earlier and later refer to index in `views`, not page\n * layout.)\n *\n * @param {GetVisibleElementsParameters} params\n * @returns {Object} `{ first, last, views: [{ id, x, y, view, percent }] }`\n */\nfunction getVisibleElements({\n scrollEl,\n views,\n sortByVisibility = false,\n horizontal = false,\n rtl = false,\n}) {\n const top = scrollEl.scrollTop,\n bottom = top + scrollEl.clientHeight;\n const left = scrollEl.scrollLeft,\n right = left + scrollEl.clientWidth;\n\n // Throughout this \"generic\" function, comments will assume we're working with\n // PDF document pages, which is the most important and complex case. In this\n // case, the visible elements we're actually interested is the page canvas,\n // which is contained in a wrapper which adds no padding/border/margin, which\n // is itself contained in `view.div` which adds no padding (but does add a\n // border). So, as specified in this function's doc comment, this function\n // does all of its work on the padding edge of the provided views, starting at\n // offsetLeft/Top (which includes margin) and adding clientLeft/Top (which is\n // the border). Adding clientWidth/Height gets us the bottom-right corner of\n // the padding edge.\n function isElementBottomAfterViewTop(view) {\n const element = view.div;\n const elementBottom =\n element.offsetTop + element.clientTop + element.clientHeight;\n return elementBottom > top;\n }\n function isElementNextAfterViewHorizontally(view) {\n const element = view.div;\n const elementLeft = element.offsetLeft + element.clientLeft;\n const elementRight = elementLeft + element.clientWidth;\n return rtl ? elementLeft < right : elementRight > left;\n }\n\n const visible = [],\n ids = new Set(),\n numViews = views.length;\n let firstVisibleElementInd = binarySearchFirstItem(\n views,\n horizontal\n ? isElementNextAfterViewHorizontally\n : isElementBottomAfterViewTop\n );\n\n // Please note the return value of the `binarySearchFirstItem` function when\n // no valid element is found (hence the `firstVisibleElementInd` check below).\n if (\n firstVisibleElementInd > 0 &&\n firstVisibleElementInd < numViews &&\n !horizontal\n ) {\n // In wrapped scrolling (or vertical scrolling with spreads), with some page\n // sizes, isElementBottomAfterViewTop doesn't satisfy the binary search\n // condition: there can be pages with bottoms above the view top between\n // pages with bottoms below. This function detects and corrects that error;\n // see it for more comments.\n firstVisibleElementInd = backtrackBeforeAllVisibleElements(\n firstVisibleElementInd,\n views,\n top\n );\n }\n\n // lastEdge acts as a cutoff for us to stop looping, because we know all\n // subsequent pages will be hidden.\n //\n // When using wrapped scrolling or vertical scrolling with spreads, we can't\n // simply stop the first time we reach a page below the bottom of the view;\n // the tops of subsequent pages on the same row could still be visible. In\n // horizontal scrolling, we don't have that issue, so we can stop as soon as\n // we pass `right`, without needing the code below that handles the -1 case.\n let lastEdge = horizontal ? right : -1;\n\n for (let i = firstVisibleElementInd; i < numViews; i++) {\n const view = views[i],\n element = view.div;\n const currentWidth = element.offsetLeft + element.clientLeft;\n const currentHeight = element.offsetTop + element.clientTop;\n const viewWidth = element.clientWidth,\n viewHeight = element.clientHeight;\n const viewRight = currentWidth + viewWidth;\n const viewBottom = currentHeight + viewHeight;\n\n if (lastEdge === -1) {\n // As commented above, this is only needed in non-horizontal cases.\n // Setting lastEdge to the bottom of the first page that is partially\n // visible ensures that the next page fully below lastEdge is on the\n // next row, which has to be fully hidden along with all subsequent rows.\n if (viewBottom >= bottom) {\n lastEdge = viewBottom;\n }\n } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) {\n break;\n }\n\n if (\n viewBottom <= top ||\n currentHeight >= bottom ||\n viewRight <= left ||\n currentWidth >= right\n ) {\n continue;\n }\n\n const hiddenHeight =\n Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom);\n const hiddenWidth =\n Math.max(0, left - currentWidth) + Math.max(0, viewRight - right);\n\n const fractionHeight = (viewHeight - hiddenHeight) / viewHeight,\n fractionWidth = (viewWidth - hiddenWidth) / viewWidth;\n const percent = (fractionHeight * fractionWidth * 100) | 0;\n\n visible.push({\n id: view.id,\n x: currentWidth,\n y: currentHeight,\n view,\n percent,\n widthPercent: (fractionWidth * 100) | 0,\n });\n ids.add(view.id);\n }\n\n const first = visible[0],\n last = visible.at(-1);\n\n if (sortByVisibility) {\n visible.sort(function (a, b) {\n const pc = a.percent - b.percent;\n if (Math.abs(pc) > 0.001) {\n return -pc;\n }\n return a.id - b.id; // ensure stability\n });\n }\n return { first, last, views: visible, ids };\n}\n\nfunction normalizeWheelEventDirection(evt) {\n let delta = Math.hypot(evt.deltaX, evt.deltaY);\n const angle = Math.atan2(evt.deltaY, evt.deltaX);\n if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {\n // All that is left-up oriented has to change the sign.\n delta = -delta;\n }\n return delta;\n}\n\nfunction normalizeWheelEventDelta(evt) {\n const deltaMode = evt.deltaMode; // Avoid being affected by bug 1392460.\n let delta = normalizeWheelEventDirection(evt);\n\n const MOUSE_PIXELS_PER_LINE = 30;\n const MOUSE_LINES_PER_PAGE = 30;\n\n // Converts delta to per-page units\n if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) {\n delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;\n } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) {\n delta /= MOUSE_LINES_PER_PAGE;\n }\n return delta;\n}\n\nfunction isValidRotation(angle) {\n return Number.isInteger(angle) && angle % 90 === 0;\n}\n\nfunction isValidScrollMode(mode) {\n return (\n Number.isInteger(mode) &&\n Object.values(ScrollMode).includes(mode) &&\n mode !== ScrollMode.UNKNOWN\n );\n}\n\nfunction isValidSpreadMode(mode) {\n return (\n Number.isInteger(mode) &&\n Object.values(SpreadMode).includes(mode) &&\n mode !== SpreadMode.UNKNOWN\n );\n}\n\nfunction isPortraitOrientation(size) {\n return size.width <= size.height;\n}\n\n/**\n * Promise that is resolved when DOM window becomes visible.\n */\nconst animationStarted = new Promise(function (resolve) {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof window === \"undefined\"\n ) {\n // Prevent \"ReferenceError: window is not defined\" errors when running the\n // unit-tests in Node.js environments.\n setTimeout(resolve, 20);\n return;\n }\n window.requestAnimationFrame(resolve);\n});\n\nconst docStyle =\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof document === \"undefined\"\n ? null\n : document.documentElement.style;\n\nfunction clamp(v, min, max) {\n return Math.min(Math.max(v, min), max);\n}\n\nclass ProgressBar {\n #classList = null;\n\n #disableAutoFetchTimeout = null;\n\n #percent = 0;\n\n #style = null;\n\n #visible = true;\n\n constructor(bar) {\n this.#classList = bar.classList;\n this.#style = bar.style;\n }\n\n get percent() {\n return this.#percent;\n }\n\n set percent(val) {\n this.#percent = clamp(val, 0, 100);\n\n if (isNaN(val)) {\n this.#classList.add(\"indeterminate\");\n return;\n }\n this.#classList.remove(\"indeterminate\");\n\n this.#style.setProperty(\"--progressBar-percent\", `${this.#percent}%`);\n }\n\n setWidth(viewer) {\n if (!viewer) {\n return;\n }\n const container = viewer.parentNode;\n const scrollbarWidth = container.offsetWidth - viewer.offsetWidth;\n if (scrollbarWidth > 0) {\n this.#style.setProperty(\n \"--progressBar-end-offset\",\n `${scrollbarWidth}px`\n );\n }\n }\n\n setDisableAutoFetch(delay = /* ms = */ 5000) {\n if (this.#percent === 100 || isNaN(this.#percent)) {\n return;\n }\n if (this.#disableAutoFetchTimeout) {\n clearTimeout(this.#disableAutoFetchTimeout);\n }\n this.show();\n\n this.#disableAutoFetchTimeout = setTimeout(() => {\n this.#disableAutoFetchTimeout = null;\n this.hide();\n }, delay);\n }\n\n hide() {\n if (!this.#visible) {\n return;\n }\n this.#visible = false;\n this.#classList.add(\"hidden\");\n }\n\n show() {\n if (this.#visible) {\n return;\n }\n this.#visible = true;\n this.#classList.remove(\"hidden\");\n }\n}\n\n/**\n * Get the active or focused element in current DOM.\n *\n * Recursively search for the truly active or focused element in case there are\n * shadow DOMs.\n *\n * @returns {Element} the truly active or focused element.\n */\nfunction getActiveOrFocusedElement() {\n let curRoot = document;\n let curActiveOrFocused =\n curRoot.activeElement || curRoot.querySelector(\":focus\");\n\n while (curActiveOrFocused?.shadowRoot) {\n curRoot = curActiveOrFocused.shadowRoot;\n curActiveOrFocused =\n curRoot.activeElement || curRoot.querySelector(\":focus\");\n }\n\n return curActiveOrFocused;\n}\n\n/**\n * Converts API PageLayout values to the format used by `BaseViewer`.\n * @param {string} layout - The API PageLayout value.\n * @returns {Object}\n */\nfunction apiPageLayoutToViewerModes(layout) {\n let scrollMode = ScrollMode.VERTICAL,\n spreadMode = SpreadMode.NONE;\n\n switch (layout) {\n case \"SinglePage\":\n scrollMode = ScrollMode.PAGE;\n break;\n case \"OneColumn\":\n break;\n case \"TwoPageLeft\":\n scrollMode = ScrollMode.PAGE;\n /* falls through */\n case \"TwoColumnLeft\":\n spreadMode = SpreadMode.ODD;\n break;\n case \"TwoPageRight\":\n scrollMode = ScrollMode.PAGE;\n /* falls through */\n case \"TwoColumnRight\":\n spreadMode = SpreadMode.EVEN;\n break;\n }\n return { scrollMode, spreadMode };\n}\n\n/**\n * Converts API PageMode values to the format used by `PDFSidebar`.\n * NOTE: There's also a \"FullScreen\" parameter which is not possible to support,\n * since the Fullscreen API used in browsers requires that entering\n * fullscreen mode only occurs as a result of a user-initiated event.\n * @param {string} mode - The API PageMode value.\n * @returns {number} A value from {SidebarView}.\n */\nfunction apiPageModeToSidebarView(mode) {\n switch (mode) {\n case \"UseNone\":\n return SidebarView.NONE;\n case \"UseThumbs\":\n return SidebarView.THUMBS;\n case \"UseOutlines\":\n return SidebarView.OUTLINE;\n case \"UseAttachments\":\n return SidebarView.ATTACHMENTS;\n case \"UseOC\":\n return SidebarView.LAYERS;\n }\n return SidebarView.NONE; // Default value.\n}\n\nfunction toggleCheckedBtn(button, toggle, view = null) {\n button.classList.toggle(\"toggled\", toggle);\n button.setAttribute(\"aria-checked\", toggle);\n\n view?.classList.toggle(\"hidden\", !toggle);\n}\n\nfunction toggleExpandedBtn(button, toggle, view = null) {\n button.classList.toggle(\"toggled\", toggle);\n button.setAttribute(\"aria-expanded\", toggle);\n\n view?.classList.toggle(\"hidden\", !toggle);\n}\n\n// In Firefox, the css calc function uses f32 precision but the Chrome or Safari\n// are using f64 one. So in order to have the same rendering in all browsers, we\n// need to use the right precision in order to have correct dimensions.\nconst calcRound =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")\n ? Math.fround\n : (function () {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof document === \"undefined\"\n ) {\n return x => x;\n }\n const e = document.createElement(\"div\");\n e.style.width = \"round(down, calc(1.6666666666666665 * 792px), 1px)\";\n return e.style.width === \"calc(1320px)\" ? Math.fround : x => x;\n })();\n\nexport {\n animationStarted,\n apiPageLayoutToViewerModes,\n apiPageModeToSidebarView,\n approximateFraction,\n AutoPrintRegExp,\n backtrackBeforeAllVisibleElements, // only exported for testing\n binarySearchFirstItem,\n calcRound,\n CursorTool,\n DEFAULT_SCALE,\n DEFAULT_SCALE_DELTA,\n DEFAULT_SCALE_VALUE,\n docStyle,\n floorToDivide,\n getActiveOrFocusedElement,\n getPageSizeInches,\n getVisibleElements,\n isPortraitOrientation,\n isValidRotation,\n isValidScrollMode,\n isValidSpreadMode,\n MAX_AUTO_SCALE,\n MAX_SCALE,\n MIN_SCALE,\n normalizeWheelEventDelta,\n normalizeWheelEventDirection,\n parseQueryString,\n PresentationModeState,\n ProgressBar,\n removeNullCharacters,\n RenderingStates,\n SCROLLBAR_PADDING,\n scrollIntoView,\n ScrollMode,\n SidebarView,\n SpreadMode,\n TextLayerMode,\n toggleCheckedBtn,\n toggleExpandedBtn,\n UNKNOWN_SCALE,\n VERTICAL_PADDING,\n watchScroll,\n};\n","/* Copyright 2018 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nif (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n // eslint-disable-next-line no-var\n var compatParams = new Map();\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof navigator === \"undefined\"\n ) {\n globalThis.navigator = Object.create(null);\n }\n const userAgent = navigator.userAgent || \"\";\n const platform = navigator.platform || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 1;\n\n const isAndroid = /Android/.test(userAgent);\n const isIOS =\n /\\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) ||\n (platform === \"MacIntel\" && maxTouchPoints > 1);\n\n // Limit canvas size to 5 mega-pixels on mobile.\n // Support: Android, iOS\n (function () {\n if (isIOS || isAndroid) {\n compatParams.set(\"maxCanvasPixels\", 5242880);\n }\n })();\n\n // Don't use system fonts on Android (issue 18210).\n // Support: Android\n (function () {\n if (isAndroid) {\n compatParams.set(\"useSystemFonts\", false);\n }\n })();\n}\n\nconst OptionKind = {\n BROWSER: 0x01,\n VIEWER: 0x02,\n API: 0x04,\n WORKER: 0x08,\n EVENT_DISPATCH: 0x10,\n PREFERENCE: 0x80,\n};\n\n// Should only be used with options that allow multiple types.\nconst Type = {\n BOOLEAN: 0x01,\n NUMBER: 0x02,\n OBJECT: 0x04,\n STRING: 0x08,\n UNDEFINED: 0x10,\n};\n\n/**\n * NOTE: These options are used to generate the `default_preferences.json` file,\n * see `OptionKind.PREFERENCE`, hence the values below must use only\n * primitive types and cannot rely on any imported types.\n */\nconst defaultOptions = {\n allowedGlobalEvents: {\n /** @type {Object} */\n value: null,\n kind: OptionKind.BROWSER,\n },\n canvasMaxAreaInBytes: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.BROWSER + OptionKind.API,\n },\n isInAutomation: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.BROWSER,\n },\n localeProperties: {\n /** @type {Object} */\n value:\n typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")\n ? { lang: navigator.language || \"en-US\" }\n : null,\n kind: OptionKind.BROWSER,\n },\n nimbusDataStr: {\n /** @type {string} */\n value: \"\",\n kind: OptionKind.BROWSER,\n },\n supportsCaretBrowsingMode: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.BROWSER,\n },\n supportsDocumentFonts: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.BROWSER,\n },\n supportsIntegratedFind: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.BROWSER,\n },\n supportsMouseWheelZoomCtrlKey: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.BROWSER,\n },\n supportsMouseWheelZoomMetaKey: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.BROWSER,\n },\n supportsPinchToZoom: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.BROWSER,\n },\n toolbarDensity: {\n /** @type {number} */\n value: 0, // 0 = \"normal\", 1 = \"compact\", 2 = \"touch\"\n kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH,\n },\n\n altTextLearnMoreUrl: {\n /** @type {string} */\n value:\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")\n ? \"https://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/pdf-alt-text\"\n : \"\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n annotationEditorMode: {\n /** @type {number} */\n value: 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n annotationMode: {\n /** @type {number} */\n value: 2,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n cursorToolOnLoad: {\n /** @type {number} */\n value: 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n debuggerSrc: {\n /** @type {string} */\n value: \"./debugger.mjs\",\n kind: OptionKind.VIEWER,\n },\n defaultZoomDelay: {\n /** @type {number} */\n value: 400,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n defaultZoomValue: {\n /** @type {string} */\n value: \"\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n disableHistory: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER,\n },\n disablePageLabels: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableAltText: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableAltTextModelDownload: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH,\n },\n enableGuessAltText: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH,\n },\n enableHighlightFloatingButton: {\n // We'll probably want to make some experiments before enabling this\n // in Firefox release, but it has to be temporary.\n // TODO: remove it when unnecessary.\n /** @type {boolean} */\n value: typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\"),\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableNewAltTextWhenAddingImage: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enablePermissions: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enablePrintAutoRotate: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableScripting: {\n /** @type {boolean} */\n value: typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"CHROME\"),\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableUpdatedAddImage: {\n // We'll probably want to make some experiments before enabling this\n // in Firefox release, but it has to be temporary.\n // TODO: remove it when unnecessary.\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n externalLinkRel: {\n /** @type {string} */\n value: \"noopener noreferrer nofollow\",\n kind: OptionKind.VIEWER,\n },\n externalLinkTarget: {\n /** @type {number} */\n value: 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n highlightEditorColors: {\n /** @type {string} */\n value: \"yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n historyUpdateUrl: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n ignoreDestinationZoom: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n imageResourcesPath: {\n /** @type {string} */\n value:\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")\n ? \"resource://pdf.js/web/images/\"\n : \"./images/\",\n kind: OptionKind.VIEWER,\n },\n maxCanvasPixels: {\n /** @type {number} */\n value: 2 ** 25,\n kind: OptionKind.VIEWER,\n },\n forcePageColors: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n pageColorsBackground: {\n /** @type {string} */\n value: \"Canvas\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n pageColorsForeground: {\n /** @type {string} */\n value: \"CanvasText\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n pdfBugEnabled: {\n /** @type {boolean} */\n value: typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\"),\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n printResolution: {\n /** @type {number} */\n value: 150,\n kind: OptionKind.VIEWER,\n },\n sidebarViewOnLoad: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n scrollModeOnLoad: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n spreadModeOnLoad: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n textLayerMode: {\n /** @type {number} */\n value: 1,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n viewOnLoad: {\n /** @type {boolean} */\n value: 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n\n cMapPacked: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.API,\n },\n cMapUrl: {\n /** @type {string} */\n value:\n // eslint-disable-next-line no-nested-ternary\n typeof PDFJSDev === \"undefined\"\n ? \"../external/bcmaps/\"\n : PDFJSDev.test(\"MOZCENTRAL\")\n ? \"resource://pdf.js/web/cmaps/\"\n : \"../web/cmaps/\",\n kind: OptionKind.API,\n },\n disableAutoFetch: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n disableFontFace: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n disableRange: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n disableStream: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n docBaseUrl: {\n /** @type {string} */\n value: typeof PDFJSDev === \"undefined\" ? document.URL.split(\"#\", 1)[0] : \"\",\n kind: OptionKind.API,\n },\n enableHWA: {\n /** @type {boolean} */\n value: typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"MOZCENTRAL\"),\n kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableXfa: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n fontExtraProperties: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API,\n },\n isEvalSupported: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.API,\n },\n isOffscreenCanvasSupported: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.API,\n },\n maxImageSize: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.API,\n },\n pdfBug: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API,\n },\n standardFontDataUrl: {\n /** @type {string} */\n value:\n // eslint-disable-next-line no-nested-ternary\n typeof PDFJSDev === \"undefined\"\n ? \"../external/standard_fonts/\"\n : PDFJSDev.test(\"MOZCENTRAL\")\n ? \"resource://pdf.js/web/standard_fonts/\"\n : \"../web/standard_fonts/\",\n kind: OptionKind.API,\n },\n useSystemFonts: {\n // On Android, there is almost no chance to have the font we want so we\n // don't use the system fonts in this case (bug 1882613).\n /** @type {boolean|undefined} */\n value: (\n typeof PDFJSDev === \"undefined\"\n ? window.isGECKOVIEW\n : PDFJSDev.test(\"GECKOVIEW\")\n )\n ? false\n : undefined,\n kind: OptionKind.API,\n type: Type.BOOLEAN + Type.UNDEFINED,\n },\n verbosity: {\n /** @type {number} */\n value: 1,\n kind: OptionKind.API,\n },\n\n workerPort: {\n /** @type {Object} */\n value: null,\n kind: OptionKind.WORKER,\n },\n workerSrc: {\n /** @type {string} */\n value:\n // eslint-disable-next-line no-nested-ternary\n typeof PDFJSDev === \"undefined\"\n ? \"../src/pdf.worker.js\"\n : PDFJSDev.test(\"MOZCENTRAL\")\n ? \"resource://pdf.js/build/pdf.worker.mjs\"\n : \"../build/pdf.worker.mjs\",\n kind: OptionKind.WORKER,\n },\n};\nif (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) {\n defaultOptions.defaultUrl = {\n /** @type {string} */\n value:\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"CHROME\")\n ? \"\"\n : \"compressed.tracemonkey-pldi-09.pdf\",\n kind: OptionKind.VIEWER,\n };\n defaultOptions.sandboxBundleSrc = {\n /** @type {string} */\n value:\n typeof PDFJSDev === \"undefined\"\n ? \"../build/dev-sandbox/pdf.sandbox.mjs\"\n : \"../build/pdf.sandbox.mjs\",\n kind: OptionKind.VIEWER,\n };\n defaultOptions.viewerCssTheme = {\n /** @type {number} */\n value: typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"CHROME\") ? 2 : 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n };\n defaultOptions.enableFakeMLManager = {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER,\n };\n}\nif (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n defaultOptions.disablePreferences = {\n /** @type {boolean} */\n value: typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\"),\n kind: OptionKind.VIEWER,\n };\n} else if (PDFJSDev.test(\"CHROME\")) {\n defaultOptions.disableTelemetry = {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n };\n}\n\nif (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING || LIB\")) {\n // Ensure that the `defaultOptions` are correctly specified.\n for (const name in defaultOptions) {\n const { value, kind, type } = defaultOptions[name];\n\n if (kind & OptionKind.PREFERENCE) {\n if (kind === OptionKind.PREFERENCE) {\n throw new Error(`Cannot use only \"PREFERENCE\" kind: ${name}`);\n }\n if (kind & OptionKind.BROWSER) {\n throw new Error(`Cannot mix \"PREFERENCE\" and \"BROWSER\" kind: ${name}`);\n }\n if (type !== undefined) {\n throw new Error(\n `Cannot have \\`type\\`-field for \"PREFERENCE\" kind: ${name}`\n );\n }\n if (typeof compatParams === \"object\" && compatParams.has(name)) {\n throw new Error(\n `Should not have compatibility-value for \"PREFERENCE\" kind: ${name}`\n );\n }\n // Only \"simple\" preference-values are allowed.\n if (\n typeof value !== \"boolean\" &&\n typeof value !== \"string\" &&\n !Number.isInteger(value)\n ) {\n throw new Error(`Invalid value for \"PREFERENCE\" kind: ${name}`);\n }\n } else if (kind & OptionKind.BROWSER) {\n if (type !== undefined) {\n throw new Error(\n `Cannot have \\`type\\`-field for \"BROWSER\" kind: ${name}`\n );\n }\n if (typeof compatParams === \"object\" && compatParams.has(name)) {\n throw new Error(\n `Should not have compatibility-value for \"BROWSER\" kind: ${name}`\n );\n }\n if (value === undefined) {\n throw new Error(`Invalid value for \"BROWSER\" kind: ${name}`);\n }\n }\n }\n}\n\nclass AppOptions {\n static eventBus;\n\n static #opts = new Map();\n\n static {\n // Initialize all the user-options.\n for (const name in defaultOptions) {\n this.#opts.set(name, defaultOptions[name].value);\n }\n\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n // Apply any compatibility-values to the user-options.\n for (const [name, value] of compatParams) {\n this.#opts.set(name, value);\n }\n this._hasInvokedSet = false;\n\n this._checkDisablePreferences = () => {\n if (this.get(\"disablePreferences\")) {\n // Give custom implementations of the default viewer a simpler way to\n // opt-out of having the `Preferences` override existing `AppOptions`.\n return true;\n }\n if (this._hasInvokedSet) {\n console.warn(\n \"The Preferences may override manually set AppOptions; \" +\n 'please use the \"disablePreferences\"-option to prevent that.'\n );\n }\n return false;\n };\n }\n }\n\n constructor() {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n throw new Error(\"Cannot initialize AppOptions.\");\n }\n }\n\n static get(name) {\n return this.#opts.get(name);\n }\n\n static getAll(kind = null, defaultOnly = false) {\n const options = Object.create(null);\n for (const name in defaultOptions) {\n const defaultOpt = defaultOptions[name];\n\n if (kind && !(kind & defaultOpt.kind)) {\n continue;\n }\n options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value;\n }\n return options;\n }\n\n static set(name, value) {\n this.setAll({ [name]: value });\n }\n\n static setAll(options, prefs = false) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n this._hasInvokedSet ||= true;\n }\n let events;\n\n for (const name in options) {\n const defaultOpt = defaultOptions[name],\n userOpt = options[name];\n\n if (\n !defaultOpt ||\n !(\n typeof userOpt === typeof defaultOpt.value ||\n Type[(typeof userOpt).toUpperCase()] & defaultOpt.type\n )\n ) {\n continue;\n }\n const { kind } = defaultOpt;\n\n if (\n prefs &&\n !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)\n ) {\n continue;\n }\n if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) {\n (events ||= new Map()).set(name, userOpt);\n }\n this.#opts.set(name, userOpt);\n }\n\n if (events) {\n for (const [name, value] of events) {\n this.eventBus.dispatch(name.toLowerCase(), { source: this, value });\n }\n }\n }\n}\n\nexport { AppOptions, OptionKind };\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./event_utils\").EventBus} EventBus */\n/** @typedef {import(\"./interfaces\").IPDFLinkService} IPDFLinkService */\n\nimport { parseQueryString } from \"./ui_utils.js\";\n\nconst DEFAULT_LINK_REL = \"noopener noreferrer nofollow\";\n\nconst LinkTarget = {\n NONE: 0, // Default value.\n SELF: 1,\n BLANK: 2,\n PARENT: 3,\n TOP: 4,\n};\n\n/**\n * @typedef {Object} PDFLinkServiceOptions\n * @property {EventBus} eventBus - The application event bus.\n * @property {number} [externalLinkTarget] - Specifies the `target` attribute\n * for external links. Must use one of the values from {LinkTarget}.\n * Defaults to using no target.\n * @property {string} [externalLinkRel] - Specifies the `rel` attribute for\n * external links. Defaults to stripping the referrer.\n * @property {boolean} [ignoreDestinationZoom] - Ignores the zoom argument,\n * thus preserving the current zoom level in the viewer, when navigating\n * to internal destinations. The default value is `false`.\n */\n\n/**\n * Performs navigation functions inside PDF, such as opening specified page,\n * or destination.\n * @implements {IPDFLinkService}\n */\nclass PDFLinkService {\n externalLinkEnabled = true;\n\n /**\n * @param {PDFLinkServiceOptions} options\n */\n constructor({\n eventBus,\n externalLinkTarget = null,\n externalLinkRel = null,\n ignoreDestinationZoom = false,\n } = {}) {\n this.eventBus = eventBus;\n this.externalLinkTarget = externalLinkTarget;\n this.externalLinkRel = externalLinkRel;\n this._ignoreDestinationZoom = ignoreDestinationZoom;\n\n this.baseUrl = null;\n this.pdfDocument = null;\n this.pdfViewer = null;\n this.pdfHistory = null;\n }\n\n setDocument(pdfDocument, baseUrl = null) {\n this.baseUrl = baseUrl;\n this.pdfDocument = pdfDocument;\n }\n\n setViewer(pdfViewer) {\n this.pdfViewer = pdfViewer;\n }\n\n setHistory(pdfHistory) {\n this.pdfHistory = pdfHistory;\n }\n\n /**\n * @type {number}\n */\n get pagesCount() {\n return this.pdfDocument ? this.pdfDocument.numPages : 0;\n }\n\n /**\n * @type {number}\n */\n get page() {\n return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1;\n }\n\n /**\n * @param {number} value\n */\n set page(value) {\n if (this.pdfDocument) {\n this.pdfViewer.currentPageNumber = value;\n }\n }\n\n /**\n * @type {number}\n */\n get rotation() {\n return this.pdfDocument ? this.pdfViewer.pagesRotation : 0;\n }\n\n /**\n * @param {number} value\n */\n set rotation(value) {\n if (this.pdfDocument) {\n this.pdfViewer.pagesRotation = value;\n }\n }\n\n /**\n * @type {boolean}\n */\n get isInPresentationMode() {\n return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false;\n }\n\n /**\n * This method will, when available, also update the browser history.\n *\n * @param {string|Array} dest - The named, or explicit, PDF destination.\n */\n async goToDestination(dest) {\n if (!this.pdfDocument) {\n return;\n }\n let namedDest, explicitDest, pageNumber;\n if (typeof dest === \"string\") {\n namedDest = dest;\n explicitDest = await this.pdfDocument.getDestination(dest);\n } else {\n namedDest = null;\n explicitDest = await dest;\n }\n if (!Array.isArray(explicitDest)) {\n console.error(\n `goToDestination: \"${explicitDest}\" is not a valid destination array, for dest=\"${dest}\".`\n );\n return;\n }\n // Dest array looks like that: \n const [destRef] = explicitDest;\n\n if (destRef && typeof destRef === \"object\") {\n pageNumber = this.pdfDocument.cachedPageNumber(destRef);\n\n if (!pageNumber) {\n // Fetch the page reference if it's not yet available. This could\n // only occur during loading, before all pages have been resolved.\n try {\n pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1;\n } catch {\n console.error(\n `goToDestination: \"${destRef}\" is not a valid page reference, for dest=\"${dest}\".`\n );\n return;\n }\n }\n } else if (Number.isInteger(destRef)) {\n pageNumber = destRef + 1;\n }\n if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {\n console.error(\n `goToDestination: \"${pageNumber}\" is not a valid page number, for dest=\"${dest}\".`\n );\n return;\n }\n\n if (this.pdfHistory) {\n // Update the browser history before scrolling the new destination into\n // view, to be able to accurately capture the current document position.\n this.pdfHistory.pushCurrentPosition();\n this.pdfHistory.push({ namedDest, explicitDest, pageNumber });\n }\n\n this.pdfViewer.scrollPageIntoView({\n pageNumber,\n destArray: explicitDest,\n ignoreDestinationZoom: this._ignoreDestinationZoom,\n });\n }\n\n /**\n * This method will, when available, also update the browser history.\n *\n * @param {number|string} val - The page number, or page label.\n */\n goToPage(val) {\n if (!this.pdfDocument) {\n return;\n }\n const pageNumber =\n (typeof val === \"string\" && this.pdfViewer.pageLabelToPageNumber(val)) ||\n val | 0;\n if (\n !(\n Number.isInteger(pageNumber) &&\n pageNumber > 0 &&\n pageNumber <= this.pagesCount\n )\n ) {\n console.error(`PDFLinkService.goToPage: \"${val}\" is not a valid page.`);\n return;\n }\n\n if (this.pdfHistory) {\n // Update the browser history before scrolling the new page into view,\n // to be able to accurately capture the current document position.\n this.pdfHistory.pushCurrentPosition();\n this.pdfHistory.pushPage(pageNumber);\n }\n\n this.pdfViewer.scrollPageIntoView({ pageNumber });\n }\n\n /**\n * Adds various attributes (href, title, target, rel) to hyperlinks.\n * @param {HTMLAnchorElement} link\n * @param {string} url\n * @param {boolean} [newWindow]\n */\n addLinkAttributes(link, url, newWindow = false) {\n if (!url || typeof url !== \"string\") {\n throw new Error('A valid \"url\" parameter must provided.');\n }\n const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget,\n rel = this.externalLinkRel;\n\n if (this.externalLinkEnabled) {\n link.href = link.title = url;\n } else {\n link.href = \"\";\n link.title = `Disabled: ${url}`;\n link.onclick = () => false;\n }\n\n let targetStr = \"\"; // LinkTarget.NONE\n switch (target) {\n case LinkTarget.NONE:\n break;\n case LinkTarget.SELF:\n targetStr = \"_self\";\n break;\n case LinkTarget.BLANK:\n targetStr = \"_blank\";\n break;\n case LinkTarget.PARENT:\n targetStr = \"_parent\";\n break;\n case LinkTarget.TOP:\n targetStr = \"_top\";\n break;\n }\n link.target = targetStr;\n\n link.rel = typeof rel === \"string\" ? rel : DEFAULT_LINK_REL;\n }\n\n /**\n * @param {string|Array} dest - The PDF destination object.\n * @returns {string} The hyperlink to the PDF object.\n */\n getDestinationHash(dest) {\n if (typeof dest === \"string\") {\n if (dest.length > 0) {\n return this.getAnchorUrl(\"#\" + escape(dest));\n }\n } else if (Array.isArray(dest)) {\n const str = JSON.stringify(dest);\n if (str.length > 0) {\n return this.getAnchorUrl(\"#\" + escape(str));\n }\n }\n return this.getAnchorUrl(\"\");\n }\n\n /**\n * Prefix the full url on anchor links to make sure that links are resolved\n * relative to the current URL instead of the one defined in .\n * @param {string} anchor - The anchor hash, including the #.\n * @returns {string} The hyperlink to the PDF object.\n */\n getAnchorUrl(anchor) {\n return this.baseUrl ? this.baseUrl + anchor : anchor;\n }\n\n /**\n * @param {string} hash\n */\n setHash(hash) {\n if (!this.pdfDocument) {\n return;\n }\n let pageNumber, dest;\n if (hash.includes(\"=\")) {\n const params = parseQueryString(hash);\n if (params.has(\"search\")) {\n const query = params.get(\"search\").replaceAll('\"', \"\"),\n phrase = params.get(\"phrase\") === \"true\";\n\n this.eventBus.dispatch(\"findfromurlhash\", {\n source: this,\n query: phrase ? query : query.match(/\\S+/g),\n });\n }\n // borrowing syntax from \"Parameters for Opening PDF Files\"\n if (params.has(\"page\")) {\n pageNumber = params.get(\"page\") | 0 || 1;\n }\n if (params.has(\"zoom\")) {\n // Build the destination array.\n const zoomArgs = params.get(\"zoom\").split(\",\"); // scale,left,top\n const zoomArg = zoomArgs[0];\n const zoomArgNumber = parseFloat(zoomArg);\n\n if (!zoomArg.includes(\"Fit\")) {\n // If the zoomArg is a number, it has to get divided by 100. If it's\n // a string, it should stay as it is.\n dest = [\n null,\n { name: \"XYZ\" },\n zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,\n zoomArgs.length > 2 ? zoomArgs[2] | 0 : null,\n zoomArgNumber ? zoomArgNumber / 100 : zoomArg,\n ];\n } else if (zoomArg === \"Fit\" || zoomArg === \"FitB\") {\n dest = [null, { name: zoomArg }];\n } else if (\n zoomArg === \"FitH\" ||\n zoomArg === \"FitBH\" ||\n zoomArg === \"FitV\" ||\n zoomArg === \"FitBV\"\n ) {\n dest = [\n null,\n { name: zoomArg },\n zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,\n ];\n } else if (zoomArg === \"FitR\") {\n if (zoomArgs.length !== 5) {\n console.error(\n 'PDFLinkService.setHash: Not enough parameters for \"FitR\".'\n );\n } else {\n dest = [\n null,\n { name: zoomArg },\n zoomArgs[1] | 0,\n zoomArgs[2] | 0,\n zoomArgs[3] | 0,\n zoomArgs[4] | 0,\n ];\n }\n } else {\n console.error(\n `PDFLinkService.setHash: \"${zoomArg}\" is not a valid zoom value.`\n );\n }\n }\n if (dest) {\n this.pdfViewer.scrollPageIntoView({\n pageNumber: pageNumber || this.page,\n destArray: dest,\n allowNegativeOffset: true,\n });\n } else if (pageNumber) {\n this.page = pageNumber; // simple page\n }\n if (params.has(\"pagemode\")) {\n this.eventBus.dispatch(\"pagemode\", {\n source: this,\n mode: params.get(\"pagemode\"),\n });\n }\n // Ensure that this parameter is *always* handled last, in order to\n // guarantee that it won't be overridden (e.g. by the \"page\" parameter).\n if (params.has(\"nameddest\")) {\n this.goToDestination(params.get(\"nameddest\"));\n }\n\n if (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) {\n return;\n }\n // Support opening of PDF attachments in the Firefox PDF Viewer,\n // which uses a couple of non-standard hash parameters; refer to\n // `DownloadManager.openOrDownloadData` in the firefoxcom.js file.\n if (!params.has(\"filename\") || !params.has(\"filedest\")) {\n return;\n }\n hash = params.get(\"filedest\");\n }\n\n // Named (or explicit) destination.\n dest = unescape(hash);\n try {\n dest = JSON.parse(dest);\n\n if (!Array.isArray(dest)) {\n // Avoid incorrectly rejecting a valid named destination, such as\n // e.g. \"4.3\" or \"true\", because `JSON.parse` converted its type.\n dest = dest.toString();\n }\n } catch {}\n\n if (typeof dest === \"string\" || PDFLinkService.#isValidExplicitDest(dest)) {\n this.goToDestination(dest);\n return;\n }\n console.error(\n `PDFLinkService.setHash: \"${unescape(hash)}\" is not a valid destination.`\n );\n }\n\n /**\n * @param {string} action\n */\n executeNamedAction(action) {\n if (!this.pdfDocument) {\n return;\n }\n // See PDF reference, table 8.45 - Named action\n switch (action) {\n case \"GoBack\":\n this.pdfHistory?.back();\n break;\n\n case \"GoForward\":\n this.pdfHistory?.forward();\n break;\n\n case \"NextPage\":\n this.pdfViewer.nextPage();\n break;\n\n case \"PrevPage\":\n this.pdfViewer.previousPage();\n break;\n\n case \"LastPage\":\n this.page = this.pagesCount;\n break;\n\n case \"FirstPage\":\n this.page = 1;\n break;\n\n default:\n break; // No action according to spec\n }\n\n this.eventBus.dispatch(\"namedaction\", {\n source: this,\n action,\n });\n }\n\n /**\n * @param {Object} action\n */\n async executeSetOCGState(action) {\n if (!this.pdfDocument) {\n return;\n }\n const pdfDocument = this.pdfDocument,\n optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise;\n\n if (pdfDocument !== this.pdfDocument) {\n return; // The document was closed while the optional content resolved.\n }\n optionalContentConfig.setOCGState(action);\n\n this.pdfViewer.optionalContentConfigPromise = Promise.resolve(\n optionalContentConfig\n );\n }\n\n static #isValidExplicitDest(dest) {\n if (!Array.isArray(dest) || dest.length < 2) {\n return false;\n }\n const [page, zoom, ...args] = dest;\n if (\n !(\n typeof page === \"object\" &&\n Number.isInteger(page?.num) &&\n Number.isInteger(page?.gen)\n ) &&\n !Number.isInteger(page)\n ) {\n return false;\n }\n if (!(typeof zoom === \"object\" && typeof zoom?.name === \"string\")) {\n return false;\n }\n const argsLen = args.length;\n let allowNull = true;\n switch (zoom.name) {\n case \"XYZ\":\n if (argsLen < 2 || argsLen > 3) {\n return false;\n }\n break;\n case \"Fit\":\n case \"FitB\":\n return argsLen === 0;\n case \"FitH\":\n case \"FitBH\":\n case \"FitV\":\n case \"FitBV\":\n if (argsLen > 1) {\n return false;\n }\n break;\n case \"FitR\":\n if (argsLen !== 4) {\n return false;\n }\n allowNull = false;\n break;\n default:\n return false;\n }\n for (const arg of args) {\n if (!(typeof arg === \"number\" || (allowNull && arg === null))) {\n return false;\n }\n }\n return true;\n }\n}\n\n/**\n * @implements {IPDFLinkService}\n */\nclass SimpleLinkService extends PDFLinkService {\n setDocument(pdfDocument, baseUrl = null) {}\n}\n\nexport { LinkTarget, PDFLinkService, SimpleLinkService };\n","/* Copyright 2016 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst {\n AbortException,\n AnnotationEditorLayer,\n AnnotationEditorParamsType,\n AnnotationEditorType,\n AnnotationEditorUIManager,\n AnnotationLayer,\n AnnotationMode,\n build,\n ColorPicker,\n createValidAbsoluteUrl,\n DOMSVGFactory,\n DrawLayer,\n FeatureTest,\n fetchData,\n getDocument,\n getFilenameFromUrl,\n getPdfFilenameFromUrl,\n getXfaPageViewport,\n GlobalWorkerOptions,\n ImageKind,\n InvalidPDFException,\n isDataScheme,\n isPdfFile,\n MissingPDFException,\n noContextMenu,\n normalizeUnicode,\n OPS,\n OutputScale,\n PasswordResponses,\n PDFDataRangeTransport,\n PDFDateString,\n PDFWorker,\n PermissionFlag,\n PixelsPerInch,\n RenderingCancelledException,\n setLayerDimensions,\n shadow,\n stopEvent,\n TextLayer,\n TouchManager,\n UnexpectedResponseException,\n Util,\n VerbosityLevel,\n version,\n XfaLayer,\n} = globalThis.pdfjsLib;\n\nexport {\n AbortException,\n AnnotationEditorLayer,\n AnnotationEditorParamsType,\n AnnotationEditorType,\n AnnotationEditorUIManager,\n AnnotationLayer,\n AnnotationMode,\n build,\n ColorPicker,\n createValidAbsoluteUrl,\n DOMSVGFactory,\n DrawLayer,\n FeatureTest,\n fetchData,\n getDocument,\n getFilenameFromUrl,\n getPdfFilenameFromUrl,\n getXfaPageViewport,\n GlobalWorkerOptions,\n ImageKind,\n InvalidPDFException,\n isDataScheme,\n isPdfFile,\n MissingPDFException,\n noContextMenu,\n normalizeUnicode,\n OPS,\n OutputScale,\n PasswordResponses,\n PDFDataRangeTransport,\n PDFDateString,\n PDFWorker,\n PermissionFlag,\n PixelsPerInch,\n RenderingCancelledException,\n setLayerDimensions,\n shadow,\n stopEvent,\n TextLayer,\n TouchManager,\n UnexpectedResponseException,\n Util,\n VerbosityLevel,\n version,\n XfaLayer,\n};\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst WaitOnType = {\n EVENT: \"event\",\n TIMEOUT: \"timeout\",\n};\n\n/**\n * @typedef {Object} WaitOnEventOrTimeoutParameters\n * @property {Object} target - The event target, can for example be:\n * `window`, `document`, a DOM element, or an {EventBus} instance.\n * @property {string} name - The name of the event.\n * @property {number} delay - The delay, in milliseconds, after which the\n * timeout occurs (if the event wasn't already dispatched).\n */\n\n/**\n * Allows waiting for an event or a timeout, whichever occurs first.\n * Can be used to ensure that an action always occurs, even when an event\n * arrives late or not at all.\n *\n * @param {WaitOnEventOrTimeoutParameters}\n * @returns {Promise} A promise that is resolved with a {WaitOnType} value.\n */\nasync function waitOnEventOrTimeout({ target, name, delay = 0 }) {\n if (\n typeof target !== \"object\" ||\n !(name && typeof name === \"string\") ||\n !(Number.isInteger(delay) && delay >= 0)\n ) {\n throw new Error(\"waitOnEventOrTimeout - invalid parameters.\");\n }\n const { promise, resolve } = Promise.withResolvers();\n const ac = new AbortController();\n\n function handler(type) {\n ac.abort(); // Remove event listener.\n clearTimeout(timeout);\n\n resolve(type);\n }\n\n const evtMethod = target instanceof EventBus ? \"_on\" : \"addEventListener\";\n target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), {\n signal: ac.signal,\n });\n\n const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay);\n\n return promise;\n}\n\n/**\n * Simple event bus for an application. Listeners are attached using the `on`\n * and `off` methods. To raise an event, the `dispatch` method shall be used.\n */\nclass EventBus {\n #listeners = Object.create(null);\n\n /**\n * @param {string} eventName\n * @param {function} listener\n * @param {Object} [options]\n */\n on(eventName, listener, options = null) {\n this._on(eventName, listener, {\n external: true,\n once: options?.once,\n signal: options?.signal,\n });\n }\n\n /**\n * @param {string} eventName\n * @param {function} listener\n * @param {Object} [options]\n */\n off(eventName, listener, options = null) {\n this._off(eventName, listener);\n }\n\n /**\n * @param {string} eventName\n * @param {Object} data\n */\n dispatch(eventName, data) {\n const eventListeners = this.#listeners[eventName];\n if (!eventListeners || eventListeners.length === 0) {\n return;\n }\n let externalListeners;\n // Making copy of the listeners array in case if it will be modified\n // during dispatch.\n for (const { listener, external, once } of eventListeners.slice(0)) {\n if (once) {\n this._off(eventName, listener);\n }\n if (external) {\n (externalListeners ||= []).push(listener);\n continue;\n }\n listener(data);\n }\n // Dispatch any \"external\" listeners *after* the internal ones, to give the\n // viewer components time to handle events and update their state first.\n if (externalListeners) {\n for (const listener of externalListeners) {\n listener(data);\n }\n externalListeners = null;\n }\n }\n\n /**\n * @ignore\n */\n _on(eventName, listener, options = null) {\n let rmAbort = null;\n if (options?.signal instanceof AbortSignal) {\n const { signal } = options;\n if (signal.aborted) {\n console.error(\"Cannot use an `aborted` signal.\");\n return;\n }\n const onAbort = () => this._off(eventName, listener);\n rmAbort = () => signal.removeEventListener(\"abort\", onAbort);\n\n signal.addEventListener(\"abort\", onAbort);\n }\n\n const eventListeners = (this.#listeners[eventName] ||= []);\n eventListeners.push({\n listener,\n external: options?.external === true,\n once: options?.once === true,\n rmAbort,\n });\n }\n\n /**\n * @ignore\n */\n _off(eventName, listener, options = null) {\n const eventListeners = this.#listeners[eventName];\n if (!eventListeners) {\n return;\n }\n for (let i = 0, ii = eventListeners.length; i < ii; i++) {\n const evt = eventListeners[i];\n if (evt.listener === listener) {\n evt.rmAbort?.(); // Ensure that the `AbortSignal` listener is removed.\n eventListeners.splice(i, 1);\n return;\n }\n }\n }\n}\n\n/**\n * NOTE: Only used in the Firefox build-in pdf viewer.\n */\nclass FirefoxEventBus extends EventBus {\n #externalServices;\n\n #globalEventNames;\n\n #isInAutomation;\n\n constructor(globalEventNames, externalServices, isInAutomation) {\n super();\n this.#globalEventNames = globalEventNames;\n this.#externalServices = externalServices;\n this.#isInAutomation = isInAutomation;\n }\n\n dispatch(eventName, data) {\n if (typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: FirefoxEventBus.dispatch\");\n }\n super.dispatch(eventName, data);\n\n if (this.#isInAutomation) {\n const detail = Object.create(null);\n if (data) {\n for (const key in data) {\n const value = data[key];\n if (key === \"source\") {\n if (value === window || value === document) {\n return; // No need to re-dispatch (already) global events.\n }\n continue; // Ignore the `source` property.\n }\n detail[key] = value;\n }\n }\n const event = new CustomEvent(eventName, {\n bubbles: true,\n cancelable: true,\n detail,\n });\n document.dispatchEvent(event);\n }\n\n if (this.#globalEventNames?.has(eventName)) {\n this.#externalServices.dispatchGlobalEvent({\n eventName,\n detail: data,\n });\n }\n }\n}\n\nexport { EventBus, FirefoxEventBus, waitOnEventOrTimeout, WaitOnType };\n","/* Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./interfaces.js\").IL10n} IL10n */\n\nclass BaseExternalServices {\n constructor() {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseExternalServices\n ) {\n throw new Error(\"Cannot initialize BaseExternalServices.\");\n }\n }\n\n updateFindControlState(data) {}\n\n updateFindMatchesCount(data) {}\n\n initPassiveLoading() {}\n\n reportTelemetry(data) {}\n\n /**\n * @returns {Promise}\n */\n async createL10n() {\n throw new Error(\"Not implemented: createL10n\");\n }\n\n createScripting() {\n throw new Error(\"Not implemented: createScripting\");\n }\n\n updateEditorStates(data) {\n throw new Error(\"Not implemented: updateEditorStates\");\n }\n\n dispatchGlobalEvent(_event) {}\n}\n\nexport { BaseExternalServices };\n","/* Copyright 2013 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppOptions, OptionKind } from \"./app_options.js\";\n\n/**\n * BasePreferences - Abstract base class for storing persistent settings.\n * Used for settings that should be applied to all opened documents,\n * or every time the viewer is loaded.\n */\nclass BasePreferences {\n #defaults = Object.freeze(\n typeof PDFJSDev === \"undefined\"\n ? AppOptions.getAll(OptionKind.PREFERENCE, /* defaultOnly = */ true)\n : PDFJSDev.eval(\"DEFAULT_PREFERENCES\")\n );\n\n #initializedPromise = null;\n\n constructor() {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BasePreferences\n ) {\n throw new Error(\"Cannot initialize BasePreferences.\");\n }\n\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"CHROME\")) {\n Object.defineProperty(this, \"defaults\", {\n get() {\n return this.#defaults;\n },\n });\n }\n\n this.#initializedPromise = this._readFromStorage(this.#defaults).then(\n ({ browserPrefs, prefs }) => {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) &&\n AppOptions._checkDisablePreferences()\n ) {\n return;\n }\n AppOptions.setAll({ ...browserPrefs, ...prefs }, /* prefs = */ true);\n }\n );\n\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n window.addEventListener(\n \"updatedPreference\",\n async ({ detail: { name, value } }) => {\n await this.#initializedPromise;\n AppOptions.setAll({ [name]: value }, /* prefs = */ true);\n }\n );\n }\n }\n\n /**\n * Stub function for writing preferences to storage.\n * @param {Object} prefObj The preferences that should be written to storage.\n * @returns {Promise} A promise that is resolved when the preference values\n * have been written.\n */\n async _writeToStorage(prefObj) {\n throw new Error(\"Not implemented: _writeToStorage\");\n }\n\n /**\n * Stub function for reading preferences from storage.\n * @param {Object} prefObj The preferences that should be read from storage.\n * @returns {Promise} A promise that is resolved with an {Object} containing\n * the preferences that have been read.\n */\n async _readFromStorage(prefObj) {\n throw new Error(\"Not implemented: _readFromStorage\");\n }\n\n /**\n * Reset the preferences to their default values and update storage.\n * @returns {Promise} A promise that is resolved when the preference values\n * have been reset.\n */\n async reset() {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Please use `about:config` to change preferences.\");\n }\n await this.#initializedPromise;\n AppOptions.setAll(this.#defaults, /* prefs = */ true);\n\n await this._writeToStorage(this.#defaults);\n }\n\n /**\n * Set the value of a preference.\n * @param {string} name The name of the preference that should be changed.\n * @param {boolean|number|string} value The new value of the preference.\n * @returns {Promise} A promise that is resolved when the value has been set,\n * provided that the preference exists and the types match.\n */\n async set(name, value) {\n await this.#initializedPromise;\n AppOptions.setAll({ [name]: value }, /* prefs = */ true);\n\n await this._writeToStorage(\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")\n ? { [name]: AppOptions.get(name) }\n : AppOptions.getAll(OptionKind.PREFERENCE)\n );\n }\n\n /**\n * Get the value of a preference.\n * @param {string} name The name of the preference whose value is requested.\n * @returns {Promise} A promise resolved with a {boolean|number|string}\n * containing the value of the preference.\n */\n async get(name) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: get\");\n }\n await this.#initializedPromise;\n return AppOptions.get(name);\n }\n\n get initializedPromise() {\n return this.#initializedPromise;\n }\n}\n\nexport { BasePreferences };\n","/**\n * The `FluentType` class is the base of Fluent's type system.\n *\n * Fluent types wrap JavaScript values and store additional configuration for\n * them, which can then be used in the `toString` method together with a proper\n * `Intl` formatter.\n */\nexport class FluentType {\n /**\n * Create a `FluentType` instance.\n *\n * @param value The JavaScript value to wrap.\n */\n constructor(value) {\n this.value = value;\n }\n /**\n * Unwrap the raw value stored by this `FluentType`.\n */\n valueOf() {\n return this.value;\n }\n}\n/**\n * A `FluentType` representing no correct value.\n */\nexport class FluentNone extends FluentType {\n /**\n * Create an instance of `FluentNone` with an optional fallback value.\n * @param value The fallback value of this `FluentNone`.\n */\n constructor(value = \"???\") {\n super(value);\n }\n /**\n * Format this `FluentNone` to the fallback string.\n */\n toString(scope) {\n return `{${this.value}}`;\n }\n}\n/**\n * A `FluentType` representing a number.\n *\n * A `FluentNumber` instance stores the number value of the number it\n * represents. It may also store an option bag of options which will be passed\n * to `Intl.NumerFormat` when the `FluentNumber` is formatted to a string.\n */\nexport class FluentNumber extends FluentType {\n /**\n * Create an instance of `FluentNumber` with options to the\n * `Intl.NumberFormat` constructor.\n *\n * @param value The number value of this `FluentNumber`.\n * @param opts Options which will be passed to `Intl.NumberFormat`.\n */\n constructor(value, opts = {}) {\n super(value);\n this.opts = opts;\n }\n /**\n * Format this `FluentNumber` to a string.\n */\n toString(scope) {\n try {\n const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts);\n return nf.format(this.value);\n }\n catch (err) {\n scope.reportError(err);\n return this.value.toString(10);\n }\n }\n}\n/**\n * A `FluentType` representing a date and time.\n *\n * A `FluentDateTime` instance stores the number value of the date it\n * represents, as a numerical timestamp in milliseconds. It may also store an\n * option bag of options which will be passed to `Intl.DateTimeFormat` when the\n * `FluentDateTime` is formatted to a string.\n */\nexport class FluentDateTime extends FluentType {\n /**\n * Create an instance of `FluentDateTime` with options to the\n * `Intl.DateTimeFormat` constructor.\n *\n * @param value The number value of this `FluentDateTime`, in milliseconds.\n * @param opts Options which will be passed to `Intl.DateTimeFormat`.\n */\n constructor(value, opts = {}) {\n super(value);\n this.opts = opts;\n }\n /**\n * Format this `FluentDateTime` to a string.\n */\n toString(scope) {\n try {\n const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts);\n return dtf.format(this.value);\n }\n catch (err) {\n scope.reportError(err);\n return new Date(this.value).toISOString();\n }\n }\n}\n","/* global Intl */\n/**\n * @overview\n *\n * The role of the Fluent resolver is to format a `Pattern` to an instance of\n * `FluentValue`. For performance reasons, primitive strings are considered\n * such instances, too.\n *\n * Translations can contain references to other messages or variables,\n * conditional logic in form of select expressions, traits which describe their\n * grammatical features, and can use Fluent builtins which make use of the\n * `Intl` formatters to format numbers and dates into the bundle's languages.\n * See the documentation of the Fluent syntax for more information.\n *\n * In case of errors the resolver will try to salvage as much of the\n * translation as possible. In rare situations where the resolver didn't know\n * how to recover from an error it will return an instance of `FluentNone`.\n *\n * All expressions resolve to an instance of `FluentValue`. The caller should\n * use the `toString` method to convert the instance to a native value.\n *\n * Functions in this file pass around an instance of the `Scope` class, which\n * stores the data required for successful resolution and error recovery.\n */\nimport { FluentType, FluentNone, FluentNumber, FluentDateTime, } from \"./types.js\";\n/**\n * The maximum number of placeables which can be expanded in a single call to\n * `formatPattern`. The limit protects against the Billion Laughs and Quadratic\n * Blowup attacks. See https://msdn.microsoft.com/en-us/magazine/ee335713.aspx.\n */\nconst MAX_PLACEABLES = 100;\n/** Unicode bidi isolation characters. */\nconst FSI = \"\\u2068\";\nconst PDI = \"\\u2069\";\n/** Helper: match a variant key to the given selector. */\nfunction match(scope, selector, key) {\n if (key === selector) {\n // Both are strings.\n return true;\n }\n // XXX Consider comparing options too, e.g. minimumFractionDigits.\n if (key instanceof FluentNumber &&\n selector instanceof FluentNumber &&\n key.value === selector.value) {\n return true;\n }\n if (selector instanceof FluentNumber && typeof key === \"string\") {\n let category = scope\n .memoizeIntlObject(Intl.PluralRules, selector.opts)\n .select(selector.value);\n if (key === category) {\n return true;\n }\n }\n return false;\n}\n/** Helper: resolve the default variant from a list of variants. */\nfunction getDefault(scope, variants, star) {\n if (variants[star]) {\n return resolvePattern(scope, variants[star].value);\n }\n scope.reportError(new RangeError(\"No default\"));\n return new FluentNone();\n}\n/** Helper: resolve arguments to a call expression. */\nfunction getArguments(scope, args) {\n const positional = [];\n const named = Object.create(null);\n for (const arg of args) {\n if (arg.type === \"narg\") {\n named[arg.name] = resolveExpression(scope, arg.value);\n }\n else {\n positional.push(resolveExpression(scope, arg));\n }\n }\n return { positional, named };\n}\n/** Resolve an expression to a Fluent type. */\nfunction resolveExpression(scope, expr) {\n switch (expr.type) {\n case \"str\":\n return expr.value;\n case \"num\":\n return new FluentNumber(expr.value, {\n minimumFractionDigits: expr.precision,\n });\n case \"var\":\n return resolveVariableReference(scope, expr);\n case \"mesg\":\n return resolveMessageReference(scope, expr);\n case \"term\":\n return resolveTermReference(scope, expr);\n case \"func\":\n return resolveFunctionReference(scope, expr);\n case \"select\":\n return resolveSelectExpression(scope, expr);\n default:\n return new FluentNone();\n }\n}\n/** Resolve a reference to a variable. */\nfunction resolveVariableReference(scope, { name }) {\n let arg;\n if (scope.params) {\n // We're inside a TermReference. It's OK to reference undefined parameters.\n if (Object.prototype.hasOwnProperty.call(scope.params, name)) {\n arg = scope.params[name];\n }\n else {\n return new FluentNone(`$${name}`);\n }\n }\n else if (scope.args &&\n Object.prototype.hasOwnProperty.call(scope.args, name)) {\n // We're in the top-level Pattern or inside a MessageReference. Missing\n // variables references produce ReferenceErrors.\n arg = scope.args[name];\n }\n else {\n scope.reportError(new ReferenceError(`Unknown variable: $${name}`));\n return new FluentNone(`$${name}`);\n }\n // Return early if the argument already is an instance of FluentType.\n if (arg instanceof FluentType) {\n return arg;\n }\n // Convert the argument to a Fluent type.\n switch (typeof arg) {\n case \"string\":\n return arg;\n case \"number\":\n return new FluentNumber(arg);\n case \"object\":\n if (arg instanceof Date) {\n return new FluentDateTime(arg.getTime());\n }\n // eslint-disable-next-line no-fallthrough\n default:\n scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`));\n return new FluentNone(`$${name}`);\n }\n}\n/** Resolve a reference to another message. */\nfunction resolveMessageReference(scope, { name, attr }) {\n const message = scope.bundle._messages.get(name);\n if (!message) {\n scope.reportError(new ReferenceError(`Unknown message: ${name}`));\n return new FluentNone(name);\n }\n if (attr) {\n const attribute = message.attributes[attr];\n if (attribute) {\n return resolvePattern(scope, attribute);\n }\n scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));\n return new FluentNone(`${name}.${attr}`);\n }\n if (message.value) {\n return resolvePattern(scope, message.value);\n }\n scope.reportError(new ReferenceError(`No value: ${name}`));\n return new FluentNone(name);\n}\n/** Resolve a call to a Term with key-value arguments. */\nfunction resolveTermReference(scope, { name, attr, args }) {\n const id = `-${name}`;\n const term = scope.bundle._terms.get(id);\n if (!term) {\n scope.reportError(new ReferenceError(`Unknown term: ${id}`));\n return new FluentNone(id);\n }\n if (attr) {\n const attribute = term.attributes[attr];\n if (attribute) {\n // Every TermReference has its own variables.\n scope.params = getArguments(scope, args).named;\n const resolved = resolvePattern(scope, attribute);\n scope.params = null;\n return resolved;\n }\n scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));\n return new FluentNone(`${id}.${attr}`);\n }\n scope.params = getArguments(scope, args).named;\n const resolved = resolvePattern(scope, term.value);\n scope.params = null;\n return resolved;\n}\n/** Resolve a call to a Function with positional and key-value arguments. */\nfunction resolveFunctionReference(scope, { name, args }) {\n // Some functions are built-in. Others may be provided by the runtime via\n // the `FluentBundle` constructor.\n let func = scope.bundle._functions[name];\n if (!func) {\n scope.reportError(new ReferenceError(`Unknown function: ${name}()`));\n return new FluentNone(`${name}()`);\n }\n if (typeof func !== \"function\") {\n scope.reportError(new TypeError(`Function ${name}() is not callable`));\n return new FluentNone(`${name}()`);\n }\n try {\n let resolved = getArguments(scope, args);\n return func(resolved.positional, resolved.named);\n }\n catch (err) {\n scope.reportError(err);\n return new FluentNone(`${name}()`);\n }\n}\n/** Resolve a select expression to the member object. */\nfunction resolveSelectExpression(scope, { selector, variants, star }) {\n let sel = resolveExpression(scope, selector);\n if (sel instanceof FluentNone) {\n return getDefault(scope, variants, star);\n }\n // Match the selector against keys of each variant, in order.\n for (const variant of variants) {\n const key = resolveExpression(scope, variant.key);\n if (match(scope, sel, key)) {\n return resolvePattern(scope, variant.value);\n }\n }\n return getDefault(scope, variants, star);\n}\n/** Resolve a pattern (a complex string with placeables). */\nexport function resolveComplexPattern(scope, ptn) {\n if (scope.dirty.has(ptn)) {\n scope.reportError(new RangeError(\"Cyclic reference\"));\n return new FluentNone();\n }\n // Tag the pattern as dirty for the purpose of the current resolution.\n scope.dirty.add(ptn);\n const result = [];\n // Wrap interpolations with Directional Isolate Formatting characters\n // only when the pattern has more than one element.\n const useIsolating = scope.bundle._useIsolating && ptn.length > 1;\n for (const elem of ptn) {\n if (typeof elem === \"string\") {\n result.push(scope.bundle._transform(elem));\n continue;\n }\n scope.placeables++;\n if (scope.placeables > MAX_PLACEABLES) {\n scope.dirty.delete(ptn);\n // This is a fatal error which causes the resolver to instantly bail out\n // on this pattern. The length check protects against excessive memory\n // usage, and throwing protects against eating up the CPU when long\n // placeables are deeply nested.\n throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` +\n `max allowed is ${MAX_PLACEABLES}`);\n }\n if (useIsolating) {\n result.push(FSI);\n }\n result.push(resolveExpression(scope, elem).toString(scope));\n if (useIsolating) {\n result.push(PDI);\n }\n }\n scope.dirty.delete(ptn);\n return result.join(\"\");\n}\n/**\n * Resolve a simple or a complex Pattern to a FluentString\n * (which is really the string primitive).\n */\nfunction resolvePattern(scope, value) {\n // Resolve a simple pattern.\n if (typeof value === \"string\") {\n return scope.bundle._transform(value);\n }\n return resolveComplexPattern(scope, value);\n}\n","export class Scope {\n constructor(bundle, errors, args) {\n /**\n * The Set of patterns already encountered during this resolution.\n * Used to detect and prevent cyclic resolutions.\n * @ignore\n */\n this.dirty = new WeakSet();\n /** A dict of parameters passed to a TermReference. */\n this.params = null;\n /**\n * The running count of placeables resolved so far.\n * Used to detect the Billion Laughs and Quadratic Blowup attacks.\n * @ignore\n */\n this.placeables = 0;\n this.bundle = bundle;\n this.errors = errors;\n this.args = args;\n }\n reportError(error) {\n if (!this.errors || !(error instanceof Error)) {\n throw error;\n }\n this.errors.push(error);\n }\n memoizeIntlObject(ctor, opts) {\n let cache = this.bundle._intls.get(ctor);\n if (!cache) {\n cache = {};\n this.bundle._intls.set(ctor, cache);\n }\n let id = JSON.stringify(opts);\n if (!cache[id]) {\n cache[id] = new ctor(this.bundle.locales, opts);\n }\n return cache[id];\n }\n}\n","/**\n * @overview\n *\n * The FTL resolver ships with a number of functions built-in.\n *\n * Each function take two arguments:\n * - args - an array of positional args\n * - opts - an object of key-value args\n *\n * Arguments to functions are guaranteed to already be instances of\n * `FluentValue`. Functions must return `FluentValues` as well.\n */\nimport { FluentNone, FluentNumber, FluentDateTime, } from \"./types.js\";\nfunction values(opts, allowed) {\n const unwrapped = Object.create(null);\n for (const [name, opt] of Object.entries(opts)) {\n if (allowed.includes(name)) {\n unwrapped[name] = opt.valueOf();\n }\n }\n return unwrapped;\n}\nconst NUMBER_ALLOWED = [\n \"unitDisplay\",\n \"currencyDisplay\",\n \"useGrouping\",\n \"minimumIntegerDigits\",\n \"minimumFractionDigits\",\n \"maximumFractionDigits\",\n \"minimumSignificantDigits\",\n \"maximumSignificantDigits\",\n];\n/**\n * The implementation of the `NUMBER()` builtin available to translations.\n *\n * Translations may call the `NUMBER()` builtin in order to specify formatting\n * options of a number. For example:\n *\n * pi = The value of π is {NUMBER($pi, maximumFractionDigits: 2)}.\n *\n * The implementation expects an array of `FluentValues` representing the\n * positional arguments, and an object of named `FluentValues` representing the\n * named parameters.\n *\n * The following options are recognized:\n *\n * unitDisplay\n * currencyDisplay\n * useGrouping\n * minimumIntegerDigits\n * minimumFractionDigits\n * maximumFractionDigits\n * minimumSignificantDigits\n * maximumSignificantDigits\n *\n * Other options are ignored.\n *\n * @param args The positional arguments passed to this `NUMBER()`.\n * @param opts The named argments passed to this `NUMBER()`.\n */\nexport function NUMBER(args, opts) {\n let arg = args[0];\n if (arg instanceof FluentNone) {\n return new FluentNone(`NUMBER(${arg.valueOf()})`);\n }\n if (arg instanceof FluentNumber) {\n return new FluentNumber(arg.valueOf(), {\n ...arg.opts,\n ...values(opts, NUMBER_ALLOWED),\n });\n }\n if (arg instanceof FluentDateTime) {\n return new FluentNumber(arg.valueOf(), {\n ...values(opts, NUMBER_ALLOWED),\n });\n }\n throw new TypeError(\"Invalid argument to NUMBER\");\n}\nconst DATETIME_ALLOWED = [\n \"dateStyle\",\n \"timeStyle\",\n \"fractionalSecondDigits\",\n \"dayPeriod\",\n \"hour12\",\n \"weekday\",\n \"era\",\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"timeZoneName\",\n];\n/**\n * The implementation of the `DATETIME()` builtin available to translations.\n *\n * Translations may call the `DATETIME()` builtin in order to specify\n * formatting options of a number. For example:\n *\n * now = It's {DATETIME($today, month: \"long\")}.\n *\n * The implementation expects an array of `FluentValues` representing the\n * positional arguments, and an object of named `FluentValues` representing the\n * named parameters.\n *\n * The following options are recognized:\n *\n * dateStyle\n * timeStyle\n * fractionalSecondDigits\n * dayPeriod\n * hour12\n * weekday\n * era\n * year\n * month\n * day\n * hour\n * minute\n * second\n * timeZoneName\n *\n * Other options are ignored.\n *\n * @param args The positional arguments passed to this `DATETIME()`.\n * @param opts The named argments passed to this `DATETIME()`.\n */\nexport function DATETIME(args, opts) {\n let arg = args[0];\n if (arg instanceof FluentNone) {\n return new FluentNone(`DATETIME(${arg.valueOf()})`);\n }\n if (arg instanceof FluentDateTime) {\n return new FluentDateTime(arg.valueOf(), {\n ...arg.opts,\n ...values(opts, DATETIME_ALLOWED),\n });\n }\n if (arg instanceof FluentNumber) {\n return new FluentDateTime(arg.valueOf(), {\n ...values(opts, DATETIME_ALLOWED),\n });\n }\n throw new TypeError(\"Invalid argument to DATETIME\");\n}\n","const cache = new Map();\nexport function getMemoizerForLocale(locales) {\n const stringLocale = Array.isArray(locales) ? locales.join(\" \") : locales;\n let memoizer = cache.get(stringLocale);\n if (memoizer === undefined) {\n memoizer = new Map();\n cache.set(stringLocale, memoizer);\n }\n return memoizer;\n}\n","import { resolveComplexPattern } from \"./resolver.js\";\nimport { Scope } from \"./scope.js\";\nimport { FluentNone } from \"./types.js\";\nimport { NUMBER, DATETIME } from \"./builtins.js\";\nimport { getMemoizerForLocale } from \"./memoizer.js\";\n/**\n * Message bundles are single-language stores of translation resources. They are\n * responsible for formatting message values and attributes to strings.\n */\nexport class FluentBundle {\n /**\n * Create an instance of `FluentBundle`.\n *\n * @example\n * ```js\n * let bundle = new FluentBundle([\"en-US\", \"en\"]);\n *\n * let bundle = new FluentBundle(locales, {useIsolating: false});\n *\n * let bundle = new FluentBundle(locales, {\n * useIsolating: true,\n * functions: {\n * NODE_ENV: () => process.env.NODE_ENV\n * }\n * });\n * ```\n *\n * @param locales - Used to instantiate `Intl` formatters used by translations.\n * @param options - Optional configuration for the bundle.\n */\n constructor(locales, { functions, useIsolating = true, transform = (v) => v, } = {}) {\n /** @ignore */\n this._terms = new Map();\n /** @ignore */\n this._messages = new Map();\n this.locales = Array.isArray(locales) ? locales : [locales];\n this._functions = {\n NUMBER,\n DATETIME,\n ...functions,\n };\n this._useIsolating = useIsolating;\n this._transform = transform;\n this._intls = getMemoizerForLocale(locales);\n }\n /**\n * Check if a message is present in the bundle.\n *\n * @param id - The identifier of the message to check.\n */\n hasMessage(id) {\n return this._messages.has(id);\n }\n /**\n * Return a raw unformatted message object from the bundle.\n *\n * Raw messages are `{value, attributes}` shapes containing translation units\n * called `Patterns`. `Patterns` are implementation-specific; they should be\n * treated as black boxes and formatted with `FluentBundle.formatPattern`.\n *\n * @param id - The identifier of the message to check.\n */\n getMessage(id) {\n return this._messages.get(id);\n }\n /**\n * Add a translation resource to the bundle.\n *\n * @example\n * ```js\n * let res = new FluentResource(\"foo = Foo\");\n * bundle.addResource(res);\n * bundle.getMessage(\"foo\");\n * // → {value: .., attributes: {..}}\n * ```\n *\n * @param res\n * @param options\n */\n addResource(res, { allowOverrides = false, } = {}) {\n const errors = [];\n for (let i = 0; i < res.body.length; i++) {\n let entry = res.body[i];\n if (entry.id.startsWith(\"-\")) {\n // Identifiers starting with a dash (-) define terms. Terms are private\n // and cannot be retrieved from FluentBundle.\n if (allowOverrides === false && this._terms.has(entry.id)) {\n errors.push(new Error(`Attempt to override an existing term: \"${entry.id}\"`));\n continue;\n }\n this._terms.set(entry.id, entry);\n }\n else {\n if (allowOverrides === false && this._messages.has(entry.id)) {\n errors.push(new Error(`Attempt to override an existing message: \"${entry.id}\"`));\n continue;\n }\n this._messages.set(entry.id, entry);\n }\n }\n return errors;\n }\n /**\n * Format a `Pattern` to a string.\n *\n * Format a raw `Pattern` into a string. `args` will be used to resolve\n * references to variables passed as arguments to the translation.\n *\n * In case of errors `formatPattern` will try to salvage as much of the\n * translation as possible and will still return a string. For performance\n * reasons, the encountered errors are not returned but instead are appended\n * to the `errors` array passed as the third argument.\n *\n * If `errors` is omitted, the first encountered error will be thrown.\n *\n * @example\n * ```js\n * let errors = [];\n * bundle.addResource(\n * new FluentResource(\"hello = Hello, {$name}!\"));\n *\n * let hello = bundle.getMessage(\"hello\");\n * if (hello.value) {\n * bundle.formatPattern(hello.value, {name: \"Jane\"}, errors);\n * // Returns \"Hello, Jane!\" and `errors` is empty.\n *\n * bundle.formatPattern(hello.value, undefined, errors);\n * // Returns \"Hello, {$name}!\" and `errors` is now:\n * // []\n * }\n * ```\n */\n formatPattern(pattern, args = null, errors = null) {\n // Resolve a simple pattern without creating a scope. No error handling is\n // required; by definition simple patterns don't have placeables.\n if (typeof pattern === \"string\") {\n return this._transform(pattern);\n }\n // Resolve a complex pattern.\n let scope = new Scope(this, errors, args);\n try {\n let value = resolveComplexPattern(scope, pattern);\n return value.toString(scope);\n }\n catch (err) {\n if (scope.errors && err instanceof Error) {\n scope.errors.push(err);\n return new FluentNone().toString(scope);\n }\n throw err;\n }\n }\n}\n","// This regex is used to iterate through the beginnings of messages and terms.\n// With the /m flag, the ^ matches at the beginning of every line.\nconst RE_MESSAGE_START = /^(-?[a-zA-Z][\\w-]*) *= */gm;\n// Both Attributes and Variants are parsed in while loops. These regexes are\n// used to break out of them.\nconst RE_ATTRIBUTE_START = /\\.([a-zA-Z][\\w-]*) *= */y;\nconst RE_VARIANT_START = /\\*?\\[/y;\nconst RE_NUMBER_LITERAL = /(-?[0-9]+(?:\\.([0-9]+))?)/y;\nconst RE_IDENTIFIER = /([a-zA-Z][\\w-]*)/y;\nconst RE_REFERENCE = /([$-])?([a-zA-Z][\\w-]*)(?:\\.([a-zA-Z][\\w-]*))?/y;\nconst RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/;\n// A \"run\" is a sequence of text or string literal characters which don't\n// require any special handling. For TextElements such special characters are: {\n// (starts a placeable), and line breaks which require additional logic to check\n// if the next line is indented. For StringLiterals they are: \\ (starts an\n// escape sequence), \" (ends the literal), and line breaks which are not allowed\n// in StringLiterals. Note that string runs may be empty; text runs may not.\nconst RE_TEXT_RUN = /([^{}\\n\\r]+)/y;\nconst RE_STRING_RUN = /([^\\\\\"\\n\\r]*)/y;\n// Escape sequences.\nconst RE_STRING_ESCAPE = /\\\\([\\\\\"])/y;\nconst RE_UNICODE_ESCAPE = /\\\\u([a-fA-F0-9]{4})|\\\\U([a-fA-F0-9]{6})/y;\n// Used for trimming TextElements and indents.\nconst RE_LEADING_NEWLINES = /^\\n+/;\nconst RE_TRAILING_SPACES = / +$/;\n// Used in makeIndent to strip spaces from blank lines and normalize CRLF to LF.\nconst RE_BLANK_LINES = / *\\r?\\n/g;\n// Used in makeIndent to measure the indentation.\nconst RE_INDENT = /( *)$/;\n// Common tokens.\nconst TOKEN_BRACE_OPEN = /{\\s*/y;\nconst TOKEN_BRACE_CLOSE = /\\s*}/y;\nconst TOKEN_BRACKET_OPEN = /\\[\\s*/y;\nconst TOKEN_BRACKET_CLOSE = /\\s*] */y;\nconst TOKEN_PAREN_OPEN = /\\s*\\(\\s*/y;\nconst TOKEN_ARROW = /\\s*->\\s*/y;\nconst TOKEN_COLON = /\\s*:\\s*/y;\n// Note the optional comma. As a deviation from the Fluent EBNF, the parser\n// doesn't enforce commas between call arguments.\nconst TOKEN_COMMA = /\\s*,?\\s*/y;\nconst TOKEN_BLANK = /\\s+/y;\n/**\n * Fluent Resource is a structure storing parsed localization entries.\n */\nexport class FluentResource {\n constructor(source) {\n this.body = [];\n RE_MESSAGE_START.lastIndex = 0;\n let cursor = 0;\n // Iterate over the beginnings of messages and terms to efficiently skip\n // comments and recover from errors.\n while (true) {\n let next = RE_MESSAGE_START.exec(source);\n if (next === null) {\n break;\n }\n cursor = RE_MESSAGE_START.lastIndex;\n try {\n this.body.push(parseMessage(next[1]));\n }\n catch (err) {\n if (err instanceof SyntaxError) {\n // Don't report any Fluent syntax errors. Skip directly to the\n // beginning of the next message or term.\n continue;\n }\n throw err;\n }\n }\n // The parser implementation is inlined below for performance reasons,\n // as well as for convenience of accessing `source` and `cursor`.\n // The parser focuses on minimizing the number of false negatives at the\n // expense of increasing the risk of false positives. In other words, it\n // aims at parsing valid Fluent messages with a success rate of 100%, but it\n // may also parse a few invalid messages which the reference parser would\n // reject. The parser doesn't perform any validation and may produce entries\n // which wouldn't make sense in the real world. For best results users are\n // advised to validate translations with the fluent-syntax parser\n // pre-runtime.\n // The parser makes an extensive use of sticky regexes which can be anchored\n // to any offset of the source string without slicing it. Errors are thrown\n // to bail out of parsing of ill-formed messages.\n function test(re) {\n re.lastIndex = cursor;\n return re.test(source);\n }\n // Advance the cursor by the char if it matches. May be used as a predicate\n // (was the match found?) or, if errorClass is passed, as an assertion.\n function consumeChar(char, errorClass) {\n if (source[cursor] === char) {\n cursor++;\n return true;\n }\n if (errorClass) {\n throw new errorClass(`Expected ${char}`);\n }\n return false;\n }\n // Advance the cursor by the token if it matches. May be used as a predicate\n // (was the match found?) or, if errorClass is passed, as an assertion.\n function consumeToken(re, errorClass) {\n if (test(re)) {\n cursor = re.lastIndex;\n return true;\n }\n if (errorClass) {\n throw new errorClass(`Expected ${re.toString()}`);\n }\n return false;\n }\n // Execute a regex, advance the cursor, and return all capture groups.\n function match(re) {\n re.lastIndex = cursor;\n let result = re.exec(source);\n if (result === null) {\n throw new SyntaxError(`Expected ${re.toString()}`);\n }\n cursor = re.lastIndex;\n return result;\n }\n // Execute a regex, advance the cursor, and return the capture group.\n function match1(re) {\n return match(re)[1];\n }\n function parseMessage(id) {\n let value = parsePattern();\n let attributes = parseAttributes();\n if (value === null && Object.keys(attributes).length === 0) {\n throw new SyntaxError(\"Expected message value or attributes\");\n }\n return { id, value, attributes };\n }\n function parseAttributes() {\n let attrs = Object.create(null);\n while (test(RE_ATTRIBUTE_START)) {\n let name = match1(RE_ATTRIBUTE_START);\n let value = parsePattern();\n if (value === null) {\n throw new SyntaxError(\"Expected attribute value\");\n }\n attrs[name] = value;\n }\n return attrs;\n }\n function parsePattern() {\n let first;\n // First try to parse any simple text on the same line as the id.\n if (test(RE_TEXT_RUN)) {\n first = match1(RE_TEXT_RUN);\n }\n // If there's a placeable on the first line, parse a complex pattern.\n if (source[cursor] === \"{\" || source[cursor] === \"}\") {\n // Re-use the text parsed above, if possible.\n return parsePatternElements(first ? [first] : [], Infinity);\n }\n // RE_TEXT_VALUE stops at newlines. Only continue parsing the pattern if\n // what comes after the newline is indented.\n let indent = parseIndent();\n if (indent) {\n if (first) {\n // If there's text on the first line, the blank block is part of the\n // translation content in its entirety.\n return parsePatternElements([first, indent], indent.length);\n }\n // Otherwise, we're dealing with a block pattern, i.e. a pattern which\n // starts on a new line. Discrad the leading newlines but keep the\n // inline indent; it will be used by the dedentation logic.\n indent.value = trim(indent.value, RE_LEADING_NEWLINES);\n return parsePatternElements([indent], indent.length);\n }\n if (first) {\n // It was just a simple inline text after all.\n return trim(first, RE_TRAILING_SPACES);\n }\n return null;\n }\n // Parse a complex pattern as an array of elements.\n function parsePatternElements(elements = [], commonIndent) {\n while (true) {\n if (test(RE_TEXT_RUN)) {\n elements.push(match1(RE_TEXT_RUN));\n continue;\n }\n if (source[cursor] === \"{\") {\n elements.push(parsePlaceable());\n continue;\n }\n if (source[cursor] === \"}\") {\n throw new SyntaxError(\"Unbalanced closing brace\");\n }\n let indent = parseIndent();\n if (indent) {\n elements.push(indent);\n commonIndent = Math.min(commonIndent, indent.length);\n continue;\n }\n break;\n }\n let lastIndex = elements.length - 1;\n let lastElement = elements[lastIndex];\n // Trim the trailing spaces in the last element if it's a TextElement.\n if (typeof lastElement === \"string\") {\n elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES);\n }\n let baked = [];\n for (let element of elements) {\n if (element instanceof Indent) {\n // Dedent indented lines by the maximum common indent.\n element = element.value.slice(0, element.value.length - commonIndent);\n }\n if (element) {\n baked.push(element);\n }\n }\n return baked;\n }\n function parsePlaceable() {\n consumeToken(TOKEN_BRACE_OPEN, SyntaxError);\n let selector = parseInlineExpression();\n if (consumeToken(TOKEN_BRACE_CLOSE)) {\n return selector;\n }\n if (consumeToken(TOKEN_ARROW)) {\n let variants = parseVariants();\n consumeToken(TOKEN_BRACE_CLOSE, SyntaxError);\n return {\n type: \"select\",\n selector,\n ...variants,\n };\n }\n throw new SyntaxError(\"Unclosed placeable\");\n }\n function parseInlineExpression() {\n if (source[cursor] === \"{\") {\n // It's a nested placeable.\n return parsePlaceable();\n }\n if (test(RE_REFERENCE)) {\n let [, sigil, name, attr = null] = match(RE_REFERENCE);\n if (sigil === \"$\") {\n return { type: \"var\", name };\n }\n if (consumeToken(TOKEN_PAREN_OPEN)) {\n let args = parseArguments();\n if (sigil === \"-\") {\n // A parameterized term: -term(...).\n return { type: \"term\", name, attr, args };\n }\n if (RE_FUNCTION_NAME.test(name)) {\n return { type: \"func\", name, args };\n }\n throw new SyntaxError(\"Function names must be all upper-case\");\n }\n if (sigil === \"-\") {\n // A non-parameterized term: -term.\n return {\n type: \"term\",\n name,\n attr,\n args: [],\n };\n }\n return { type: \"mesg\", name, attr };\n }\n return parseLiteral();\n }\n function parseArguments() {\n let args = [];\n while (true) {\n switch (source[cursor]) {\n case \")\": // End of the argument list.\n cursor++;\n return args;\n case undefined: // EOF\n throw new SyntaxError(\"Unclosed argument list\");\n }\n args.push(parseArgument());\n // Commas between arguments are treated as whitespace.\n consumeToken(TOKEN_COMMA);\n }\n }\n function parseArgument() {\n let expr = parseInlineExpression();\n if (expr.type !== \"mesg\") {\n return expr;\n }\n if (consumeToken(TOKEN_COLON)) {\n // The reference is the beginning of a named argument.\n return {\n type: \"narg\",\n name: expr.name,\n value: parseLiteral(),\n };\n }\n // It's a regular message reference.\n return expr;\n }\n function parseVariants() {\n let variants = [];\n let count = 0;\n let star;\n while (test(RE_VARIANT_START)) {\n if (consumeChar(\"*\")) {\n star = count;\n }\n let key = parseVariantKey();\n let value = parsePattern();\n if (value === null) {\n throw new SyntaxError(\"Expected variant value\");\n }\n variants[count++] = { key, value };\n }\n if (count === 0) {\n return null;\n }\n if (star === undefined) {\n throw new SyntaxError(\"Expected default variant\");\n }\n return { variants, star };\n }\n function parseVariantKey() {\n consumeToken(TOKEN_BRACKET_OPEN, SyntaxError);\n let key;\n if (test(RE_NUMBER_LITERAL)) {\n key = parseNumberLiteral();\n }\n else {\n key = {\n type: \"str\",\n value: match1(RE_IDENTIFIER),\n };\n }\n consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError);\n return key;\n }\n function parseLiteral() {\n if (test(RE_NUMBER_LITERAL)) {\n return parseNumberLiteral();\n }\n if (source[cursor] === '\"') {\n return parseStringLiteral();\n }\n throw new SyntaxError(\"Invalid expression\");\n }\n function parseNumberLiteral() {\n let [, value, fraction = \"\"] = match(RE_NUMBER_LITERAL);\n let precision = fraction.length;\n return {\n type: \"num\",\n value: parseFloat(value),\n precision,\n };\n }\n function parseStringLiteral() {\n consumeChar('\"', SyntaxError);\n let value = \"\";\n while (true) {\n value += match1(RE_STRING_RUN);\n if (source[cursor] === \"\\\\\") {\n value += parseEscapeSequence();\n continue;\n }\n if (consumeChar('\"')) {\n return { type: \"str\", value };\n }\n // We've reached an EOL of EOF.\n throw new SyntaxError(\"Unclosed string literal\");\n }\n }\n // Unescape known escape sequences.\n function parseEscapeSequence() {\n if (test(RE_STRING_ESCAPE)) {\n return match1(RE_STRING_ESCAPE);\n }\n if (test(RE_UNICODE_ESCAPE)) {\n let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE);\n let codepoint = parseInt(codepoint4 || codepoint6, 16);\n return codepoint <= 0xd7ff || 0xe000 <= codepoint\n ? // It's a Unicode scalar value.\n String.fromCodePoint(codepoint)\n : // Lonely surrogates can cause trouble when the parsing result is\n // saved using UTF-8. Use U+FFFD REPLACEMENT CHARACTER instead.\n \"�\";\n }\n throw new SyntaxError(\"Unknown escape sequence\");\n }\n // Parse blank space. Return it if it looks like indent before a pattern\n // line. Skip it othwerwise.\n function parseIndent() {\n let start = cursor;\n consumeToken(TOKEN_BLANK);\n // Check the first non-blank character after the indent.\n switch (source[cursor]) {\n case \".\":\n case \"[\":\n case \"*\":\n case \"}\":\n case undefined: // EOF\n // A special character. End the Pattern.\n return false;\n case \"{\":\n // Placeables don't require indentation (in EBNF: block-placeable).\n // Continue the Pattern.\n return makeIndent(source.slice(start, cursor));\n }\n // If the first character on the line is not one of the special characters\n // listed above, it's a regular text character. Check if there's at least\n // one space of indent before it.\n if (source[cursor - 1] === \" \") {\n // It's an indented text character (in EBNF: indented-char). Continue\n // the Pattern.\n return makeIndent(source.slice(start, cursor));\n }\n // A not-indented text character is likely the identifier of the next\n // message. End the Pattern.\n return false;\n }\n // Trim blanks in text according to the given regex.\n function trim(text, re) {\n return text.replace(re, \"\");\n }\n // Normalize a blank block and extract the indent details.\n function makeIndent(blank) {\n let value = blank.replace(RE_BLANK_LINES, \"\\n\");\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n let length = RE_INDENT.exec(blank)[1].length;\n return new Indent(value, length);\n }\n }\n}\nclass Indent {\n constructor(value, length) {\n this.value = value;\n this.length = length;\n }\n}\n","/**\n * @module fluent\n * @overview\n *\n * `fluent` is a JavaScript implementation of Project Fluent, a localization\n * framework designed to unleash the expressive power of the natural language.\n *\n */\nexport { FluentBundle } from \"./bundle.js\";\nexport { FluentResource } from \"./resource.js\";\nexport { FluentType, FluentNone, FluentNumber, FluentDateTime, } from \"./types.js\";\n","/* eslint no-console: [\"error\", {allow: [\"warn\"]}] */\n/* global console */\n// Match the opening angle bracket (<) in HTML tags, and HTML entities like\n// &, &, &.\nconst reOverlay = /<|&#?\\w+;/;\n/**\n * Elements allowed in translations even if they are not present in the source\n * HTML. They are text-level elements as defined by the HTML5 spec:\n * https://www.w3.org/TR/html5/text-level-semantics.html with the exception of:\n *\n * - a - because we don't allow href on it anyways,\n * - ruby, rt, rp - because we don't allow nested elements to be inserted.\n */\nconst TEXT_LEVEL_ELEMENTS = {\n \"http://www.w3.org/1999/xhtml\": [\n \"em\",\n \"strong\",\n \"small\",\n \"s\",\n \"cite\",\n \"q\",\n \"dfn\",\n \"abbr\",\n \"data\",\n \"time\",\n \"code\",\n \"var\",\n \"samp\",\n \"kbd\",\n \"sub\",\n \"sup\",\n \"i\",\n \"b\",\n \"u\",\n \"mark\",\n \"bdi\",\n \"bdo\",\n \"span\",\n \"br\",\n \"wbr\",\n ],\n};\nconst LOCALIZABLE_ATTRIBUTES = {\n \"http://www.w3.org/1999/xhtml\": {\n global: [\"title\", \"aria-label\", \"aria-valuetext\"],\n a: [\"download\"],\n area: [\"download\", \"alt\"],\n // value is special-cased in isAttrNameLocalizable\n input: [\"alt\", \"placeholder\"],\n menuitem: [\"label\"],\n menu: [\"label\"],\n optgroup: [\"label\"],\n option: [\"label\"],\n track: [\"label\"],\n img: [\"alt\"],\n textarea: [\"placeholder\"],\n th: [\"abbr\"],\n },\n \"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul\": {\n global: [\n \"accesskey\",\n \"aria-label\",\n \"aria-valuetext\",\n \"label\",\n \"title\",\n \"tooltiptext\",\n ],\n description: [\"value\"],\n key: [\"key\", \"keycode\"],\n label: [\"value\"],\n textbox: [\"placeholder\", \"value\"],\n },\n};\n/**\n * Translate an element.\n *\n * Translate the element's text content and attributes. Some HTML markup is\n * allowed in the translation. The element's children with the data-l10n-name\n * attribute will be treated as arguments to the translation. If the\n * translation defines the same children, their attributes and text contents\n * will be used for translating the matching source child.\n *\n * @param {Element} element\n * @param {Object} translation\n * @private\n */\nexport default function translateElement(element, translation) {\n const { value } = translation;\n if (typeof value === \"string\") {\n if (element.localName === \"title\" &&\n element.namespaceURI === \"http://www.w3.org/1999/xhtml\") {\n // A special case for the HTML title element whose content must be text.\n element.textContent = value;\n }\n else if (!reOverlay.test(value)) {\n // If the translation doesn't contain any markup skip the overlay logic.\n element.textContent = value;\n }\n else {\n // Else parse the translation's HTML using an inert template element,\n // sanitize it and replace the element's content.\n const templateElement = element.ownerDocument.createElementNS(\"http://www.w3.org/1999/xhtml\", \"template\");\n templateElement.innerHTML = value;\n overlayChildNodes(templateElement.content, element);\n }\n }\n // Even if the translation doesn't define any localizable attributes, run\n // overlayAttributes to remove any localizable attributes set by previous\n // translations.\n overlayAttributes(translation, element);\n}\n/**\n * Replace child nodes of an element with child nodes of another element.\n *\n * The contents of the target element will be cleared and fully replaced with\n * sanitized contents of the source element.\n *\n * @param {DocumentFragment} fromFragment - The source of children to overlay.\n * @param {Element} toElement - The target of the overlay.\n * @private\n */\nfunction overlayChildNodes(fromFragment, toElement) {\n for (const childNode of fromFragment.childNodes) {\n if (childNode.nodeType === childNode.TEXT_NODE) {\n // Keep the translated text node.\n continue;\n }\n if (childNode.hasAttribute(\"data-l10n-name\")) {\n const sanitized = getNodeForNamedElement(toElement, childNode);\n fromFragment.replaceChild(sanitized, childNode);\n continue;\n }\n if (isElementAllowed(childNode)) {\n const sanitized = createSanitizedElement(childNode);\n fromFragment.replaceChild(sanitized, childNode);\n continue;\n }\n console.warn(`An element of forbidden type \"${childNode.localName}\" was found in ` +\n \"the translation. Only safe text-level elements and elements with \" +\n \"data-l10n-name are allowed.\");\n // If all else fails, replace the element with its text content.\n fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode);\n }\n toElement.textContent = \"\";\n toElement.appendChild(fromFragment);\n}\nfunction hasAttribute(attributes, name) {\n if (!attributes) {\n return false;\n }\n for (let attr of attributes) {\n if (attr.name === name) {\n return true;\n }\n }\n return false;\n}\n/**\n * Transplant localizable attributes of an element to another element.\n *\n * Any localizable attributes already set on the target element will be\n * cleared.\n *\n * @param {Element|Object} fromElement - The source of child nodes to overlay.\n * @param {Element} toElement - The target of the overlay.\n * @private\n */\nfunction overlayAttributes(fromElement, toElement) {\n const explicitlyAllowed = toElement.hasAttribute(\"data-l10n-attrs\")\n ? toElement\n .getAttribute(\"data-l10n-attrs\")\n .split(\",\")\n .map(i => i.trim())\n : null;\n // Remove existing localizable attributes if they\n // will not be used in the new translation.\n for (const attr of Array.from(toElement.attributes)) {\n if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) &&\n !hasAttribute(fromElement.attributes, attr.name)) {\n toElement.removeAttribute(attr.name);\n }\n }\n // fromElement might be a {value, attributes} object as returned by\n // Localization.messageFromBundle. In which case attributes may be null to\n // save GC cycles.\n if (!fromElement.attributes) {\n return;\n }\n // Set localizable attributes.\n for (const attr of Array.from(fromElement.attributes)) {\n if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) &&\n toElement.getAttribute(attr.name) !== attr.value) {\n toElement.setAttribute(attr.name, attr.value);\n }\n }\n}\n/**\n * Sanitize a child element created by the translation.\n *\n * Try to find a corresponding child in sourceElement and use it as the base\n * for the sanitization. This will preserve functional attribtues defined on\n * the child element in the source HTML.\n *\n * @param {Element} sourceElement - The source for data-l10n-name lookups.\n * @param {Element} translatedChild - The translated child to be sanitized.\n * @returns {Element}\n * @private\n */\nfunction getNodeForNamedElement(sourceElement, translatedChild) {\n const childName = translatedChild.getAttribute(\"data-l10n-name\");\n const sourceChild = sourceElement.querySelector(`[data-l10n-name=\"${childName}\"]`);\n if (!sourceChild) {\n console.warn(`An element named \"${childName}\" wasn't found in the source.`);\n return createTextNodeFromTextContent(translatedChild);\n }\n if (sourceChild.localName !== translatedChild.localName) {\n console.warn(`An element named \"${childName}\" was found in the translation ` +\n `but its type ${translatedChild.localName} didn't match the ` +\n `element found in the source (${sourceChild.localName}).`);\n return createTextNodeFromTextContent(translatedChild);\n }\n // Remove it from sourceElement so that the translation cannot use\n // the same reference name again.\n sourceElement.removeChild(sourceChild);\n // We can't currently guarantee that a translation won't remove\n // sourceChild from the element completely, which could break the app if\n // it relies on an event handler attached to the sourceChild. Let's make\n // this limitation explicit for now by breaking the identitiy of the\n // sourceChild by cloning it. This will destroy all event handlers\n // attached to sourceChild via addEventListener and via on\n // properties.\n const clone = sourceChild.cloneNode(false);\n return shallowPopulateUsing(translatedChild, clone);\n}\n/**\n * Sanitize an allowed element.\n *\n * Text-level elements allowed in translations may only use safe attributes\n * and will have any nested markup stripped to text content.\n *\n * @param {Element} element - The element to be sanitized.\n * @returns {Element}\n * @private\n */\nfunction createSanitizedElement(element) {\n // Start with an empty element of the same type to remove nested children\n // and non-localizable attributes defined by the translation.\n const clone = element.ownerDocument.createElement(element.localName);\n return shallowPopulateUsing(element, clone);\n}\n/**\n * Convert an element to a text node.\n *\n * @param {Element} element - The element to be sanitized.\n * @returns {Node}\n * @private\n */\nfunction createTextNodeFromTextContent(element) {\n return element.ownerDocument.createTextNode(element.textContent);\n}\n/**\n * Check if element is allowed in the translation.\n *\n * This method is used by the sanitizer when the translation markup contains\n * an element which is not present in the source code.\n *\n * @param {Element} element\n * @returns {boolean}\n * @private\n */\nfunction isElementAllowed(element) {\n const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI];\n return allowed && allowed.includes(element.localName);\n}\n/**\n * Check if attribute is allowed for the given element.\n *\n * This method is used by the sanitizer when the translation markup contains\n * DOM attributes, or when the translation has traits which map to DOM\n * attributes.\n *\n * `explicitlyAllowed` can be passed as a list of attributes explicitly\n * allowed on this element.\n *\n * @param {string} name\n * @param {Element} element\n * @param {Array} explicitlyAllowed\n * @returns {boolean}\n * @private\n */\nfunction isAttrNameLocalizable(name, element, explicitlyAllowed = null) {\n if (explicitlyAllowed && explicitlyAllowed.includes(name)) {\n return true;\n }\n const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI];\n if (!allowed) {\n return false;\n }\n const attrName = name.toLowerCase();\n const elemName = element.localName;\n // Is it a globally safe attribute?\n if (allowed.global.includes(attrName)) {\n return true;\n }\n // Are there no allowed attributes for this element?\n if (!allowed[elemName]) {\n return false;\n }\n // Is it allowed on this element?\n if (allowed[elemName].includes(attrName)) {\n return true;\n }\n // Special case for value on HTML inputs with type button, reset, submit\n if (element.namespaceURI === \"http://www.w3.org/1999/xhtml\" &&\n elemName === \"input\" &&\n attrName === \"value\") {\n const type = element.type.toLowerCase();\n if (type === \"submit\" || type === \"button\" || type === \"reset\") {\n return true;\n }\n }\n return false;\n}\n/**\n * Helper to set textContent and localizable attributes on an element.\n *\n * @param {Element} fromElement\n * @param {Element} toElement\n * @returns {Element}\n * @private\n */\nfunction shallowPopulateUsing(fromElement, toElement) {\n toElement.textContent = fromElement.textContent;\n overlayAttributes(fromElement, toElement);\n return toElement;\n}\n","/*\n * Base CachedIterable class.\n */\nexport default class CachedIterable extends Array {\n /**\n * Create a `CachedIterable` instance from an iterable or, if another\n * instance of `CachedIterable` is passed, return it without any\n * modifications.\n *\n * @param {Iterable} iterable\n * @returns {CachedIterable}\n */\n static from(iterable) {\n if (iterable instanceof this) {\n return iterable;\n }\n\n return new this(iterable);\n }\n}\n","import CachedIterable from \"./cached_iterable.mjs\";\n\n/*\n * CachedSyncIterable caches the elements yielded by an iterable.\n *\n * It can be used to iterate over an iterable many times without depleting the\n * iterable.\n */\nexport default class CachedSyncIterable extends CachedIterable {\n /**\n * Create an `CachedSyncIterable` instance.\n *\n * @param {Iterable} iterable\n * @returns {CachedSyncIterable}\n */\n constructor(iterable) {\n super();\n\n if (Symbol.iterator in Object(iterable)) {\n this.iterator = iterable[Symbol.iterator]();\n } else {\n throw new TypeError(\"Argument must implement the iteration protocol.\");\n }\n }\n\n [Symbol.iterator]() {\n const cached = this;\n let cur = 0;\n\n return {\n next() {\n if (cached.length <= cur) {\n cached.push(cached.iterator.next());\n }\n return cached[cur++];\n }\n };\n }\n\n /**\n * This method allows user to consume the next element from the iterator\n * into the cache.\n *\n * @param {number} count - number of elements to consume\n */\n touchNext(count = 1) {\n let idx = 0;\n while (idx++ < count) {\n const last = this[this.length - 1];\n if (last && last.done) {\n break;\n }\n this.push(this.iterator.next());\n }\n // Return the last cached {value, done} object to allow the calling\n // code to decide if it needs to call touchNext again.\n return this[this.length - 1];\n }\n}\n","import CachedIterable from \"./cached_iterable.mjs\";\n\n/*\n * CachedAsyncIterable caches the elements yielded by an async iterable.\n *\n * It can be used to iterate over an iterable many times without depleting the\n * iterable.\n */\nexport default class CachedAsyncIterable extends CachedIterable {\n /**\n * Create an `CachedAsyncIterable` instance.\n *\n * @param {Iterable} iterable\n * @returns {CachedAsyncIterable}\n */\n constructor(iterable) {\n super();\n\n if (Symbol.asyncIterator in Object(iterable)) {\n this.iterator = iterable[Symbol.asyncIterator]();\n } else if (Symbol.iterator in Object(iterable)) {\n this.iterator = iterable[Symbol.iterator]();\n } else {\n throw new TypeError(\"Argument must implement the iteration protocol.\");\n }\n }\n\n /**\n * Asynchronous iterator caching the yielded elements.\n *\n * Elements yielded by the original iterable will be cached and available\n * synchronously. Returns an async generator object implementing the\n * iterator protocol over the elements of the original (async or sync)\n * iterable.\n */\n [Symbol.asyncIterator]() {\n const cached = this;\n let cur = 0;\n\n return {\n async next() {\n if (cached.length <= cur) {\n cached.push(cached.iterator.next());\n }\n return cached[cur++];\n }\n };\n }\n\n /**\n * This method allows user to consume the next element from the iterator\n * into the cache.\n *\n * @param {number} count - number of elements to consume\n */\n async touchNext(count = 1) {\n let idx = 0;\n while (idx++ < count) {\n const last = this[this.length - 1];\n if (last && (await last).done) {\n break;\n }\n this.push(this.iterator.next());\n }\n // Return the last cached {value, done} object to allow the calling\n // code to decide if it needs to call touchNext again.\n return this[this.length - 1];\n }\n}\n","export {default as CachedSyncIterable} from \"./cached_sync_iterable.mjs\";\nexport {default as CachedAsyncIterable} from \"./cached_async_iterable.mjs\";\n","/* eslint no-console: [\"error\", { allow: [\"warn\", \"error\"] }] */\n/* global console */\nimport { CachedAsyncIterable } from \"cached-iterable\";\n/**\n * The `Localization` class is a central high-level API for vanilla\n * JavaScript use of Fluent.\n * It combines language negotiation, FluentBundle and I/O to\n * provide a scriptable API to format translations.\n */\nexport default class Localization {\n /**\n * @param {Array} resourceIds - List of resource IDs\n * @param {Function} generateBundles - Function that returns a\n * generator over FluentBundles\n *\n * @returns {Localization}\n */\n constructor(resourceIds = [], generateBundles) {\n this.resourceIds = resourceIds;\n this.generateBundles = generateBundles;\n this.onChange(true);\n }\n addResourceIds(resourceIds, eager = false) {\n this.resourceIds.push(...resourceIds);\n this.onChange(eager);\n return this.resourceIds.length;\n }\n removeResourceIds(resourceIds) {\n this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r));\n this.onChange();\n return this.resourceIds.length;\n }\n /**\n * Format translations and handle fallback if needed.\n *\n * Format translations for `keys` from `FluentBundle` instances on this\n * DOMLocalization. In case of errors, fetch the next context in the\n * fallback chain.\n *\n * @param {Array} keys - Translation keys to format.\n * @param {Function} method - Formatting function.\n * @returns {Promise>}\n * @private\n */\n async formatWithFallback(keys, method) {\n const translations = [];\n let hasAtLeastOneBundle = false;\n for await (const bundle of this.bundles) {\n hasAtLeastOneBundle = true;\n const missingIds = keysFromBundle(method, bundle, keys, translations);\n if (missingIds.size === 0) {\n break;\n }\n if (typeof console !== \"undefined\") {\n const locale = bundle.locales[0];\n const ids = Array.from(missingIds).join(\", \");\n console.warn(`[fluent] Missing translations in ${locale}: ${ids}`);\n }\n }\n if (!hasAtLeastOneBundle && typeof console !== \"undefined\") {\n // eslint-disable-next-line max-len\n console.warn(`[fluent] Request for keys failed because no resource bundles got generated.\n keys: ${JSON.stringify(keys)}.\n resourceIds: ${JSON.stringify(this.resourceIds)}.`);\n }\n return translations;\n }\n /**\n * Format translations into `{value, attributes}` objects.\n *\n * The fallback logic is the same as in `formatValues`\n * but it returns `{value, attributes}` objects\n * which are suitable for the translation of DOM elements.\n *\n * Returns a Promise resolving to an array of the translation strings.\n *\n * @example\n * ```js\n * docL10n.formatMessages([\n * {id: 'hello', args: { who: 'Mary' }},\n * {id: 'welcome'}\n * ]).then(console.log);\n *\n * // [\n * // { value: 'Hello, Mary!', attributes: null },\n * // {\n * // value: 'Welcome!',\n * // attributes: [ { name: \"title\", value: 'Hello' } ]\n * // }\n * // ]\n * ```\n *\n * @param {Array} keys\n * @returns {Promise>}\n * @private\n */\n formatMessages(keys) {\n return this.formatWithFallback(keys, messageFromBundle);\n }\n /**\n * Retrieve translations corresponding to the passed keys.\n *\n * A generalized version of `DOMLocalization.formatValue`. Keys must\n * be `{id, args}` objects.\n *\n * Returns a Promise resolving to an array of the translation strings.\n *\n * @example\n * ```js\n * docL10n.formatValues([\n * {id: 'hello', args: { who: 'Mary' }},\n * {id: 'hello', args: { who: 'John' }},\n * {id: 'welcome'}\n * ]).then(console.log);\n *\n * // ['Hello, Mary!', 'Hello, John!', 'Welcome!']\n * ```\n *\n * @param {Array} keys\n * @returns {Promise>}\n */\n formatValues(keys) {\n return this.formatWithFallback(keys, valueFromBundle);\n }\n /**\n * Retrieve the translation corresponding to the `id` identifier.\n *\n * If passed, `args` is a simple hash object with a list of variables that\n * will be interpolated in the value of the translation.\n *\n * Returns a Promise resolving to the translation string.\n *\n * Use this sparingly for one-off messages which don't need to be\n * retranslated when the user changes their language preferences, e.g. in\n * notifications.\n *\n * @example\n * ```js\n * docL10n.formatValue(\n * 'hello', { who: 'world' }\n * ).then(console.log);\n *\n * // 'Hello, world!'\n * ```\n *\n * @param {string} id - Identifier of the translation to format\n * @param {Object} [args] - Optional external arguments\n * @returns {Promise}\n */\n async formatValue(id, args) {\n const [val] = await this.formatValues([{ id, args }]);\n return val;\n }\n handleEvent() {\n this.onChange();\n }\n /**\n * This method should be called when there's a reason to believe\n * that language negotiation or available resources changed.\n */\n onChange(eager = false) {\n this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds));\n if (eager) {\n this.bundles.touchNext(2);\n }\n }\n}\n/**\n * Format the value of a message into a string or `null`.\n *\n * This function is passed as a method to `keysFromBundle` and resolve\n * a value of a single L10n Entity using provided `FluentBundle`.\n *\n * If the message doesn't have a value, return `null`.\n *\n * @param {FluentBundle} bundle\n * @param {Array} errors\n * @param {Object} message\n * @param {Object} args\n * @returns {string|null}\n * @private\n */\nfunction valueFromBundle(bundle, errors, message, args) {\n if (message.value) {\n return bundle.formatPattern(message.value, args, errors);\n }\n return null;\n}\n/**\n * Format all public values of a message into a {value, attributes} object.\n *\n * This function is passed as a method to `keysFromBundle` and resolve\n * a single L10n Entity using provided `FluentBundle`.\n *\n * The function will return an object with a value and attributes of the\n * entity.\n *\n * @param {FluentBundle} bundle\n * @param {Array} errors\n * @param {Object} message\n * @param {Object} args\n * @returns {Object}\n * @private\n */\nfunction messageFromBundle(bundle, errors, message, args) {\n const formatted = {\n value: null,\n attributes: null,\n };\n if (message.value) {\n formatted.value = bundle.formatPattern(message.value, args, errors);\n }\n let attrNames = Object.keys(message.attributes);\n if (attrNames.length > 0) {\n formatted.attributes = new Array(attrNames.length);\n for (let [i, name] of attrNames.entries()) {\n let value = bundle.formatPattern(message.attributes[name], args, errors);\n formatted.attributes[i] = { name, value };\n }\n }\n return formatted;\n}\n/**\n * This function is an inner function for `Localization.formatWithFallback`.\n *\n * It takes a `FluentBundle`, list of l10n-ids and a method to be used for\n * key resolution (either `valueFromBundle` or `messageFromBundle`) and\n * optionally a value returned from `keysFromBundle` executed against\n * another `FluentBundle`.\n *\n * The idea here is that if the previous `FluentBundle` did not resolve\n * all keys, we're calling this function with the next context to resolve\n * the remaining ones.\n *\n * In the function, we loop over `keys` and check if we have the `prev`\n * passed and if it has an error entry for the position we're in.\n *\n * If it doesn't, it means that we have a good translation for this key and\n * we return it. If it does, we'll try to resolve the key using the passed\n * `FluentBundle`.\n *\n * In the end, we fill the translations array, and return the Set with\n * missing ids.\n *\n * See `Localization.formatWithFallback` for more info on how this is used.\n *\n * @param {Function} method\n * @param {FluentBundle} bundle\n * @param {Array} keys\n * @param {{Array<{value: string, attributes: Object}>}} translations\n *\n * @returns {Set}\n * @private\n */\nfunction keysFromBundle(method, bundle, keys, translations) {\n const messageErrors = [];\n const missingIds = new Set();\n keys.forEach(({ id, args }, i) => {\n if (translations[i] !== undefined) {\n return;\n }\n let message = bundle.getMessage(id);\n if (message) {\n messageErrors.length = 0;\n translations[i] = method(bundle, messageErrors, message, args);\n if (messageErrors.length > 0 && typeof console !== \"undefined\") {\n const locale = bundle.locales[0];\n const errors = messageErrors.join(\", \");\n // eslint-disable-next-line max-len\n console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`);\n }\n }\n else {\n missingIds.add(id);\n }\n });\n return missingIds;\n}\n","import translateElement from \"./overlay.js\";\nimport Localization from \"./localization.js\";\nconst L10NID_ATTR_NAME = \"data-l10n-id\";\nconst L10NARGS_ATTR_NAME = \"data-l10n-args\";\nconst L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`;\n/**\n * The `DOMLocalization` class is responsible for fetching resources and\n * formatting translations.\n *\n * It implements the fallback strategy in case of errors encountered during the\n * formatting of translations and methods for observing DOM\n * trees with a `MutationObserver`.\n */\nexport default class DOMLocalization extends Localization {\n /**\n * @param {Array} resourceIds - List of resource IDs\n * @param {Function} generateBundles - Function that returns a\n * generator over FluentBundles\n * @returns {DOMLocalization}\n */\n constructor(resourceIds, generateBundles) {\n super(resourceIds, generateBundles);\n // A Set of DOM trees observed by the `MutationObserver`.\n this.roots = new Set();\n // requestAnimationFrame handler.\n this.pendingrAF = null;\n // list of elements pending for translation.\n this.pendingElements = new Set();\n this.windowElement = null;\n this.mutationObserver = null;\n this.observerConfig = {\n attributes: true,\n characterData: false,\n childList: true,\n subtree: true,\n attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME],\n };\n }\n onChange(eager = false) {\n super.onChange(eager);\n if (this.roots) {\n this.translateRoots();\n }\n }\n /**\n * Set the `data-l10n-id` and `data-l10n-args` attributes on DOM elements.\n * FluentDOM makes use of mutation observers to detect changes\n * to `data-l10n-*` attributes and translate elements asynchronously.\n * `setAttributes` is a convenience method which allows to translate\n * DOM elements declaratively.\n *\n * You should always prefer to use `data-l10n-id` on elements (statically in\n * HTML or dynamically via `setAttributes`) over manually retrieving\n * translations with `format`. The use of attributes ensures that the\n * elements can be retranslated when the user changes their language\n * preferences.\n *\n * ```javascript\n * localization.setAttributes(\n * document.querySelector('#welcome'), 'hello', { who: 'world' }\n * );\n * ```\n *\n * This will set the following attributes on the `#welcome` element.\n * The MutationObserver will pick up this change and will localize the element\n * asynchronously.\n *\n * ```html\n *

    \n *

    \n * ```\n *\n * @param {Element} element - Element to set attributes on\n * @param {string} id - l10n-id string\n * @param {Object} args - KVP list of l10n arguments\n * @returns {Element}\n */\n setAttributes(element, id, args) {\n element.setAttribute(L10NID_ATTR_NAME, id);\n if (args) {\n element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args));\n }\n else {\n element.removeAttribute(L10NARGS_ATTR_NAME);\n }\n return element;\n }\n /**\n * Get the `data-l10n-*` attributes from DOM elements.\n *\n * ```javascript\n * localization.getAttributes(\n * document.querySelector('#welcome')\n * );\n * // -> { id: 'hello', args: { who: 'world' } }\n * ```\n *\n * @param {Element} element - HTML element\n * @returns {{id: string, args: Object}}\n */\n getAttributes(element) {\n return {\n id: element.getAttribute(L10NID_ATTR_NAME),\n args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null),\n };\n }\n /**\n * Add `newRoot` to the list of roots managed by this `DOMLocalization`.\n *\n * Additionally, if this `DOMLocalization` has an observer, start observing\n * `newRoot` in order to translate mutations in it.\n *\n * @param {Element} newRoot - Root to observe.\n */\n connectRoot(newRoot) {\n for (const root of this.roots) {\n if (root === newRoot ||\n root.contains(newRoot) ||\n newRoot.contains(root)) {\n throw new Error(\"Cannot add a root that overlaps with existing root.\");\n }\n }\n if (this.windowElement) {\n if (this.windowElement !== newRoot.ownerDocument.defaultView) {\n throw new Error(`Cannot connect a root:\n DOMLocalization already has a root from a different window.`);\n }\n }\n else {\n this.windowElement = newRoot.ownerDocument.defaultView;\n this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations));\n }\n this.roots.add(newRoot);\n this.mutationObserver.observe(newRoot, this.observerConfig);\n }\n /**\n * Remove `root` from the list of roots managed by this `DOMLocalization`.\n *\n * Additionally, if this `DOMLocalization` has an observer, stop observing\n * `root`.\n *\n * Returns `true` if the root was the last one managed by this\n * `DOMLocalization`.\n *\n * @param {Element} root - Root to disconnect.\n * @returns {boolean}\n */\n disconnectRoot(root) {\n this.roots.delete(root);\n // Pause the mutation observer to stop observing `root`.\n this.pauseObserving();\n if (this.roots.size === 0) {\n this.mutationObserver = null;\n if (this.windowElement && this.pendingrAF) {\n this.windowElement.cancelAnimationFrame(this.pendingrAF);\n }\n this.windowElement = null;\n this.pendingrAF = null;\n this.pendingElements.clear();\n return true;\n }\n // Resume observing all other roots.\n this.resumeObserving();\n return false;\n }\n /**\n * Translate all roots associated with this `DOMLocalization`.\n *\n * @returns {Promise}\n */\n translateRoots() {\n const roots = Array.from(this.roots);\n return Promise.all(roots.map(root => this.translateFragment(root)));\n }\n /**\n * Pauses the `MutationObserver`.\n */\n pauseObserving() {\n if (!this.mutationObserver) {\n return;\n }\n this.translateMutations(this.mutationObserver.takeRecords());\n this.mutationObserver.disconnect();\n }\n /**\n * Resumes the `MutationObserver`.\n */\n resumeObserving() {\n if (!this.mutationObserver) {\n return;\n }\n for (const root of this.roots) {\n this.mutationObserver.observe(root, this.observerConfig);\n }\n }\n /**\n * Translate mutations detected by the `MutationObserver`.\n *\n * @private\n */\n translateMutations(mutations) {\n for (const mutation of mutations) {\n switch (mutation.type) {\n case \"attributes\":\n if (mutation.target.hasAttribute(\"data-l10n-id\")) {\n this.pendingElements.add(mutation.target);\n }\n break;\n case \"childList\":\n for (const addedNode of mutation.addedNodes) {\n if (addedNode.nodeType === addedNode.ELEMENT_NODE) {\n if (addedNode.childElementCount) {\n for (const element of this.getTranslatables(addedNode)) {\n this.pendingElements.add(element);\n }\n }\n else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) {\n this.pendingElements.add(addedNode);\n }\n }\n }\n break;\n }\n }\n // This fragment allows us to coalesce all pending translations\n // into a single requestAnimationFrame.\n if (this.pendingElements.size > 0) {\n if (this.pendingrAF === null) {\n this.pendingrAF = this.windowElement.requestAnimationFrame(() => {\n this.translateElements(Array.from(this.pendingElements));\n this.pendingElements.clear();\n this.pendingrAF = null;\n });\n }\n }\n }\n /**\n * Translate a DOM element or fragment asynchronously using this\n * `DOMLocalization` object.\n *\n * Manually trigger the translation (or re-translation) of a DOM fragment.\n * Use the `data-l10n-id` and `data-l10n-args` attributes to mark up the DOM\n * with information about which translations to use.\n *\n * Returns a `Promise` that gets resolved once the translation is complete.\n *\n * @param {DOMFragment} frag - Element or DocumentFragment to be translated\n * @returns {Promise}\n */\n translateFragment(frag) {\n return this.translateElements(this.getTranslatables(frag));\n }\n /**\n * Translate a list of DOM elements asynchronously using this\n * `DOMLocalization` object.\n *\n * Manually trigger the translation (or re-translation) of a list of elements.\n * Use the `data-l10n-id` and `data-l10n-args` attributes to mark up the DOM\n * with information about which translations to use.\n *\n * Returns a `Promise` that gets resolved once the translation is complete.\n *\n * @param {Array} elements - List of elements to be translated\n * @returns {Promise}\n */\n async translateElements(elements) {\n if (!elements.length) {\n return undefined;\n }\n const keys = elements.map(this.getKeysForElement);\n const translations = await this.formatMessages(keys);\n return this.applyTranslations(elements, translations);\n }\n /**\n * Applies translations onto elements.\n *\n * @param {Array} elements\n * @param {Array} translations\n * @private\n */\n applyTranslations(elements, translations) {\n this.pauseObserving();\n for (let i = 0; i < elements.length; i++) {\n if (translations[i] !== undefined) {\n translateElement(elements[i], translations[i]);\n }\n }\n this.resumeObserving();\n }\n /**\n * Collects all translatable child elements of the element.\n *\n * @param {Element} element\n * @returns {Array}\n * @private\n */\n getTranslatables(element) {\n const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY));\n if (typeof element.hasAttribute === \"function\" &&\n element.hasAttribute(L10NID_ATTR_NAME)) {\n nodes.push(element);\n }\n return nodes;\n }\n /**\n * Get the `data-l10n-*` attributes from DOM elements as a two-element\n * array.\n *\n * @param {Element} element\n * @returns {Object}\n * @private\n */\n getKeysForElement(element) {\n return {\n id: element.getAttribute(L10NID_ATTR_NAME),\n args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null),\n };\n }\n}\n","export { default as DOMLocalization } from \"./dom_localization.js\";\nexport { default as Localization } from \"./localization.js\";\n","/* Copyright 2023 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./interfaces\").IL10n} IL10n */\n\n/**\n * NOTE: The L10n-implementations should use lowercase language-codes\n * internally.\n * @implements {IL10n}\n */\nclass L10n {\n #dir;\n\n #elements;\n\n #lang;\n\n #l10n;\n\n constructor({ lang, isRTL }, l10n = null) {\n this.#lang = L10n.#fixupLangCode(lang);\n this.#l10n = l10n;\n this.#dir = (isRTL ?? L10n.#isRTL(this.#lang)) ? \"rtl\" : \"ltr\";\n }\n\n _setL10n(l10n) {\n this.#l10n = l10n;\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\")) {\n document.l10n = l10n;\n }\n }\n\n /** @inheritdoc */\n getLanguage() {\n return this.#lang;\n }\n\n /** @inheritdoc */\n getDirection() {\n return this.#dir;\n }\n\n /** @inheritdoc */\n async get(ids, args = null, fallback) {\n if (Array.isArray(ids)) {\n ids = ids.map(id => ({ id }));\n const messages = await this.#l10n.formatMessages(ids);\n return messages.map(message => message.value);\n }\n\n const messages = await this.#l10n.formatMessages([\n {\n id: ids,\n args,\n },\n ]);\n return messages[0]?.value || fallback;\n }\n\n /** @inheritdoc */\n async translate(element) {\n (this.#elements ||= new Set()).add(element);\n try {\n this.#l10n.connectRoot(element);\n await this.#l10n.translateRoots();\n } catch {\n // Element is under an existing root, so there is no need to add it again.\n }\n }\n\n /** @inheritdoc */\n async translateOnce(element) {\n try {\n await this.#l10n.translateElements([element]);\n } catch (ex) {\n console.error(\"translateOnce:\", ex);\n }\n }\n\n /** @inheritdoc */\n async destroy() {\n if (this.#elements) {\n for (const element of this.#elements) {\n this.#l10n.disconnectRoot(element);\n }\n this.#elements.clear();\n this.#elements = null;\n }\n this.#l10n.pauseObserving();\n }\n\n /** @inheritdoc */\n pause() {\n this.#l10n.pauseObserving();\n }\n\n /** @inheritdoc */\n resume() {\n this.#l10n.resumeObserving();\n }\n\n static #fixupLangCode(langCode) {\n // Use only lowercase language-codes internally, and fallback to English.\n langCode = langCode?.toLowerCase() || \"en-us\";\n\n // Try to support \"incompletely\" specified language codes (see issue 13689).\n const PARTIAL_LANG_CODES = {\n en: \"en-us\",\n es: \"es-es\",\n fy: \"fy-nl\",\n ga: \"ga-ie\",\n gu: \"gu-in\",\n hi: \"hi-in\",\n hy: \"hy-am\",\n nb: \"nb-no\",\n ne: \"ne-np\",\n nn: \"nn-no\",\n pa: \"pa-in\",\n pt: \"pt-pt\",\n sv: \"sv-se\",\n zh: \"zh-cn\",\n };\n return PARTIAL_LANG_CODES[langCode] || langCode;\n }\n\n static #isRTL(lang) {\n const shortCode = lang.split(\"-\", 1)[0];\n return [\"ar\", \"he\", \"fa\", \"ps\", \"ur\"].includes(shortCode);\n }\n}\n\nconst GenericL10n = null;\n\nexport { GenericL10n, L10n };\n","/* Copyright 2017 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./interfaces\").IL10n} IL10n */\n\nimport { FluentBundle, FluentResource } from \"fluent-bundle\";\nimport { DOMLocalization } from \"fluent-dom\";\nimport { fetchData } from \"pdfjs-lib\";\nimport { L10n } from \"./l10n.js\";\n\nfunction createBundle(lang, text) {\n const resource = new FluentResource(text);\n const bundle = new FluentBundle(lang);\n const errors = bundle.addResource(resource);\n if (errors.length) {\n console.error(\"L10n errors\", errors);\n }\n return bundle;\n}\n\n/**\n * @implements {IL10n}\n */\nclass GenericL10n extends L10n {\n constructor(lang) {\n super({ lang });\n\n const generateBundles = !lang\n ? GenericL10n.#generateBundlesFallback.bind(\n GenericL10n,\n this.getLanguage()\n )\n : GenericL10n.#generateBundles.bind(\n GenericL10n,\n \"en-us\",\n this.getLanguage()\n );\n this._setL10n(new DOMLocalization([], generateBundles));\n }\n\n /**\n * Generate the bundles for Fluent.\n * @param {String} defaultLang - The fallback language to use for\n * translations.\n * @param {String} baseLang - The base language to use for translations.\n */\n static async *#generateBundles(defaultLang, baseLang) {\n const { baseURL, paths } = await this.#getPaths();\n\n const langs = [baseLang];\n if (defaultLang !== baseLang) {\n // Also fallback to the short-format of the base language\n // (see issue 17269).\n const shortLang = baseLang.split(\"-\", 1)[0];\n\n if (shortLang !== baseLang) {\n langs.push(shortLang);\n }\n langs.push(defaultLang);\n }\n for (const lang of langs) {\n const bundle = await this.#createBundle(lang, baseURL, paths);\n if (bundle) {\n yield bundle;\n } else if (lang === \"en-us\") {\n yield this.#createBundleFallback(lang);\n }\n }\n }\n\n static async #createBundle(lang, baseURL, paths) {\n const path = paths[lang];\n if (!path) {\n return null;\n }\n const url = new URL(path, baseURL);\n const text = await fetchData(url, /* type = */ \"text\");\n\n return createBundle(lang, text);\n }\n\n static async #getPaths() {\n try {\n const { href } = document.querySelector(`link[type=\"application/l10n\"]`);\n const paths = await fetchData(href, /* type = */ \"json\");\n\n return { baseURL: href.replace(/[^/]*$/, \"\") || \"./\", paths };\n } catch {}\n return { baseURL: \"./\", paths: Object.create(null) };\n }\n\n static async *#generateBundlesFallback(lang) {\n yield this.#createBundleFallback(lang);\n }\n\n static async #createBundleFallback(lang) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\")) {\n throw new Error(\"Not implemented: #createBundleFallback\");\n }\n const text =\n typeof PDFJSDev === \"undefined\"\n ? await fetchData(\n new URL(\"../l10n/en-US/viewer.ftl\", window.location.href),\n /* type = */ \"text\"\n )\n : PDFJSDev.eval(\"DEFAULT_FTL\");\n\n return createBundle(lang, text);\n }\n}\n\nexport { GenericL10n };\n","/* Copyright 2020 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getPdfFilenameFromUrl } from \"pdfjs-lib\";\n\nasync function docProperties(pdfDocument) {\n const url = \"\",\n baseUrl = url.split(\"#\", 1)[0];\n // eslint-disable-next-line prefer-const\n let { info, metadata, contentDispositionFilename, contentLength } =\n await pdfDocument.getMetadata();\n\n if (!contentLength) {\n const { length } = await pdfDocument.getDownloadInfo();\n contentLength = length;\n }\n\n return {\n ...info,\n baseURL: baseUrl,\n filesize: contentLength,\n filename: contentDispositionFilename || getPdfFilenameFromUrl(url),\n metadata: metadata?.getRaw(),\n authors: metadata?.get(\"dc:creator\"),\n numPages: pdfDocument.numPages,\n URL: url,\n };\n}\n\nclass GenericScripting {\n constructor(sandboxBundleSrc) {\n this._ready = new Promise((resolve, reject) => {\n const sandbox =\n typeof PDFJSDev === \"undefined\"\n ? import(sandboxBundleSrc) // eslint-disable-line no-unsanitized/method\n : __non_webpack_import__(sandboxBundleSrc);\n sandbox\n .then(pdfjsSandbox => {\n resolve(pdfjsSandbox.QuickJSSandbox());\n })\n .catch(reject);\n });\n }\n\n async createSandbox(data) {\n const sandbox = await this._ready;\n sandbox.create(data);\n }\n\n async dispatchEventInSandbox(event) {\n const sandbox = await this._ready;\n setTimeout(() => sandbox.dispatchEvent(event), 0);\n }\n\n async destroySandbox() {\n const sandbox = await this._ready;\n sandbox.nukeSandbox();\n }\n}\n\nexport { docProperties, GenericScripting };\n","/* Copyright 2017 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppOptions } from \"./app_options.js\";\nimport { BaseExternalServices } from \"./external_services.js\";\nimport { BasePreferences } from \"./preferences.js\";\nimport { GenericL10n } from \"./genericl10n.js\";\nimport { GenericScripting } from \"./generic_scripting.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"GENERIC\")) {\n throw new Error(\n 'Module \"pdfjs-web/genericcom\" shall not be used outside GENERIC build.'\n );\n}\n\nfunction initCom(app) {}\n\nclass Preferences extends BasePreferences {\n async _writeToStorage(prefObj) {\n localStorage.setItem(\"pdfjs.preferences\", JSON.stringify(prefObj));\n }\n\n async _readFromStorage(prefObj) {\n return { prefs: JSON.parse(localStorage.getItem(\"pdfjs.preferences\")) };\n }\n}\n\nclass ExternalServices extends BaseExternalServices {\n async createL10n() {\n return new GenericL10n(AppOptions.get(\"localeProperties\")?.lang);\n }\n\n createScripting() {\n return new GenericScripting(AppOptions.get(\"sandboxBundleSrc\"));\n }\n}\n\nclass MLManager {\n async isEnabledFor(_name) {\n return false;\n }\n\n async deleteModel(_service) {\n return null;\n }\n\n isReady(_name) {\n return false;\n }\n\n guess(_data) {}\n\n toggleService(_name, _enabled) {}\n\n static getFakeMLManager(options) {\n return new FakeMLManager(options);\n }\n}\n\nclass FakeMLManager {\n eventBus = null;\n\n hasProgress = false;\n\n constructor({ enableGuessAltText, enableAltTextModelDownload }) {\n this.enableGuessAltText = enableGuessAltText;\n this.enableAltTextModelDownload = enableAltTextModelDownload;\n }\n\n setEventBus(eventBus, abortSignal) {\n this.eventBus = eventBus;\n }\n\n async isEnabledFor(_name) {\n return this.enableGuessAltText;\n }\n\n async deleteModel(_name) {\n this.enableAltTextModelDownload = false;\n return null;\n }\n\n async loadModel(_name) {}\n\n async downloadModel(_name) {\n // Simulate downloading the model but with progress.\n // The progress can be seen in the new alt-text dialog.\n this.hasProgress = true;\n\n const { promise, resolve } = Promise.withResolvers();\n const total = 1e8;\n const end = 1.5 * total;\n const increment = 5e6;\n let loaded = 0;\n const id = setInterval(() => {\n loaded += increment;\n if (loaded <= end) {\n this.eventBus.dispatch(\"loadaiengineprogress\", {\n source: this,\n detail: {\n total,\n totalLoaded: loaded,\n finished: loaded + increment >= end,\n },\n });\n return;\n }\n clearInterval(id);\n this.hasProgress = false;\n this.enableAltTextModelDownload = true;\n resolve(true);\n }, 900);\n return promise;\n }\n\n isReady(_name) {\n return this.enableAltTextModelDownload;\n }\n\n guess({ request: { data } }) {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve(data ? { output: \"Fake alt text.\" } : { error: true });\n }, 3000);\n });\n }\n\n toggleService(_name, enabled) {\n this.enableGuessAltText = enabled;\n }\n}\n\nexport { ExternalServices, initCom, MLManager, Preferences };\n","/* Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { noContextMenu } from \"pdfjs-lib\";\n\nclass NewAltTextManager {\n #boundCancel = this.#cancel.bind(this);\n\n #createAutomaticallyButton;\n\n #currentEditor = null;\n\n #cancelButton;\n\n #descriptionContainer;\n\n #dialog;\n\n #disclaimer;\n\n #downloadModel;\n\n #downloadModelDescription;\n\n #eventBus;\n\n #firstTime = false;\n\n #guessedAltText;\n\n #hasAI = null;\n\n #isEditing = null;\n\n #imagePreview;\n\n #imageData;\n\n #isAILoading = false;\n\n #wasAILoading = false;\n\n #learnMore;\n\n #notNowButton;\n\n #overlayManager;\n\n #textarea;\n\n #title;\n\n #uiManager;\n\n #previousAltText = null;\n\n constructor(\n {\n descriptionContainer,\n dialog,\n imagePreview,\n cancelButton,\n disclaimer,\n notNowButton,\n saveButton,\n textarea,\n learnMore,\n errorCloseButton,\n createAutomaticallyButton,\n downloadModel,\n downloadModelDescription,\n title,\n },\n overlayManager,\n eventBus\n ) {\n this.#cancelButton = cancelButton;\n this.#createAutomaticallyButton = createAutomaticallyButton;\n this.#descriptionContainer = descriptionContainer;\n this.#dialog = dialog;\n this.#disclaimer = disclaimer;\n this.#notNowButton = notNowButton;\n this.#imagePreview = imagePreview;\n this.#textarea = textarea;\n this.#learnMore = learnMore;\n this.#title = title;\n this.#downloadModel = downloadModel;\n this.#downloadModelDescription = downloadModelDescription;\n this.#overlayManager = overlayManager;\n this.#eventBus = eventBus;\n\n dialog.addEventListener(\"close\", this.#close.bind(this));\n dialog.addEventListener(\"contextmenu\", event => {\n if (event.target !== this.#textarea) {\n event.preventDefault();\n }\n });\n cancelButton.addEventListener(\"click\", this.#boundCancel);\n notNowButton.addEventListener(\"click\", this.#boundCancel);\n saveButton.addEventListener(\"click\", this.#save.bind(this));\n errorCloseButton.addEventListener(\"click\", () => {\n this.#toggleError(false);\n });\n createAutomaticallyButton.addEventListener(\"click\", async () => {\n const checked =\n createAutomaticallyButton.getAttribute(\"aria-pressed\") !== \"true\";\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.ai_generation_check\",\n data: { status: checked },\n });\n\n if (this.#uiManager) {\n this.#uiManager.setPreference(\"enableGuessAltText\", checked);\n await this.#uiManager.mlManager.toggleService(\"altText\", checked);\n }\n this.#toggleGuessAltText(checked, /* isInitial = */ false);\n });\n textarea.addEventListener(\"focus\", () => {\n this.#wasAILoading = this.#isAILoading;\n this.#toggleLoading(false);\n this.#toggleTitleAndDisclaimer();\n });\n textarea.addEventListener(\"blur\", () => {\n if (!textarea.value) {\n this.#toggleLoading(this.#wasAILoading);\n }\n this.#toggleTitleAndDisclaimer();\n });\n textarea.addEventListener(\"input\", () => {\n this.#toggleTitleAndDisclaimer();\n });\n\n eventBus._on(\"enableguessalttext\", ({ value }) => {\n this.#toggleGuessAltText(value, /* isInitial = */ false);\n });\n\n this.#overlayManager.register(dialog);\n\n this.#learnMore.addEventListener(\"click\", () => {\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.info\",\n data: { topic: \"alt_text\" },\n });\n });\n }\n\n #toggleLoading(value) {\n if (!this.#uiManager || this.#isAILoading === value) {\n return;\n }\n this.#isAILoading = value;\n this.#descriptionContainer.classList.toggle(\"loading\", value);\n }\n\n #toggleError(value) {\n if (!this.#uiManager) {\n return;\n }\n this.#dialog.classList.toggle(\"error\", value);\n }\n\n async #toggleGuessAltText(value, isInitial = false) {\n if (!this.#uiManager) {\n return;\n }\n this.#dialog.classList.toggle(\"aiDisabled\", !value);\n this.#createAutomaticallyButton.setAttribute(\"aria-pressed\", value);\n\n if (value) {\n const { altTextLearnMoreUrl } = this.#uiManager.mlManager;\n if (altTextLearnMoreUrl) {\n this.#learnMore.href = altTextLearnMoreUrl;\n }\n this.#mlGuessAltText(isInitial);\n } else {\n this.#toggleLoading(false);\n this.#isAILoading = false;\n this.#toggleTitleAndDisclaimer();\n }\n }\n\n #toggleNotNow() {\n this.#notNowButton.classList.toggle(\"hidden\", !this.#firstTime);\n this.#cancelButton.classList.toggle(\"hidden\", this.#firstTime);\n }\n\n #toggleAI(value) {\n if (!this.#uiManager || this.#hasAI === value) {\n return;\n }\n this.#hasAI = value;\n this.#dialog.classList.toggle(\"noAi\", !value);\n this.#toggleTitleAndDisclaimer();\n }\n\n #toggleTitleAndDisclaimer() {\n // Disclaimer is visible when the AI is loading or the user didn't change\n // the guessed alt text.\n const visible =\n this.#isAILoading ||\n (this.#guessedAltText && this.#guessedAltText === this.#textarea.value);\n this.#disclaimer.hidden = !visible;\n\n // The title changes depending if the text area is empty or not.\n const isEditing = this.#isAILoading || !!this.#textarea.value;\n if (this.#isEditing === isEditing) {\n return;\n }\n this.#isEditing = isEditing;\n this.#title.setAttribute(\n \"data-l10n-id\",\n isEditing\n ? \"pdfjs-editor-new-alt-text-dialog-edit-label\"\n : \"pdfjs-editor-new-alt-text-dialog-add-label\"\n );\n }\n\n async #mlGuessAltText(isInitial) {\n if (this.#isAILoading) {\n // We're still loading the previous guess.\n return;\n }\n\n if (this.#textarea.value) {\n // The user has already set an alt text.\n return;\n }\n\n if (isInitial && this.#previousAltText !== null) {\n // The user has already set an alt text (empty or not).\n return;\n }\n\n this.#guessedAltText = this.#currentEditor.guessedAltText;\n if (this.#previousAltText === null && this.#guessedAltText) {\n // We have a guessed alt text and the user didn't change it.\n this.#addAltText(this.#guessedAltText);\n return;\n }\n\n this.#toggleLoading(true);\n this.#toggleTitleAndDisclaimer();\n\n let hasError = false;\n try {\n // When calling #mlGuessAltText we don't wait for it, so we must take care\n // that the alt text dialog can have been closed before the response is.\n\n const altText = await this.#currentEditor.mlGuessAltText(\n this.#imageData,\n /* updateAltTextData = */ false\n );\n if (altText) {\n this.#guessedAltText = altText;\n this.#wasAILoading = this.#isAILoading;\n if (this.#isAILoading) {\n this.#addAltText(altText);\n }\n }\n } catch (e) {\n console.error(e);\n hasError = true;\n }\n\n this.#toggleLoading(false);\n this.#toggleTitleAndDisclaimer();\n\n if (hasError && this.#uiManager) {\n this.#toggleError(true);\n }\n }\n\n #addAltText(altText) {\n if (!this.#uiManager || this.#textarea.value) {\n return;\n }\n this.#textarea.value = altText;\n this.#toggleTitleAndDisclaimer();\n }\n\n #setProgress() {\n // Show the download model progress.\n this.#downloadModel.classList.toggle(\"hidden\", false);\n\n const callback = async ({ detail: { finished, total, totalLoaded } }) => {\n const ONE_MEGA_BYTES = 1e6;\n // totalLoaded can be greater than total if the download is compressed.\n // So we cheat to avoid any confusion.\n totalLoaded = Math.min(0.99 * total, totalLoaded);\n\n // Update the progress.\n const totalSize = (this.#downloadModelDescription.ariaValueMax =\n Math.round(total / ONE_MEGA_BYTES));\n const downloadedSize = (this.#downloadModelDescription.ariaValueNow =\n Math.round(totalLoaded / ONE_MEGA_BYTES));\n this.#downloadModelDescription.setAttribute(\n \"data-l10n-args\",\n JSON.stringify({ totalSize, downloadedSize })\n );\n if (!finished) {\n return;\n }\n\n // We're done, remove the listener and hide the download model progress.\n this.#eventBus._off(\"loadaiengineprogress\", callback);\n this.#downloadModel.classList.toggle(\"hidden\", true);\n\n this.#toggleAI(true);\n if (!this.#uiManager) {\n return;\n }\n const { mlManager } = this.#uiManager;\n\n // The model has been downloaded, we can now enable the AI service.\n mlManager.toggleService(\"altText\", true);\n this.#toggleGuessAltText(\n await mlManager.isEnabledFor(\"altText\"),\n /* isInitial = */ true\n );\n };\n this.#eventBus._on(\"loadaiengineprogress\", callback);\n }\n\n async editAltText(uiManager, editor, firstTime) {\n if (this.#currentEditor || !editor) {\n return;\n }\n\n if (firstTime && editor.hasAltTextData()) {\n editor.altTextFinish();\n return;\n }\n\n this.#firstTime = firstTime;\n let { mlManager } = uiManager;\n let hasAI = !!mlManager;\n this.#toggleTitleAndDisclaimer();\n\n if (mlManager && !mlManager.isReady(\"altText\")) {\n hasAI = false;\n if (mlManager.hasProgress) {\n this.#setProgress();\n } else {\n mlManager = null;\n }\n } else {\n this.#downloadModel.classList.toggle(\"hidden\", true);\n }\n\n const isAltTextEnabledPromise = mlManager?.isEnabledFor(\"altText\");\n\n this.#currentEditor = editor;\n this.#uiManager = uiManager;\n this.#uiManager.removeEditListeners();\n\n ({ altText: this.#previousAltText } = editor.altTextData);\n this.#textarea.value = this.#previousAltText ?? \"\";\n\n // TODO: get this value from Firefox\n // (https://bugzilla.mozilla.org/show_bug.cgi?id=1908184)\n const AI_MAX_IMAGE_DIMENSION = 224;\n const MAX_PREVIEW_DIMENSION = 180;\n\n // The max dimension of the preview in the dialog is 180px, so we keep 224px\n // and rescale it thanks to css.\n\n let canvas, width, height;\n if (mlManager) {\n ({\n canvas,\n width,\n height,\n imageData: this.#imageData,\n } = editor.copyCanvas(\n AI_MAX_IMAGE_DIMENSION,\n MAX_PREVIEW_DIMENSION,\n /* createImageData = */ true\n ));\n if (hasAI) {\n this.#toggleGuessAltText(\n await isAltTextEnabledPromise,\n /* isInitial = */ true\n );\n }\n } else {\n ({ canvas, width, height } = editor.copyCanvas(\n AI_MAX_IMAGE_DIMENSION,\n MAX_PREVIEW_DIMENSION,\n /* createImageData = */ false\n ));\n }\n\n canvas.setAttribute(\"role\", \"presentation\");\n const { style } = canvas;\n style.width = `${width}px`;\n style.height = `${height}px`;\n this.#imagePreview.append(canvas);\n\n this.#toggleNotNow();\n this.#toggleAI(hasAI);\n this.#toggleError(false);\n\n try {\n await this.#overlayManager.open(this.#dialog);\n } catch (ex) {\n this.#close();\n throw ex;\n }\n }\n\n #cancel() {\n this.#currentEditor.altTextData = {\n cancel: true,\n };\n const altText = this.#textarea.value.trim();\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.dismiss\",\n data: {\n alt_text_type: altText ? \"present\" : \"empty\",\n flow: this.#firstTime ? \"image_add\" : \"alt_text_edit\",\n },\n });\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.image_added\",\n data: { alt_text_modal: true, alt_text_type: \"skipped\" },\n });\n this.#finish();\n }\n\n #finish() {\n if (this.#overlayManager.active === this.#dialog) {\n this.#overlayManager.close(this.#dialog);\n }\n }\n\n #close() {\n const canvas = this.#imagePreview.firstChild;\n canvas.remove();\n canvas.width = canvas.height = 0;\n this.#imageData = null;\n\n this.#toggleLoading(false);\n\n this.#uiManager?.addEditListeners();\n this.#currentEditor.altTextFinish();\n this.#uiManager?.setSelected(this.#currentEditor);\n this.#currentEditor = null;\n this.#uiManager = null;\n }\n\n #extractWords(text) {\n return new Set(\n text\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/gu)\n .filter(x => !!x)\n );\n }\n\n #save() {\n const altText = this.#textarea.value.trim();\n this.#currentEditor.altTextData = {\n altText,\n decorative: false,\n };\n this.#currentEditor.altTextData.guessedAltText = this.#guessedAltText;\n\n if (this.#guessedAltText && this.#guessedAltText !== altText) {\n const guessedWords = this.#extractWords(this.#guessedAltText);\n const words = this.#extractWords(altText);\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.user_edit\",\n data: {\n total_words: guessedWords.size,\n words_removed: guessedWords.difference(words).size,\n words_added: words.difference(guessedWords).size,\n },\n });\n }\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.image_added\",\n data: {\n alt_text_modal: true,\n alt_text_type: altText ? \"present\" : \"empty\",\n },\n });\n\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.save\",\n data: {\n alt_text_type: altText ? \"present\" : \"empty\",\n flow: this.#firstTime ? \"image_add\" : \"alt_text_edit\",\n },\n });\n\n this.#finish();\n }\n\n destroy() {\n this.#uiManager = null; // Avoid re-adding the edit listeners.\n this.#finish();\n }\n}\n\nclass ImageAltTextSettings {\n #aiModelSettings;\n\n #createModelButton;\n\n #downloadModelButton;\n\n #dialog;\n\n #eventBus;\n\n #mlManager;\n\n #overlayManager;\n\n #showAltTextDialogButton;\n\n constructor(\n {\n dialog,\n createModelButton,\n aiModelSettings,\n learnMore,\n closeButton,\n deleteModelButton,\n downloadModelButton,\n showAltTextDialogButton,\n },\n overlayManager,\n eventBus,\n mlManager\n ) {\n this.#dialog = dialog;\n this.#aiModelSettings = aiModelSettings;\n this.#createModelButton = createModelButton;\n this.#downloadModelButton = downloadModelButton;\n this.#showAltTextDialogButton = showAltTextDialogButton;\n this.#overlayManager = overlayManager;\n this.#eventBus = eventBus;\n this.#mlManager = mlManager;\n\n const { altTextLearnMoreUrl } = mlManager;\n if (altTextLearnMoreUrl) {\n learnMore.href = altTextLearnMoreUrl;\n }\n\n dialog.addEventListener(\"contextmenu\", noContextMenu);\n\n createModelButton.addEventListener(\"click\", async e => {\n const checked = this.#togglePref(\"enableGuessAltText\", e);\n await mlManager.toggleService(\"altText\", checked);\n this.#reportTelemetry({\n type: \"stamp\",\n action: \"pdfjs.image.alt_text.settings_ai_generation_check\",\n data: { status: checked },\n });\n });\n\n showAltTextDialogButton.addEventListener(\"click\", e => {\n const checked = this.#togglePref(\"enableNewAltTextWhenAddingImage\", e);\n this.#reportTelemetry({\n type: \"stamp\",\n action: \"pdfjs.image.alt_text.settings_edit_alt_text_check\",\n data: { status: checked },\n });\n });\n\n deleteModelButton.addEventListener(\"click\", this.#delete.bind(this, true));\n downloadModelButton.addEventListener(\n \"click\",\n this.#download.bind(this, true)\n );\n\n closeButton.addEventListener(\"click\", this.#finish.bind(this));\n\n learnMore.addEventListener(\"click\", () => {\n this.#reportTelemetry({\n type: \"stamp\",\n action: \"pdfjs.image.alt_text.info\",\n data: { topic: \"ai_generation\" },\n });\n });\n\n eventBus._on(\"enablealttextmodeldownload\", ({ value }) => {\n if (value) {\n this.#download(false);\n } else {\n this.#delete(false);\n }\n });\n\n this.#overlayManager.register(dialog);\n }\n\n #reportTelemetry(data) {\n this.#eventBus.dispatch(\"reporttelemetry\", {\n source: this,\n details: {\n type: \"editing\",\n data,\n },\n });\n }\n\n async #download(isFromUI = false) {\n if (isFromUI) {\n this.#downloadModelButton.disabled = true;\n const span = this.#downloadModelButton.firstChild;\n span.setAttribute(\n \"data-l10n-id\",\n \"pdfjs-editor-alt-text-settings-downloading-model-button\"\n );\n\n await this.#mlManager.downloadModel(\"altText\");\n\n span.setAttribute(\n \"data-l10n-id\",\n \"pdfjs-editor-alt-text-settings-download-model-button\"\n );\n\n this.#createModelButton.disabled = false;\n this.#setPref(\"enableGuessAltText\", true);\n this.#mlManager.toggleService(\"altText\", true);\n this.#setPref(\"enableAltTextModelDownload\", true);\n this.#downloadModelButton.disabled = false;\n }\n\n this.#aiModelSettings.classList.toggle(\"download\", false);\n this.#createModelButton.setAttribute(\"aria-pressed\", true);\n }\n\n async #delete(isFromUI = false) {\n if (isFromUI) {\n await this.#mlManager.deleteModel(\"altText\");\n this.#setPref(\"enableGuessAltText\", false);\n this.#setPref(\"enableAltTextModelDownload\", false);\n }\n\n this.#aiModelSettings.classList.toggle(\"download\", true);\n this.#createModelButton.disabled = true;\n this.#createModelButton.setAttribute(\"aria-pressed\", false);\n }\n\n async open({ enableGuessAltText, enableNewAltTextWhenAddingImage }) {\n const { enableAltTextModelDownload } = this.#mlManager;\n this.#createModelButton.disabled = !enableAltTextModelDownload;\n this.#createModelButton.setAttribute(\n \"aria-pressed\",\n enableAltTextModelDownload && enableGuessAltText\n );\n this.#showAltTextDialogButton.setAttribute(\n \"aria-pressed\",\n enableNewAltTextWhenAddingImage\n );\n this.#aiModelSettings.classList.toggle(\n \"download\",\n !enableAltTextModelDownload\n );\n\n await this.#overlayManager.open(this.#dialog);\n this.#reportTelemetry({\n type: \"stamp\",\n action: \"pdfjs.image.alt_text.settings_displayed\",\n });\n }\n\n #togglePref(name, { target }) {\n const checked = target.getAttribute(\"aria-pressed\") !== \"true\";\n this.#setPref(name, checked);\n target.setAttribute(\"aria-pressed\", checked);\n return checked;\n }\n\n #setPref(name, value) {\n this.#eventBus.dispatch(\"setpreference\", {\n source: this,\n name,\n value,\n });\n }\n\n #finish() {\n if (this.#overlayManager.active === this.#dialog) {\n this.#overlayManager.close(this.#dialog);\n }\n }\n}\n\nexport { ImageAltTextSettings, NewAltTextManager };\n","/* Copyright 2023 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DOMSVGFactory } from \"pdfjs-lib\";\n\nclass AltTextManager {\n #clickAC = null;\n\n #currentEditor = null;\n\n #cancelButton;\n\n #dialog;\n\n #eventBus;\n\n #hasUsedPointer = false;\n\n #optionDescription;\n\n #optionDecorative;\n\n #overlayManager;\n\n #saveButton;\n\n #textarea;\n\n #uiManager;\n\n #previousAltText = null;\n\n #resizeAC = null;\n\n #svgElement = null;\n\n #rectElement = null;\n\n #container;\n\n #telemetryData = null;\n\n constructor(\n {\n dialog,\n optionDescription,\n optionDecorative,\n textarea,\n cancelButton,\n saveButton,\n },\n container,\n overlayManager,\n eventBus\n ) {\n this.#dialog = dialog;\n this.#optionDescription = optionDescription;\n this.#optionDecorative = optionDecorative;\n this.#textarea = textarea;\n this.#cancelButton = cancelButton;\n this.#saveButton = saveButton;\n this.#overlayManager = overlayManager;\n this.#eventBus = eventBus;\n this.#container = container;\n\n const onUpdateUIState = this.#updateUIState.bind(this);\n\n dialog.addEventListener(\"close\", this.#close.bind(this));\n dialog.addEventListener(\"contextmenu\", event => {\n if (event.target !== this.#textarea) {\n event.preventDefault();\n }\n });\n cancelButton.addEventListener(\"click\", this.#finish.bind(this));\n saveButton.addEventListener(\"click\", this.#save.bind(this));\n optionDescription.addEventListener(\"change\", onUpdateUIState);\n optionDecorative.addEventListener(\"change\", onUpdateUIState);\n\n this.#overlayManager.register(dialog);\n }\n\n #createSVGElement() {\n if (this.#svgElement) {\n return;\n }\n\n // We create a mask to add to the dialog backdrop: the idea is to have a\n // darken background everywhere except on the editor to clearly see the\n // picture to describe.\n\n const svgFactory = new DOMSVGFactory();\n const svg = (this.#svgElement = svgFactory.createElement(\"svg\"));\n svg.setAttribute(\"width\", \"0\");\n svg.setAttribute(\"height\", \"0\");\n const defs = svgFactory.createElement(\"defs\");\n svg.append(defs);\n const mask = svgFactory.createElement(\"mask\");\n defs.append(mask);\n mask.setAttribute(\"id\", \"alttext-manager-mask\");\n mask.setAttribute(\"maskContentUnits\", \"objectBoundingBox\");\n let rect = svgFactory.createElement(\"rect\");\n mask.append(rect);\n rect.setAttribute(\"fill\", \"white\");\n rect.setAttribute(\"width\", \"1\");\n rect.setAttribute(\"height\", \"1\");\n rect.setAttribute(\"x\", \"0\");\n rect.setAttribute(\"y\", \"0\");\n\n rect = this.#rectElement = svgFactory.createElement(\"rect\");\n mask.append(rect);\n rect.setAttribute(\"fill\", \"black\");\n this.#dialog.append(svg);\n }\n\n async editAltText(uiManager, editor) {\n if (this.#currentEditor || !editor) {\n return;\n }\n this.#createSVGElement();\n\n this.#hasUsedPointer = false;\n\n this.#clickAC = new AbortController();\n const clickOpts = { signal: this.#clickAC.signal },\n onClick = this.#onClick.bind(this);\n for (const element of [\n this.#optionDescription,\n this.#optionDecorative,\n this.#textarea,\n this.#saveButton,\n this.#cancelButton,\n ]) {\n element.addEventListener(\"click\", onClick, clickOpts);\n }\n\n const { altText, decorative } = editor.altTextData;\n if (decorative === true) {\n this.#optionDecorative.checked = true;\n this.#optionDescription.checked = false;\n } else {\n this.#optionDecorative.checked = false;\n this.#optionDescription.checked = true;\n }\n this.#previousAltText = this.#textarea.value = altText?.trim() || \"\";\n this.#updateUIState();\n\n this.#currentEditor = editor;\n this.#uiManager = uiManager;\n this.#uiManager.removeEditListeners();\n\n this.#resizeAC = new AbortController();\n this.#eventBus._on(\"resize\", this.#setPosition.bind(this), {\n signal: this.#resizeAC.signal,\n });\n\n try {\n await this.#overlayManager.open(this.#dialog);\n this.#setPosition();\n } catch (ex) {\n this.#close();\n throw ex;\n }\n }\n\n #setPosition() {\n if (!this.#currentEditor) {\n return;\n }\n const dialog = this.#dialog;\n const { style } = dialog;\n const {\n x: containerX,\n y: containerY,\n width: containerW,\n height: containerH,\n } = this.#container.getBoundingClientRect();\n const { innerWidth: windowW, innerHeight: windowH } = window;\n const { width: dialogW, height: dialogH } = dialog.getBoundingClientRect();\n const { x, y, width, height } = this.#currentEditor.getClientDimensions();\n const MARGIN = 10;\n const isLTR = this.#uiManager.direction === \"ltr\";\n\n const xs = Math.max(x, containerX);\n const xe = Math.min(x + width, containerX + containerW);\n const ys = Math.max(y, containerY);\n const ye = Math.min(y + height, containerY + containerH);\n this.#rectElement.setAttribute(\"width\", `${(xe - xs) / windowW}`);\n this.#rectElement.setAttribute(\"height\", `${(ye - ys) / windowH}`);\n this.#rectElement.setAttribute(\"x\", `${xs / windowW}`);\n this.#rectElement.setAttribute(\"y\", `${ys / windowH}`);\n\n let left = null;\n let top = Math.max(y, 0);\n top += Math.min(windowH - (top + dialogH), 0);\n\n if (isLTR) {\n // Prefer to position the dialog \"after\" (so on the right) the editor.\n if (x + width + MARGIN + dialogW < windowW) {\n left = x + width + MARGIN;\n } else if (x > dialogW + MARGIN) {\n left = x - dialogW - MARGIN;\n }\n } else if (x > dialogW + MARGIN) {\n left = x - dialogW - MARGIN;\n } else if (x + width + MARGIN + dialogW < windowW) {\n left = x + width + MARGIN;\n }\n\n if (left === null) {\n top = null;\n left = Math.max(x, 0);\n left += Math.min(windowW - (left + dialogW), 0);\n if (y > dialogH + MARGIN) {\n top = y - dialogH - MARGIN;\n } else if (y + height + MARGIN + dialogH < windowH) {\n top = y + height + MARGIN;\n }\n }\n\n if (top !== null) {\n dialog.classList.add(\"positioned\");\n if (isLTR) {\n style.left = `${left}px`;\n } else {\n style.right = `${windowW - left - dialogW}px`;\n }\n style.top = `${top}px`;\n } else {\n dialog.classList.remove(\"positioned\");\n style.left = \"\";\n style.top = \"\";\n }\n }\n\n #finish() {\n if (this.#overlayManager.active === this.#dialog) {\n this.#overlayManager.close(this.#dialog);\n }\n }\n\n #close() {\n this.#currentEditor._reportTelemetry(\n this.#telemetryData || {\n action: \"alt_text_cancel\",\n alt_text_keyboard: !this.#hasUsedPointer,\n }\n );\n this.#telemetryData = null;\n\n this.#removeOnClickListeners();\n this.#uiManager?.addEditListeners();\n this.#resizeAC?.abort();\n this.#resizeAC = null;\n this.#currentEditor.altTextFinish();\n this.#currentEditor = null;\n this.#uiManager = null;\n }\n\n #updateUIState() {\n this.#textarea.disabled = this.#optionDecorative.checked;\n }\n\n #save() {\n const altText = this.#textarea.value.trim();\n const decorative = this.#optionDecorative.checked;\n this.#currentEditor.altTextData = {\n altText,\n decorative,\n };\n this.#telemetryData = {\n action: \"alt_text_save\",\n alt_text_description: !!altText,\n alt_text_edit:\n !!this.#previousAltText && this.#previousAltText !== altText,\n alt_text_decorative: decorative,\n alt_text_keyboard: !this.#hasUsedPointer,\n };\n this.#finish();\n }\n\n #onClick(evt) {\n if (evt.detail === 0) {\n return; // The keyboard was used.\n }\n this.#hasUsedPointer = true;\n this.#removeOnClickListeners();\n }\n\n #removeOnClickListeners() {\n this.#clickAC?.abort();\n this.#clickAC = null;\n }\n\n destroy() {\n this.#uiManager = null; // Avoid re-adding the edit listeners.\n this.#finish();\n this.#svgElement?.remove();\n this.#svgElement = this.#rectElement = null;\n }\n}\n\nexport { AltTextManager };\n","/* Copyright 2022 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./event_utils.js\").EventBus} EventBus */\n\nimport { AnnotationEditorParamsType } from \"pdfjs-lib\";\n\n/**\n * @typedef {Object} AnnotationEditorParamsOptions\n * @property {HTMLInputElement} editorFreeTextFontSize\n * @property {HTMLInputElement} editorFreeTextColor\n * @property {HTMLInputElement} editorInkColor\n * @property {HTMLInputElement} editorInkThickness\n * @property {HTMLInputElement} editorInkOpacity\n * @property {HTMLButtonElement} editorStampAddImage\n * @property {HTMLInputElement} editorFreeHighlightThickness\n * @property {HTMLButtonElement} editorHighlightShowAll\n */\n\nclass AnnotationEditorParams {\n /**\n * @param {AnnotationEditorParamsOptions} options\n * @param {EventBus} eventBus\n */\n constructor(options, eventBus) {\n this.eventBus = eventBus;\n this.#bindListeners(options);\n }\n\n /**\n * @param {AnnotationEditorParamsOptions} options\n */\n #bindListeners({\n editorFreeTextFontSize,\n editorFreeTextColor,\n editorInkColor,\n editorInkThickness,\n editorInkOpacity,\n editorStampAddImage,\n editorFreeHighlightThickness,\n editorHighlightShowAll,\n }) {\n const dispatchEvent = (typeStr, value) => {\n this.eventBus.dispatch(\"switchannotationeditorparams\", {\n source: this,\n type: AnnotationEditorParamsType[typeStr],\n value,\n });\n };\n editorFreeTextFontSize.addEventListener(\"input\", function () {\n dispatchEvent(\"FREETEXT_SIZE\", this.valueAsNumber);\n });\n editorFreeTextColor.addEventListener(\"input\", function () {\n dispatchEvent(\"FREETEXT_COLOR\", this.value);\n });\n editorInkColor.addEventListener(\"input\", function () {\n dispatchEvent(\"INK_COLOR\", this.value);\n });\n editorInkThickness.addEventListener(\"input\", function () {\n dispatchEvent(\"INK_THICKNESS\", this.valueAsNumber);\n });\n editorInkOpacity.addEventListener(\"input\", function () {\n dispatchEvent(\"INK_OPACITY\", this.valueAsNumber);\n });\n editorStampAddImage.addEventListener(\"click\", () => {\n this.eventBus.dispatch(\"reporttelemetry\", {\n source: this,\n details: {\n type: \"editing\",\n data: { action: \"pdfjs.image.add_image_click\" },\n },\n });\n dispatchEvent(\"CREATE\");\n });\n editorFreeHighlightThickness.addEventListener(\"input\", function () {\n dispatchEvent(\"HIGHLIGHT_THICKNESS\", this.valueAsNumber);\n });\n editorHighlightShowAll.addEventListener(\"click\", function () {\n const checked = this.getAttribute(\"aria-pressed\") === \"true\";\n this.setAttribute(\"aria-pressed\", !checked);\n dispatchEvent(\"HIGHLIGHT_SHOW_ALL\", !checked);\n });\n\n this.eventBus._on(\"annotationeditorparamschanged\", evt => {\n for (const [type, value] of evt.details) {\n switch (type) {\n case AnnotationEditorParamsType.FREETEXT_SIZE:\n editorFreeTextFontSize.value = value;\n break;\n case AnnotationEditorParamsType.FREETEXT_COLOR:\n editorFreeTextColor.value = value;\n break;\n case AnnotationEditorParamsType.INK_COLOR:\n editorInkColor.value = value;\n break;\n case AnnotationEditorParamsType.INK_THICKNESS:\n editorInkThickness.value = value;\n break;\n case AnnotationEditorParamsType.INK_OPACITY:\n editorInkOpacity.value = value;\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:\n editorFreeHighlightThickness.value = value;\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_FREE:\n editorFreeHighlightThickness.disabled = !value;\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:\n editorHighlightShowAll.setAttribute(\"aria-pressed\", value);\n break;\n }\n }\n });\n }\n}\n\nexport { AnnotationEditorParams };\n","/* Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Used to compare floats: there is no exact equality due to rounding errors.\nconst PRECISION = 1e-1;\n\nclass CaretBrowsingMode {\n #mainContainer;\n\n #toolBarHeight = 0;\n\n #viewerContainer;\n\n constructor(abortSignal, mainContainer, viewerContainer, toolbarContainer) {\n this.#mainContainer = mainContainer;\n this.#viewerContainer = viewerContainer;\n\n if (!toolbarContainer) {\n return;\n }\n this.#toolBarHeight = toolbarContainer.getBoundingClientRect().height;\n\n const toolbarObserver = new ResizeObserver(entries => {\n for (const entry of entries) {\n if (entry.target === toolbarContainer) {\n this.#toolBarHeight = Math.floor(entry.borderBoxSize[0].blockSize);\n break;\n }\n }\n });\n toolbarObserver.observe(toolbarContainer);\n\n abortSignal.addEventListener(\"abort\", () => toolbarObserver.disconnect(), {\n once: true,\n });\n }\n\n /**\n * Return true if the two rectangles are on the same line.\n * @param {DOMRect} rect1\n * @param {DOMRect} rect2\n * @returns {boolean}\n */\n #isOnSameLine(rect1, rect2) {\n const top1 = rect1.y;\n const bot1 = rect1.bottom;\n const mid1 = rect1.y + rect1.height / 2;\n\n const top2 = rect2.y;\n const bot2 = rect2.bottom;\n const mid2 = rect2.y + rect2.height / 2;\n\n return (top1 <= mid2 && mid2 <= bot1) || (top2 <= mid1 && mid1 <= bot2);\n }\n\n /**\n * Return `true` if the rectangle is:\n * - under the caret when `isUp === false`.\n * - over the caret when `isUp === true`.\n * @param {DOMRect} rect\n * @param {number} x\n * @param {number} y\n * @param {boolean} isUp\n * @returns {boolean}\n */\n #isUnderOver(rect, x, y, isUp) {\n const midY = rect.y + rect.height / 2;\n return (\n (isUp ? y >= midY : y <= midY) &&\n rect.x - PRECISION <= x &&\n x <= rect.right + PRECISION\n );\n }\n\n /**\n * Check if the rectangle is visible.\n * @param {DOMRect} rect\n * @returns {boolean}\n */\n #isVisible(rect) {\n return (\n rect.top >= this.#toolBarHeight &&\n rect.left >= 0 &&\n rect.bottom <=\n (window.innerHeight || document.documentElement.clientHeight) &&\n rect.right <= (window.innerWidth || document.documentElement.clientWidth)\n );\n }\n\n /**\n * Get the position of the caret.\n * @param {Selection} selection\n * @param {boolean} isUp\n * @returns {Array}\n */\n #getCaretPosition(selection, isUp) {\n const { focusNode, focusOffset } = selection;\n const range = document.createRange();\n range.setStart(focusNode, focusOffset);\n range.setEnd(focusNode, focusOffset);\n const rect = range.getBoundingClientRect();\n\n return [rect.x, isUp ? rect.top : rect.bottom];\n }\n\n static #caretPositionFromPoint(x, y) {\n if (\n (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) &&\n !document.caretPositionFromPoint\n ) {\n const { startContainer: offsetNode, startOffset: offset } =\n document.caretRangeFromPoint(x, y);\n return { offsetNode, offset };\n }\n return document.caretPositionFromPoint(x, y);\n }\n\n #setCaretPositionHelper(selection, caretX, select, element, rect) {\n rect ||= element.getBoundingClientRect();\n if (caretX <= rect.x + PRECISION) {\n if (select) {\n selection.extend(element.firstChild, 0);\n } else {\n selection.setPosition(element.firstChild, 0);\n }\n return;\n }\n if (rect.right - PRECISION <= caretX) {\n const { lastChild } = element;\n if (select) {\n selection.extend(lastChild, lastChild.length);\n } else {\n selection.setPosition(lastChild, lastChild.length);\n }\n return;\n }\n\n const midY = rect.y + rect.height / 2;\n let caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY);\n let parentElement = caretPosition.offsetNode?.parentElement;\n if (parentElement && parentElement !== element) {\n // There is an element on top of the one in the text layer, so we\n // need to hide all the elements (except the one in the text layer)\n // at this position in order to get the correct caret position.\n const elementsAtPoint = document.elementsFromPoint(caretX, midY);\n const savedVisibilities = [];\n for (const el of elementsAtPoint) {\n if (el === element) {\n break;\n }\n const { style } = el;\n savedVisibilities.push([el, style.visibility]);\n style.visibility = \"hidden\";\n }\n caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY);\n parentElement = caretPosition.offsetNode?.parentElement;\n for (const [el, visibility] of savedVisibilities) {\n el.style.visibility = visibility;\n }\n }\n if (parentElement !== element) {\n // The element targeted by caretPositionFromPoint isn't in the text\n // layer.\n if (select) {\n selection.extend(element.firstChild, 0);\n } else {\n selection.setPosition(element.firstChild, 0);\n }\n return;\n }\n if (select) {\n selection.extend(caretPosition.offsetNode, caretPosition.offset);\n } else {\n selection.setPosition(caretPosition.offsetNode, caretPosition.offset);\n }\n }\n\n /**\n * Set the caret position or extend the selection (it depends on the select\n * parameter).\n * @param {boolean} select\n * @param {Selection} selection\n * @param {Element} newLineElement\n * @param {DOMRect} newLineElementRect\n * @param {number} caretX\n */\n #setCaretPosition(\n select,\n selection,\n newLineElement,\n newLineElementRect,\n caretX\n ) {\n if (this.#isVisible(newLineElementRect)) {\n this.#setCaretPositionHelper(\n selection,\n caretX,\n select,\n newLineElement,\n newLineElementRect\n );\n return;\n }\n this.#mainContainer.addEventListener(\n \"scrollend\",\n this.#setCaretPositionHelper.bind(\n this,\n selection,\n caretX,\n select,\n newLineElement,\n null\n ),\n { once: true }\n );\n newLineElement.scrollIntoView();\n }\n\n /**\n * Get the node on the next page.\n * @param {Element} textLayer\n * @param {boolean} isUp\n * @returns {Node}\n */\n #getNodeOnNextPage(textLayer, isUp) {\n while (true) {\n const page = textLayer.closest(\".page\");\n const pageNumber = parseInt(page.getAttribute(\"data-page-number\"));\n const nextPage = isUp ? pageNumber - 1 : pageNumber + 1;\n textLayer = this.#viewerContainer.querySelector(\n `.page[data-page-number=\"${nextPage}\"] .textLayer`\n );\n if (!textLayer) {\n return null;\n }\n const walker = document.createTreeWalker(textLayer, NodeFilter.SHOW_TEXT);\n const node = isUp ? walker.lastChild() : walker.firstChild();\n if (node) {\n return node;\n }\n }\n }\n\n /**\n * Move the caret in the given direction.\n * @param {boolean} isUp\n * @param {boolean} select\n */\n moveCaret(isUp, select) {\n const selection = document.getSelection();\n if (selection.rangeCount === 0) {\n return;\n }\n const { focusNode } = selection;\n const focusElement =\n focusNode.nodeType !== Node.ELEMENT_NODE\n ? focusNode.parentElement\n : focusNode;\n const root = focusElement.closest(\".textLayer\");\n if (!root) {\n return;\n }\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n walker.currentNode = focusNode;\n\n // Move to the next element which is not on the same line as the focus\n // element.\n const focusRect = focusElement.getBoundingClientRect();\n let newLineElement = null;\n const nodeIterator = (\n isUp ? walker.previousSibling : walker.nextSibling\n ).bind(walker);\n while (nodeIterator()) {\n const element = walker.currentNode.parentElement;\n if (!this.#isOnSameLine(focusRect, element.getBoundingClientRect())) {\n newLineElement = element;\n break;\n }\n }\n\n if (!newLineElement) {\n // Need to find the next line on the next page.\n const node = this.#getNodeOnNextPage(root, isUp);\n if (!node) {\n return;\n }\n if (select) {\n const lastNode =\n (isUp ? walker.firstChild() : walker.lastChild()) || focusNode;\n selection.extend(lastNode, isUp ? 0 : lastNode.length);\n const range = document.createRange();\n range.setStart(node, isUp ? node.length : 0);\n range.setEnd(node, isUp ? node.length : 0);\n selection.addRange(range);\n return;\n }\n const [caretX] = this.#getCaretPosition(selection, isUp);\n const { parentElement } = node;\n this.#setCaretPosition(\n select,\n selection,\n parentElement,\n parentElement.getBoundingClientRect(),\n caretX\n );\n return;\n }\n\n // We've a candidate for the next line now we want to find the first element\n // which is under/over the caret.\n const [caretX, caretY] = this.#getCaretPosition(selection, isUp);\n const newLineElementRect = newLineElement.getBoundingClientRect();\n\n // Maybe the element on the new line is a valid candidate.\n if (this.#isUnderOver(newLineElementRect, caretX, caretY, isUp)) {\n this.#setCaretPosition(\n select,\n selection,\n newLineElement,\n newLineElementRect,\n caretX\n );\n return;\n }\n\n while (nodeIterator()) {\n // Search an element on the same line as newLineElement\n // which could be under/over the caret.\n const element = walker.currentNode.parentElement;\n const elementRect = element.getBoundingClientRect();\n if (!this.#isOnSameLine(newLineElementRect, elementRect)) {\n break;\n }\n if (this.#isUnderOver(elementRect, caretX, caretY, isUp)) {\n // We found the element.\n this.#setCaretPosition(select, selection, element, elementRect, caretX);\n return;\n }\n }\n\n // No element has been found so just put the caret on the element on the new\n // line.\n this.#setCaretPosition(\n select,\n selection,\n newLineElement,\n newLineElementRect,\n caretX\n );\n }\n}\n\nexport { CaretBrowsingMode };\n","/* Copyright 2013 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./interfaces\").IDownloadManager} IDownloadManager */\n\nimport { createValidAbsoluteUrl, isPdfFile } from \"pdfjs-lib\";\n\nif (typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"CHROME || GENERIC\")) {\n throw new Error(\n 'Module \"pdfjs-web/download_manager\" shall not be used ' +\n \"outside CHROME and GENERIC builds.\"\n );\n}\n\nfunction download(blobUrl, filename) {\n const a = document.createElement(\"a\");\n if (!a.click) {\n throw new Error('DownloadManager: \"a.click()\" is not supported.');\n }\n a.href = blobUrl;\n a.target = \"_parent\";\n // Use a.download if available. This increases the likelihood that\n // the file is downloaded instead of opened by another PDF plugin.\n if (\"download\" in a) {\n a.download = filename;\n }\n // must be in the document for recent Firefox versions,\n // otherwise .click() is ignored.\n (document.body || document.documentElement).append(a);\n a.click();\n a.remove();\n}\n\n/**\n * @implements {IDownloadManager}\n */\nclass DownloadManager {\n #openBlobUrls = new WeakMap();\n\n downloadData(data, filename, contentType) {\n const blobUrl = URL.createObjectURL(\n new Blob([data], { type: contentType })\n );\n download(blobUrl, filename);\n }\n\n /**\n * @returns {boolean} Indicating if the data was opened.\n */\n openOrDownloadData(data, filename, dest = null) {\n const isPdfData = isPdfFile(filename);\n const contentType = isPdfData ? \"application/pdf\" : \"\";\n\n if (\n (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"COMPONENTS\")) &&\n isPdfData\n ) {\n let blobUrl = this.#openBlobUrls.get(data);\n if (!blobUrl) {\n blobUrl = URL.createObjectURL(new Blob([data], { type: contentType }));\n this.#openBlobUrls.set(data, blobUrl);\n }\n let viewerUrl;\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n // The current URL is the viewer, let's use it and append the file.\n viewerUrl = \"?file=\" + encodeURIComponent(blobUrl + \"#\" + filename);\n } else if (PDFJSDev.test(\"CHROME\")) {\n // In the Chrome extension, the URL is rewritten using the history API\n // in viewer.js, so an absolute URL must be generated.\n viewerUrl =\n // eslint-disable-next-line no-undef\n chrome.runtime.getURL(\"/content/web/viewer.html\") +\n \"?file=\" +\n encodeURIComponent(blobUrl + \"#\" + filename);\n }\n if (dest) {\n viewerUrl += `#${escape(dest)}`;\n }\n\n try {\n window.open(viewerUrl);\n return true;\n } catch (ex) {\n console.error(\"openOrDownloadData:\", ex);\n // Release the `blobUrl`, since opening it failed, and fallback to\n // downloading the PDF file.\n URL.revokeObjectURL(blobUrl);\n this.#openBlobUrls.delete(data);\n }\n }\n\n this.downloadData(data, filename, contentType);\n return false;\n }\n\n download(data, url, filename) {\n let blobUrl;\n if (data) {\n blobUrl = URL.createObjectURL(\n new Blob([data], { type: \"application/pdf\" })\n );\n } else {\n if (!createValidAbsoluteUrl(url, \"http://example.com\")) {\n console.error(`download - not a valid URL: ${url}`);\n return;\n }\n blobUrl = url + \"#pdfjs.action=download\";\n }\n download(blobUrl, filename);\n }\n}\n\nexport { DownloadManager };\n","/* Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { noContextMenu } from \"pdfjs-lib\";\n\nclass EditorUndoBar {\n #closeButton = null;\n\n #container;\n\n #eventBus = null;\n\n #focusTimeout = null;\n\n #initController = null;\n\n isOpen = false;\n\n #message;\n\n #showController = null;\n\n #undoButton;\n\n static #l10nMessages = Object.freeze({\n highlight: \"pdfjs-editor-undo-bar-message-highlight\",\n freetext: \"pdfjs-editor-undo-bar-message-freetext\",\n stamp: \"pdfjs-editor-undo-bar-message-stamp\",\n ink: \"pdfjs-editor-undo-bar-message-ink\",\n _multiple: \"pdfjs-editor-undo-bar-message-multiple\",\n });\n\n constructor({ container, message, undoButton, closeButton }, eventBus) {\n this.#container = container;\n this.#message = message;\n this.#undoButton = undoButton;\n this.#closeButton = closeButton;\n this.#eventBus = eventBus;\n }\n\n destroy() {\n this.#initController?.abort();\n this.#initController = null;\n\n this.hide();\n }\n\n show(undoAction, messageData) {\n if (!this.#initController) {\n this.#initController = new AbortController();\n const opts = { signal: this.#initController.signal };\n const boundHide = this.hide.bind(this);\n\n this.#container.addEventListener(\"contextmenu\", noContextMenu, opts);\n this.#closeButton.addEventListener(\"click\", boundHide, opts);\n this.#eventBus._on(\"beforeprint\", boundHide, opts);\n this.#eventBus._on(\"download\", boundHide, opts);\n }\n\n this.hide();\n\n if (typeof messageData === \"string\") {\n this.#message.setAttribute(\n \"data-l10n-id\",\n EditorUndoBar.#l10nMessages[messageData]\n );\n } else {\n this.#message.setAttribute(\n \"data-l10n-id\",\n EditorUndoBar.#l10nMessages._multiple\n );\n this.#message.setAttribute(\n \"data-l10n-args\",\n JSON.stringify({ count: messageData })\n );\n }\n this.isOpen = true;\n this.#container.hidden = false;\n\n this.#showController = new AbortController();\n\n this.#undoButton.addEventListener(\n \"click\",\n () => {\n undoAction();\n this.hide();\n },\n { signal: this.#showController.signal }\n );\n\n // Without the setTimeout, VoiceOver will read out the document title\n // instead of the popup label.\n this.#focusTimeout = setTimeout(() => {\n this.#container.focus();\n this.#focusTimeout = null;\n }, 100);\n }\n\n hide() {\n if (!this.isOpen) {\n return;\n }\n this.isOpen = false;\n this.#container.hidden = true;\n\n this.#showController?.abort();\n this.#showController = null;\n\n if (this.#focusTimeout) {\n clearTimeout(this.#focusTimeout);\n this.#focusTimeout = null;\n }\n }\n}\n\nexport { EditorUndoBar };\n","/* Copyright 2014 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nclass OverlayManager {\n #overlays = new WeakMap();\n\n #active = null;\n\n get active() {\n return this.#active;\n }\n\n /**\n * @param {HTMLDialogElement} dialog - The overlay's DOM element.\n * @param {boolean} [canForceClose] - Indicates if opening the overlay closes\n * an active overlay. The default is `false`.\n * @returns {Promise} A promise that is resolved when the overlay has been\n * registered.\n */\n async register(dialog, canForceClose = false) {\n if (typeof dialog !== \"object\") {\n throw new Error(\"Not enough parameters.\");\n } else if (this.#overlays.has(dialog)) {\n throw new Error(\"The overlay is already registered.\");\n }\n this.#overlays.set(dialog, { canForceClose });\n\n dialog.addEventListener(\"cancel\", evt => {\n this.#active = null;\n });\n }\n\n /**\n * @param {HTMLDialogElement} dialog - The overlay's DOM element.\n * @returns {Promise} A promise that is resolved when the overlay has been\n * opened.\n */\n async open(dialog) {\n if (!this.#overlays.has(dialog)) {\n throw new Error(\"The overlay does not exist.\");\n } else if (this.#active) {\n if (this.#active === dialog) {\n throw new Error(\"The overlay is already active.\");\n } else if (this.#overlays.get(dialog).canForceClose) {\n await this.close();\n } else {\n throw new Error(\"Another overlay is currently active.\");\n }\n }\n this.#active = dialog;\n dialog.showModal();\n }\n\n /**\n * @param {HTMLDialogElement} dialog - The overlay's DOM element.\n * @returns {Promise} A promise that is resolved when the overlay has been\n * closed.\n */\n async close(dialog = this.#active) {\n if (!this.#overlays.has(dialog)) {\n throw new Error(\"The overlay does not exist.\");\n } else if (!this.#active) {\n throw new Error(\"The overlay is currently not active.\");\n } else if (this.#active !== dialog) {\n throw new Error(\"Another overlay is currently active.\");\n }\n dialog.close();\n this.#active = null;\n }\n}\n\nexport { OverlayManager };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./overlay_manager.js\").OverlayManager} OverlayManager */\n\nimport { PasswordResponses } from \"pdfjs-lib\";\n\n/**\n * @typedef {Object} PasswordPromptOptions\n * @property {HTMLDialogElement} dialog - The overlay's DOM element.\n * @property {HTMLParagraphElement} label - Label containing instructions for\n * entering the password.\n * @property {HTMLInputElement} input - Input field for entering the password.\n * @property {HTMLButtonElement} submitButton - Button for submitting the\n * password.\n * @property {HTMLButtonElement} cancelButton - Button for cancelling password\n * entry.\n */\n\nclass PasswordPrompt {\n #activeCapability = null;\n\n #updateCallback = null;\n\n #reason = null;\n\n /**\n * @param {PasswordPromptOptions} options\n * @param {OverlayManager} overlayManager - Manager for the viewer overlays.\n * @param {boolean} [isViewerEmbedded] - If the viewer is embedded, in e.g.\n * an